Entity Class
Entity is part of the KBEngine module. More...
import KBEngine
Member Functions
def accelerate( self, accelerateType, acceleration ):
def addYawRotator( self, targetYaw, velocity, userArg ):
def addProximity( self, range, userArg ):
def addTimer( self, start, interval=0.0, userData=0 ):
def cancelController( self, controllerID ):
def clientEntity( self, destID ):
def canNavigate( self ):
def debugView( self ):
def delTimer( self, id ):
def destroy( self ):
def destroySpace( self ):
def entitiesInView( self, pending):
def entitiesInRange( self, range, entityType=None, position=None ):
def isReal( self ):
def moveToEntity( self, destEntityID, velocity, distance, userData, faceMovement, moveVertically, offsetPos ):
def moveToPoint( self, destination, velocity, distance, userData, faceMovement, moveVertically ):
def getViewRadius( self ):
def getViewHystArea( self ):
def getRandomPoints( self, centerPos, maxRadius, maxPoints, layer ):
def navigate( self, destination, velocity, distance, maxMoveDistance, maxSearchDistance, faceMovement, layer, userData ):
def navigatePathPoints( self, destination, maxSearchDistance, layer ):
def setViewRadius( self, radius, hyst=5 ):
def teleport( self, nearbyMBRef, position, direction ):
def writeToDB( self, shouldAutoLoad, dbInterfaceName ):
def getWitnesses( self ):
def getComponent( self, componentName, all ):
def fireEvent( self, eventName, *args ):
def registerEvent( self, eventName, callback ):
def deregisterEvent( self, eventName, callback ):
Callback Functions
def onDestroy( self ):
def onEnterTrap( self, entity, rangeXZ, rangeY, controllerID, userArg ):
def onEnteredView( self, entity ):
def onGetWitness( self ):
def onLeaveTrap( self, entity, rangeXZ, rangeY, controllerID, userArg ):
def onLoseControlledBy( self, id ):
def onLoseWitness( self ):
def onMove( self, controllerID, userData ):
def onMoveOver( self, controllerID, userData ):
def onMoveFailure( self, controllerID, userData ):
def onRestore( self ):
def onSpaceGone( self ):
def onTurn( self, controllerID, userData ):
def onTeleport( self ):
def onTeleportFailure( self ):
def onTeleportSuccess( self, nearbyEntity ):
def onTimer( self, timerHandle, userData ):
def onUpdateBegin( self ):
def onUpdateEnd( self ):
def onWitnessed( self, isWitnessed ):
def onWriteToDB( self ):
Properties
allClients read-only PyClient
base read-only BaseEntityCall
client read-only ClientEntityCall
direction Tuple of 3 floats as (roll, pitch, yaw)
hasWitness boolean
id read-only Integer
isDestroyed read-only bool
isOnGround read-only bool
isWitnessed read-only bool
layer int8
otherClients read-only PyClient
spaceID read-only uint32
topSpeed float
topSpeedY float
volatileInfo float
Detailed Description
An instance of the Entity class represents a game object on the cell. An Entity can be "real" or "ghosted". A "ghost" Entity is a copy of a "real" Entity that lives on a neighboring cell. For each entity, there is a unique "real" Entity instance, and zero or more "ghost" Entity instances.
An Entity instance controls the entity's position data, including its space and rotation. It also controls the frequency at which this data is sent to the client (if applicable). Position data can be updated by the unique client, by controller objects, or by the teleport member function. Controllers are non-python objects that can be used on cell entities to change their position data over time. They can be added to Entity via member functions such as "trackEntity" and "turnToYaw", and can be removed via "cancelController".
The area of interest, or "View", is an important concept for all KBEngine entities belonging to a client. An entity's View is the area around the entity that the client (if it has one) can perceive. This is used to select the amount of data sent to the client. The actual shape of the View is defined by the distance range on the x and z axes, plus a hysteresis area extending outward. An Entity enters another Entity's View, but does not leave it until it leaves the hysteresis area. An Entity can modify its View size via "setViewRadius". You can use "entitiesInRange" to find all entities within a certain distance, and use "addProximity" to set a trap to capture all entities entering the trap.
A new Entity on cellApp can be created using KBEngine.createEntity. An entity can also be created via remote call from baseApp using KBEngine.createCellEntity.
An Entity can access its equivalent entity on the base and client applications via ENTITYCALL. This requires a set of remote call functions (specified in the entity's .def file).
Member Function Documentation
def accelerate( self, accelerateType, acceleration ):
Function Description:
Accelerate the entity's current movement.
Movements that can be affected include:
Parameters:
accelerateType
: string, the type of movement to be affected, such as: Movement, Turn.
velocity
: float, acceleration in units per second, negative value indicates deceleration.
Returns:
The entity's current speed after the effect.
def addYawRotator( self, targetYaw, velocity, userArg ):
Function Description:
Control the entity's rotation around the yaw axis. Completion of the rotation will be notified via Entity.onTurn.
Use Entity.cancelController with the controller ID, or Entity.cancelController("Movement") to remove it.
See Also:
Parameters:
targetYaw
: float, the target yaw angle in radians.
velocity
: float, the angular velocity in radians per second.
userArg
: An optional integer, shared by all controllers. If this value is not 0, it will be passed to the callback function. It is recommended to set the default value to 0 in the callback prototype.
def addProximity( self, rangeXZ, rangeY, userArg ):
Function Description:
Create a range trigger. When other entities enter or leave this trigger area, the Entity is notified. The area is square (for efficiency). If another entity is within the given distance on both the x and z axes, it is considered within range. The Entity is notified via the onEnterTrap and onLeaveTrap functions, which can be defined as follows:
def onEnterTrap( self, entityEntering, rangeXZ, rangeY, controllerID, userArg = 0 ):
def onLeaveTrap( self, entityLeaving, rangeXZ, rangeY, controllerID, userArg = 0 ):
Since this range trigger is a controller, use Entity.cancelController with the controller ID to remove it.
Note that the callback may be triggered immediately, even before the addProximity() call returns.
See Also:
Parameters:
rangeXZ
: float, the size of the trigger area on the xz plane, must be greater than or equal to 0.
rangeY
: float, the height of the trigger area on the y axis, must be greater than or equal to 0.
Note that for this parameter to take effect, the kbengine_defaults.xml -> cellapp-> coordinate_system -> rangemgr_y must be enabled. Enabling y-axis management may incur some overhead, as in some games, many entities are at the same y-axis height or nearly the same horizontal line height, making collisions very dense.
3D space games or games with few entities like small rooms are more suitable for this option.
userArg
: An optional integer, shared by all controllers. If this value is not 0, it will be passed to the callback function. It is recommended to set the default value to 0 in the callback prototype.
Returns:
Returns the ID of the created controller.
def addTimer( self, start, interval=0.0, userData=0 ):
Function Description:
Register a timer. The timer is triggered by the callback function onTimer The callback function will be executed for the first time after "initialOffset" seconds, and then every "repeatOffset" seconds. A user parameter "userArg" (limited to integer type) can be set.
onTimer The function must be defined in the cell part of the entity and must have 2 parameters. The first is an integer type timer ID (which can be used to remove the timer with the "delTimer" function), and the second is the user parameter "userArg".
Example:
# Here is an example of using addTimer
import KBEngine
class MyCellEntity( KBEngine.Entity ):
def __init__( self ):
KBEngine.Entity.__init__( self )
# Add a timer, executed for the first time after 5 seconds, and then every 1 second, the user parameter is 9
self.addTimer( 5, 1, 9 )
# Add a timer, executed after 1 second, the user parameter is 0 by default
self.addTimer( 1 )
# The entity's timer callback "onTimer" is called
def onTimer( self, id, userArg ):
print "MyCellEntity.onTimer called: id %i, userArg: %i" % ( id, userArg )
# if this is a repeating timer, when the timer is no longer needed, call the following function to remove it:
# self.delTimer( id )
Parameters:
initialOffset
: float, specifies the time interval (in seconds) from registration to the first callback of the timer.
repeatOffset
: float, specifies the time interval (in seconds) for each execution after the first callback. It must be removed with the delTimer function, otherwise, it will continue to repeat. Values less than or equal to 0 will be ignored.
userArg
: integer, specifies the userArg parameter value when the underlying callback "onTimer" is called.
Returns:
integer, this function returns the internal ID of the timer, which can be used to remove the timer with delTimer.
def cancelController( self, controllerID ):
Function Description:
The cancelController function stops a controller from affecting the Entity. It can only be called on a real entity.
Parameters:
controllerID
: controllerID is the index of the controller to be canceled, which is an integer. A dedicated controller type string can also be used as its type. For example, only one move/navigation controller can be activated at a time, which can be canceled with entity.cancelController( "Movement" ).
def clientEntity( self, destID ):
Function Description:
This method allows access to the methods of a certain entity in its own client (the current entity must be bound to a client), only entities within the View range will be synchronized to the client. It can only be called on a real entity.
Parameters:
destID
: The ID of the target entity.
def canNavigate( self ):
Function Description:
This method determines whether the current entity can use the navigation (Entity.navigate ) function. It can only be called on a real entity.
Typically, this function is available when the Space where the entity is located has loaded valid navigation collision data (Navmesh or 2D tile data) using Entity.addSpaceGeometryMapping , and the entity is in a valid navigation area.
Returns:
bool, returns True if the entity can use the navigation function in the current Space, otherwise returns False.
def debugView( self ):
Function Description:
debugView outputs detailed information about the Entity's View to the cell's debug log. A description of how the View system works can be found in the Entity class documentation.
A sample output is as follows:
INFO cellapp [0x00001a1c] [2014-11-04 00:28:41,409] - Avatar::debugView: 100 size=4, Seen=4, Pending=0, ViewRadius=50.000, ViewHyst=5.000
INFO cellapp [0x00001a1c] [2014-11-04 00:28:41,409] - Avatar::debugView: 100 Avatar(102), position(771.586.211.002.776.55), dist=0
INFO cellapp [0x00001a1c] [2014-11-04 00:28:41,409] - Avatar::debugView: 100 Monster(1028), position(820.834.211.635.768.749), dist=49.8659
INFO cellapp [0x00001a1c] [2014-11-04 00:28:41,409] - Avatar::debugView: 100 NPC(1025), position(784.024.210.95.782.273), dist=13.6915
INFO cellapp [0x00001a1c] [2014-11-04 00:28:41,409] - Avatar::debugView: 100 Avatar(106), position(771.586.211.002.776.55), dist=0
The first line of information tells us:
- Data for entity #1000
- There are 4 entities in its View area that have been synchronized to the client.
- There are 0 entities in its View area that are waiting to be synchronized to the client.
- The View radius is 50.000
- The hysteresis area of the View extends outward by 5.000
def delTimer( self, id ):
Function Description:
The delTimer function is used to remove a registered timer, and the removed timer will no longer execute. Timers that execute only once will be automatically removed after executing the callback, and do not need to be removed with delTimer. Using the delTimer function with an invalid ID (e.g., already removed) will cause an error.
Parameters:
id
: integer, specifies the ID of the timer to be removed. If the parameter is the string "All", all timers will be removed at once.
def destroy( self ):
Function Description:
This function destroys its local Entity instance. If the entity exists on other processes as a ghost , it will also notify the destruction of the ghost part. This function is best called by the entity itself. If the entity is a ghost, an exception will be thrown. If the callback function onDestroy() is implemented, it will be called.
def destroySpace( self ):
Function Description:
Destroy the space where this entity is located.
def entitiesInView( self, pending ):
Function Description:
Get the list of entities within the View range of this entity.
Parameters:
pending
: bool, optional, default value is False, returns all entities visible to the client, otherwise returns all entities visible on the server but not yet synchronized to the client.
def entitiesInRange( self, range, entityType=None, position=None ):
Function Description:
Search for entities within a given distance. This is a spherical search, measuring the distance on all 3 axes. It can find entities outside the View range of this Entity, but cannot find entities from other cells.
Examples:
self.entitiesInRange( 100, 'Creature', (100, 0, 100) )
Search for a list of entities of type 'Creature' (instances of the 'Creature' subclass). The center point is (100, 0, 100), and the search radius is 100 meters.
[ e for e in self.entitiesInRange( 100, None, (100,0,100) ) if isinstance( e, BaseType ) ]
This will give a list of entities instantiated from 'BaseType' or its subclasses.
Parameters:
range
: The distance to search around this entity, of type float
entityType
: An optional string parameter, the entity type name, used to match entities. If the entity type is a valid class name (listed in res/scripts/entities.xml ), only entities of this type will be returned, otherwise, all entities within this range will be returned.
position
: An optional parameter of type Vector3, used as the center of the search radius, default is the entity itself.
Returns:
A list of Entity objects within the given range.
def isReal( self ):
Function Description:
This function returns whether this Entity is real or a ghost.
This function is rarely used but is useful for debugging.
Returns:
bool, returns True if it is a real entity, otherwise returns False.
def moveToEntity( self, destEntityID, velocity, distance, userData, faceMovement, moveVertically, offsetPos ):
Function Description:
Move the Entity in a straight line to the position of another Entity .
Any Entity can only have one move controller at any time, and calling any move function repeatedly will terminate the previous move controller.
It returns a controller ID that can be used to cancel this move, for example, Entity.cancelController(movementID ).
Move cancellation can also be done by calling Entity.cancelController("Movement" ). Once the move is canceled, the callback notification methods will not be called.
def onMove( self, controllerID, userData ):
def onMoveOver( self, controllerID, userData ):
def onMoveFailure( self, controllerID, userData ):
See Also:
Parameters:
destEntityID
: int, the ID of the target Entity
velocity
: float, the speed of the Entity, in m/s
distance
: float, stop moving if the distance to the target is less than this value, if this value is 0, move to the target position.
userData
: object, optional, the value of userData will be this value when the callback notification is called.
faceMovement
: bool, optional, true if the entity faces the direction of movement, false if it is another mechanism.
moveVertically
: bool, optional, set to True for straight-line movement, set to False for ground-aligned straight-line movement.
offsetPos
: Vector3, optional, set a certain offset, for example, to make the movement target position to the left of the entity.
Returns:
int, the newly created controller ID.
def moveToPoint( self, destination, velocity, distance, userData, faceMovement, moveVertically ):
Function Description:
Move the Entity in a straight line to a given coordinate point. Success or failure will call the callback function.
Any Entity can only have one move controller at any time, and calling any move function repeatedly will terminate the previous move controller.
It returns a controller ID that can be used to cancel this move.
For example:
Entity.cancelController( movementID )。 Move cancellation can also be done by calling Entity.cancelController( "Movement" )。Once the move is canceled, the notification method will not be called.
The callback function is defined as follows:
def onMove( self, controllerID, userData ):
def onMoveOver( self, controllerID, userData ):
def onMoveFailure( self, controllerID, userData ):
See Also:
Parameters:
destination
: Vector3, the target position point for the Entity to move to
velocity
: float, the movement speed of the Entity, in m/s
distance
: float, stop moving if the distance to the target is less than this value, if this value is 0, move to the target position.
userData
: object, the data passed to the notification function
faceMovement
: bool, true if the entity faces the direction of movement, false if it is another mechanism.
moveVertically
: bool, true for straight-line movement, false for ground-aligned movement.
Returns:
int, the newly created controller ID.
def getViewRadius( self ):
Function Description:
This function returns the current View radius value of this Entity.
The data can be set by Entity.setViewRadius( radius, hyst ).
Returns:
float, View radius.
def getViewHystArea( self ):
Function Description:
This function returns the current hysteresis area value of this Entity's View.
The data can be set by Entity.setViewRadius( radius, hyst ).
Returns:
float, current hysteresis area value of the View.
def getRandomPoints( self, centerPos, maxRadius, maxPoints, layer ):
Function Description:
This function is used to obtain random coordinate points that can be reached by Entity.navigate within a certain area centered around a certain coordinate point.
Parameters:
centerPos
: Vector3, the central coordinate point of the Entity
maxRadius
: float, the maximum search radius
maxPoints
: uint32, the maximum number of random coordinate points to be returned.
layer
: int8, use the navmesh of a certain layer for searching.
Returns:
tuple, an array containing one or more coordinates.
def navigate( _self, destination, velocity, distance, maxMoveDistance, maxSearchDistance, faceMovement, layer,
userData_ ):
Function Description:
Use the navigation system to move this Entity to a target point. Success or failure will call the callback function.
KBEngine can have several pre-generated navigation meshes, with different mesh sizes (leading to different navigation paths).
Any Entity can only have one move controller at any time, and calling any move function repeatedly will terminate the previous move controller.
It returns a controller ID that can be used to cancel this move.
For example:
Entity.cancelController( movementID )。 Move cancellation can also be done by calling Entity.cancelController( "Movement" )。Once the move is canceled, the notification method will not be called.
The callback function is defined as follows:
def onMove( self, controllerID, userData ):
def onMoveOver( self, controllerID, userData ):
def onMoveFailure( self, controllerID, userData ):
See Also:
Parameters:
destination
: Vector3, the target point for the Entity to move to.
velocity
: float, the movement speed of the Entity, in m/s
distance
: float, stop moving if the distance to the target is less than this value, if this value is 0, move to the target position.
maxMoveDistance
: float, the maximum move distance.
maxSearchDistance
: float, the maximum search distance from the navigation data.
faceMovement
: bool, true if the entity faces the direction of movement (default). False if it is another mechanism.
layer
: int8, use the navmesh of a certain layer for pathfinding.
userData
: object, the data passed to the notification function.
Returns:
int, the newly created controller ID.
def navigatePathPoints( self, destination, maxSearchDistance, layer ):
Function Description:
This function returns a list of path points from the current position of the Entity to the destination.
Parameters:
destination
: Vector3, the target point for the Entity to move to
maxSearchDistance
: float, the maximum search distance
layer
: int8, use the navmesh of a certain layer to find the list of path points.
def setViewRadius( self, radius, hyst=5 ):
Function Description:
Specify the size of the area of interest for the Entity.
This function can only be used for entities associated with a Witness.
Note: You can set the default View radius by configuring the 'cellapp/defaultViewRadius' option in the kbengine.xml configuration file.
The default View radius should not be greater than 500.0. For details, see the configuration option 'cellapp/entity_posdir_updates' in kbengine_defaults.xml .
The data can be obtained through Entity.getViewRadius( ) and Entity.getViewHystArea( ).
Parameters:
radius
: float, specifies the radius of the View area
hyst
: float, specifies the size of the hysteresis area that extends beyond the View area. Properly setting the hysteresis area can reduce the sensitivity of View collisions and improve CPU execution efficiency.
An entity must cross the View radius area to enter another entity's View, but to leave the View area, it must move out of both the View radius area and the hysteresis area.
Returns:
None
def teleport( self, nearbyMBRef, position, direction ):
Function Description:
Instantly move an Entity to a specified space. This function allows specifying the position and orientation of the entity after the move.
If you need to jump between different spaces (usually for scene or room transitions), you can pass a CellEntityCall to this function (the entity corresponding to this entityCall must be in the destination space ).
This function can only be called on real entities.
Parameters:
nearbyMBRef
: A CellEntityCall that determines which Space the Entity will jump to (the entity corresponding to this entityCall must be in the destination Space ). It is considered the teleport destination. This can be set to None, in which case the teleport will be completed in the current cell.
position
: The coordinates of the Entity after the teleport, as a sequence of 3 floats (x, y, z).
direction
: The orientation of the Entity after the teleport, as a sequence of 3 floats (roll, pitch, yaw).
def writeToDB( self, shouldAutoLoad, dbInterfaceName ):
Function Description:
This function saves data related to this entity to the database, including base entity data. The base entity's onWriteToDB function will be called before the data is confirmed to be sent to the database.
Cell entity data is also backed up in the base entity to ensure that the data is up-to-date in case of disaster recovery.
This function can only be called on real entities and only when the entity has a base part.
Parameters:
shouldAutoLoad
: [ This optional parameter specifies whether this entity needs to be loaded from the database when the service starts.
Note: When the server starts and automatically loads the entity, the underlying default will call createEntityAnywhereFromDBID to create the entity on a baseapp with the least load, and the entire process will be completed before onBaseAppReady is called on the first started baseapp.
The script layer can re-implement the entity creation method in the personalized script (defined in kbengine_defaults.xml->baseapp->entryScriptFile).
For example:
def onAutoLoadEntityCreate(entityType, dbid):
KBEngine.createEntityFromDBID(entityType, dbid)]
dbInterfaceName
: string, optional, specifies which database interface to use, default is "default" interface. Database interfaces are defined in kbengine_defaults.xml->dbmgr->databaseInterfaces
.
def getWitnesses( self ):
Function Description:
This function returns all observers (players) observing this Entity.
Returns:
tuple, an array containing zero or more Entity.
def getComponent( self, componentName, all ):
Function Description:
This function is used to obtain an instance of a certain type of component bound to the entity.
Parameters:
componentName
: string, component type name, module name of the component.
all
: bool, if True, return all instances of the same type of component, otherwise return the first one or an empty list.
def fireEvent( self, eventName, *args ):
Function Description:
This function is used to trigger entity events.
Parameters:
eventName
: string, the name of the event to be triggered.
args
: event data to be attached, variable parameters.
def registerEvent( self, eventName, callback ):
Function Description:
This function is used to register entity events.
Parameters:
eventName
: string, the name of the event to be registered.
callback
: the callback method used to respond to the event when it is triggered.
def deregisterEvent( self, eventName, callback ):
Function Description:
This function is used to unregister the listener for entity events.
Parameters:
eventName
: string, the name of the event to be unregistered.
callback
: the callback method to be unregistered.
Callback Function Documentation
def onDestroy( self ):
If this function is implemented in the script, it is called before the actual destruction after calling Entity.destroy(). This function has no parameters.
def onEnterTrap( self, entity, rangeXZ, rangeY, controllerID, userArg ):
When a range trigger is registered using Entity.addProximity , this callback function is called when another entity enters the trigger.
Parameters:
entity
: The entity that has entered the range.
rangeXZ
: float, the size of the trigger area on the xz plane, must be greater than or equal to 0.
rangeY
: float, the height of the trigger area on the y axis, must be greater than or equal to 0.
Note that for this parameter to take effect, the kbengine_defaults.xml -> cellapp-> coordinate_system -> rangemgr_y must be enabled. Enabling y-axis management may incur some overhead, as in some games, many entities are at the same y-axis height or nearly the same horizontal line height, making collisions very dense.
3D space games or games with few entities like small rooms are more suitable for this option.
controllerID
: The controller ID of this trigger.
userArg
: The value of this parameter is given when the user calls addProximity, and the user can make some judgments about the current behavior based on this parameter.
def onEnteredView( self, entity ):
If this function is implemented in the script, this callback is triggered when an entity enters the View](../../keywords.html#View) range of the current entity.
Parameters:
entity
: The entity that has entered the View range.
def onGetWitness( self ):
If this function is implemented in the script, it is called when the entity is bound to a Witness.
The current state of the entity can also be accessed through the entity property Entity.hasWitness.
def onLeaveTrap( self, entity, rangeXZ, rangeY, controllerID, userArg ):
If this function is implemented in the script, it is triggered when the entity leaves the area of the range trigger registered with the current entity, which is registered with Entity.addProximity.
Parameters:
entity
: The entity that has left the trigger area.
rangeXZ
: float, the size of the trigger area on the xz plane, must be greater than or equal to 0.
rangeY
: float, the height of the trigger area on the y axis, must be greater than or equal to 0.
Note that for this parameter to take effect, the kbengine_defaults.xml -> cellapp-> coordinate_system -> rangemgr_y must be enabled. Enabling y-axis management may incur some overhead, as in some games, many entities are at the same y-axis height or nearly the same horizontal line height, making collisions very dense.
3D space games or games with few entities like small rooms are more suitable for this option.
controllerID
: The controller ID of this trigger.
userArg
: The value of this parameter is given when the user calls addProximity, and the user can make some judgments about the current behavior based on this parameter.
def onLoseControlledBy( self, id ):
If this function is implemented in the script, this callback method is called when the entity associated with Entity.controlledBy is lost.
Parameters:
id
: The ID of the controlledBy entity.
def onLoseWitness( self ):
If this function is implemented in the script, this callback is triggered when the entity is unbound from the Witness.
The current state of the entity can also be accessed through the entity property Entity.hasWitness.
def onMove( self, controllerID, userData ):
If this function is implemented in the script, it is called every frame when the related Entity.moveToPoint , Entity.moveToEntity , and Entity.navigate methods are called and succeed.
Parameters:
controllerID
: The controller ID related to a certain move.
userData
: The value of this parameter is given by the user when requesting the move-related interface.
def onMoveOver( self, controllerID, userData ):
If this function is implemented in the script, it is called when the related Entity.moveToPoint , Entity.moveToEntity , and Entity.navigate methods are called and the specified target point is reached.
Parameters:
controllerID
: The controller ID related to a certain move.
userData
: The value of this parameter is given by the user when requesting the move-related interface.
def onMoveFailure( self, controllerID, userData ):
If this function is implemented in the script, it is called when the related Entity.moveToPoint , Entity.moveToEntity , and Entity.navigate methods are called and fail.
Parameters:
controllerID
: The controller ID related to a certain move.
userData
: The value of this parameter is given by the user when requesting the move-related interface.
def onRestore( self ):
If this function is implemented in the script, this function is called when the entity is recreated on another Cell application after a crash. This function has no parameters.
def onSpaceGone( self ):
If this function is implemented in the script, the current entity's Space will be destroyed, triggering this function. This function has no parameters.
def onTurn( self, controllerID, userData ):
If this function is implemented in the script, it is called when the related Entity.addYawRotator method is called and the specified yaw is reached.
Parameters:
controllerID
: The controller ID returned by Entity.addYawRotator.
userData
: The value of this parameter is given by the user when requesting the move-related interface.
def onTeleport( self ):
If this function is implemented in the script, it is called just before the entity (Real entity) is teleported during the teleportation called by the baseapp's Entity.teleport.
Note that calling the entity's teleport on the cell will not trigger this interface. If you need this functionality, please call this callback after Entity.teleport .
def onTimer( self, timerHandle, userData ):
Function Description:
This function is called when a timer associated with this entity is triggered. A timer can be added using the Entity.addTimer function.
Parameters:
timerHandle
: The ID of the timer.
userData
: The integer user data passed to Entity.addTimer.
def onTeleportFailure( self ):
If this function is implemented in the script, it is called when the user's call to Entity.teleport fails.
def onTeleportSuccess( self, nearbyEntity ):
If this function is implemented in the script, it is called when the user's call to Entity.teleport succeeds.
Parameters:
nearbyEntity
: This parameter is given by the user when calling Entity.teleport . This is a real entity.
def onUpdateBegin( self ):
Called when the synchronization frame begins.
def onUpdateEnd( self ):
Called when the synchronization frame ends.
def onWitnessed( self, isWitnessed ):
If this function is implemented in the script, it is called when the current entity enters the View range of another entity bound with Witness (it can also be understood as an entity being observed by an observer).
This function can be used to activate the entity's AI when it is being observed, and stop the AI when it is no longer being observed, thus reducing the server's computational load and improving efficiency.
Parameters:
isWitnessed
: bool, True if the entity is being observed, False if the observation has stopped. The current state of the entity can also be accessed through the entity property Entity.isWitnessed.
def onWriteToDB( self ):
If this function is implemented in the script, it is called when the entity is about to be archived to the database.
Properties Documentation
allClients
Call the entity's client remote method through this property, the engine will broadcast this message to all other entities bound to the client within the entity's View range ( including its own client. Entities bound to clients are usually players).
Example:
In the avatar's View range, there are players A, B, and monster C.
avatar.allClients.attack(monsterID,skillID, damage)
At this time, the clients of player A and B will call the entity's attack method, and they can perform the attack action of the specified skill on their client for display.
See Also:
base
base is the entityCall used to contact the Entity entity. This property is read-only, and is None if there is no associated Entity.
See Also:
Type:
Read-only, ENTITYCALL
client
client is the entityCall used to contact the client. This property is read-only, and is None if there is no associated client.
See Also:
Type:
Read-only ENTITYCALL
controlledBy
If this property is set to the BaseEntityCall of the server entity associated with a certain client, then the entity is controlled by the corresponding client for movement. If this property is None, the entity is moved by the server. This property is automatically set to the BaseEntityCall of the client's own entity when the client logs in and calls giveClientTo to this entity.
Scripts can flexibly control whether the entity is moved by the server or by the client (own client or other clients).
See Also:
Type:
className
The class name of the entity.
Type:
Read-only string
direction
This property describes the orientation of the Entity in the world space. Users can change this property, and the data will be synchronized to the client.
Example: self.direction.y = 1.0 self.direction.z = 1.0
Type:
Vector3, containing (roll, pitch, yaw), expressed in radians.
hasWitness
This read-only property, if True, indicates that the entity is bound to a Witness . Entities bound to a Witness can have information about entities within their View range obtained through the client. Otherwise, it is False.
Type:
Read-only bool
id
id is the object id of the Entity. This id is an integer, and is the same across the base, cell, and client entities. This property is read-only.
Type:
Read-only int32
isDestroyed
If the value of this property is True, the Entity has been destroyed.
Type:
Read-only bool
isOnGround
If the value of this property is True, the Entity is on the ground, otherwise it is False.
Type:
Read-only bool
isWitnessed
If the current entity enters the View range of another entity bound with Witness (it can also be understood as an entity being observed by an observer), this property value is True, otherwise it is False.
See Also:
Type:
Read-only bool
layer
A space can load multiple navmesh data at the same time, different navmesh are in different layers, and different layers can be abstracted as ground, water surface, etc. This property determines which layer an entity exists in.
See Also:
KBEngine.addSpaceGeometryMapping
Type:
int8
otherClients
Call the entity's client remote method through this property, the engine will broadcast this message to all other entities bound to the client within the entity's View range ( excluding its own client. Entities bound to clients are usually players).
Example:
In the avatar's View range, there are players A, B, and monster C.
avatar.otherClients.attack(monsterID,skillID, damage)
At this time, the clients of player A and B will call the entity's attack method, and they can perform the attack action of the specified skill on their client for display.
See Also:
position
The coordinates (x, y, z) of this entity in the world space. This property can be changed by the user, and the change will be synchronized to the client. Note that do not reference this property, as referencing this property may incorrectly modify the entity's real coordinates.
Example:
self.position.y = 10.0
If you want to copy the value of this property, you can use the following method:
import Math
self.copyPosition = Math.Vector3( self.position )
Type:
spaceID
This property is the ID of the space where the entity is located, and is consistent between cell and client.
Type:
Read-only Integer
topSpeed
The maximum xz-axis movement speed of the entity (m/s). This property is usually set higher than the actual movement speed. The server checks the legality of the client's movement based on this property. If the movement distance exceeds the speed limit, it will be forcibly pulled back to the previous coordinate position.
See Also:
Type:
float
topSpeedY
The maximum y-axis movement speed of the entity (m/s). This property is usually set higher than the actual movement speed. The server checks the legality of the client's movement based on this property. If the movement distance exceeds the speed limit, it will be forcibly pulled back to the previous coordinate position.
See Also:
Type:
float
volatileInfo
This property specifies the strategy for synchronizing volatile class data of the Entity to the client.
Volatile class data includes the entity's coordinates position and the entity's orientation direction. Due to the easily changeable nature of volatile class data, the underlying engine uses an optimized scheme to synchronize it to the client.
This property is four floats (position, yaw, pitch, roll) representing distance values. When an entity approaches the current entity to a certain distance, the server synchronizes the relevant data. If the distance value is greater than the View radius, it means synchronization is always performed.
There is also a special bool property optimized, which controls whether the server performs optimization during synchronization. Currently, the main optimization is on the Y-axis.
If true, when the server can determine that the entity is on the ground due to certain actions (such as: navigate), the server will not synchronize the Y-axis coordinate of the entity. This can save a lot of bandwidth when synchronizing大量实体时,默认为true。
Users can also specify different synchronization strategies for entities in the .def
file:
<Volatile>
<position/> <!-- Always synchronize -->
<yaw/> <!-- Always synchronize -->
<pitch>20</pitch> <!-- Synchronize when within 20 meters -->
<optimized> true </optimized>
</Volatile> <!-- If roll is not specified, it is always synchronized -->
Type:
sequence, four floats (float, float, float, float)