Entity
From Blue Mars Developer Guidebook
|
|
Contents |
Overview
CryEngine supplies a number of Lua functions that operate on entities, defined in the Entity table. However, they are applied in object-oriented Lua fashion, i.e. called in the form:
golfball:SetWorldPos({x=0,y=0,z=0});
Creation/Deletion
To remove an entity from the system, call this:
- DeleteThis()
- request that this entity be deleted
Call System.SpawnEntity to create an entity.
Class
Every entity has an entity class. This can be accessed from a member of the entity:
- class
- the string class name of the entity
ID
Every entity has a globally unique ID, accessible as a member of the entity:
- id
- the entity ID of the entity. This is Lua userdata (opaque C++ data that cannot be inspected from Lua), so to print it, you need to convert it to a string using the Lua function tostring. For an example, see ARPrintEntity.
Lua bindings that take entities as parameters typically expect the entity ID, i.e. pass entity.id, not entity, e.g. the System entity functions.
There is one special entity ID constant:
- NULL_ENTITY
- ID for a null entity
Names
Every entity has a string name
- SetName(name)
- change entity name
- GetName()
- return name of entity
- GetArchetype()
- return archetype name of entity, nil if none
- SetAIName(name)
- set AI string name of entity
- GetAIName()
- return AI string name of entity
Flags
Each entity has a set of bit flags controlling various aspects of the entity, e.g. whether it casts a shadow.
- SetFlags(flags, mode)
- Set one or more entity flags
- GetFlags()
- return value - integer all the entity's bit flags
- HasFlags(flags)
- return value - boolean true if the entity has any flags set
Transform
You can set an entity's position and orientation.
- ToLocal(slot, pos)
- return world position converted to local position
- slot specifies slot from which to obtain transformation, entity transformation if -1
- examples - none
- ToGlobal(slot, pos)
- return local position transformed to world position
- slot specifies slot from which to obtain transformation, entity transformation if -1
- examples - none
- SetWorldPos(vPos)
- set the entity position, a vector in world coordinates
- SetWorldAngles(vAngles)
- set the world rotation, a vector
- SetWorldScale(fScale)
- set the world scale factor, a number
- GetWorldPos()
- return the entity position as a vector in world coordinates
- GetWorldAngles()
- return the entity rotation as a vector
- GetWorldScale()
- return the entity scale factor
- SetPos(vPos)
- same as SetWorldPos
- GetPos()
- same as GetWorldPos
- SetAngles(vAngles)
- same as SetWorldAngles
- SetScale(fScale)
- same as SetWorldScale
- GetAngles()
- return value - rotation
- GetScale()
- same as GetWorldScale
- return value - scale factor
If the entity is attached to a parent (see next section), then you can set the local transformation relative to the parent
- SetLocalPos(vPos)
- set the local position
- SetLocalAngles(vAngles)
- Set the local rotation
- SetLocalScale(fScale)
- Set the local scale
- GetLocalPos()
- return the local position as a vector
- GetLocalAngles()
- return the local rotation as a vector
- GetLocalScale()
- return the local scale, a number
Another way to change the orientation is to set its direction (facing forward) vector.
- GetDirectionVector()
- return the forward direction, a vector
- SetDirectionVector(direction, [up])
- GetDistance(entityID)
- returns the distance between this entity and another entity
- entityID - entity ID of the other entity
- example - Game/Scripts/Entities/Other/Switch.lua
- GetBoneLocal()
- IsEntityInside(EntityId)
The following are added by Avatar Reality:
- SetWorldAA(rad,vec)
- Set orientation by angle axis vector
- SetWorldV0V1(v0,v1)
- Set orientation by rotation from vector v0 to v1
- SetWorldVDir(v)
- Set orientation according to aim direction vector
Children
Entities can have entities as children - the parent-child relationship dictates that the child entity's local position and orientation are relative to that of the parent's. In other words, when the parent moves, the child entity moves along with it.
- AttachChild(childEntityId, flags)
- attach another entity as a child so child position and orientation will be offset (transformed) from that of this entity performs same function as the Link button in the Sandbox Editor
- DetachThis(flags)
- detach this entity from its parent
- DetachAll(flags)
- detach all children of this entity
- optional attachment flags parameter
- GetParent()
- return parent entity, nil if none
- GetChildCount()
- return number of children
- GetChild(nIndex)
- return child entity at nIndex, a number
- EnableInheritXForm(bEnable)
- enable/disable inheritance of transform from parent
Hiding
- Hide(dohide)
- Hide or unhide the entity. When hidden, the entity is invisible and has physics disabled.
- dohide - 0 specified don't hide, 1 specified do hide
- example - Item.lua
- IsHidden()
- returns boolean indicating whether entity is hidden
Proxies
Various behaviors of entities are implemented through proxies.
Proxies are allocated and destroyed as necessary - in general, you don't have to deal directly with them, but sometimes they will be mentioned for completeness or clarity. For example, entity slots are actually implemented in the render proxy.
Slots
General
Every entity has a variable number of slots, each of which can contain a character model, fog volume, particle emitter, cloud, light, or static geometry. This allows an entity to switch among different visible representations.
For example, BasicActor.lua loads different character models in slots 0, 2 and 3 and a static model in slot 1.
Multiple slots can be visible at the same time. For example, we can display a molecule by loading an atom model (a sphere) in various slots. (note there is a 16k object limit in the renderer)
- DrawSlot(slot, enable)
- show/hide object loaded in a slot
- slot - number of slot
- enable - 0 hides the object, 1 shows the object
- IgnorePhysicsUpdatesOnSlot(nSlot)
- FreeSlot(nSlot)
- clear slot, removing any object assigned to it
- example - Golf
- GetSlotCount()
- IsSlotValid(nSlot)
- return value - boolean indicating whether nSlot is a valid slot index
The functions to load objects into slots vary according to the type of object and are described in different sections below, e.g. LoadObject and LoadCharacter.
Transform
Slots can have a transform relative to the entity's transform.
- SetSlotPos(nSlot,vPos)
- GetSlotPos(nSlot)
- SetSlotAngles(nSlot,vAngles)
- GetSlotAngles(nSlot)
- SetSlotScale(nSlot,fScale)
- GetSlotScale(nSlot)
- CopySlotTM(srcSlot,destSlot,includeTranslation)
- MultiplyWitSlotTM(slot, pos)
- SetSlotWorldTM(slot, pos, dir)
- GetSlotWorldPos(slot)
- GetSlotWorldDir(slot)
Hierarchy
Slots can have parent-child relationships amongst themselves (in which case a transform are relative to the parent)
- SetParentSlot(child, parent)
- example - none
- GetParentSlot(child)
Geometry
A slot can contain static geometry, which is loaded from a CGF file. To create CGF files, see:
- Asset Creation Manual - export from 3DSMax
- Blue Mars Asset Creation - export from Maya and 3DSMax using ColladaCry
- IsSlotGeometry(slot)
- returns true if slot contains static geometry (or a character), false if not
- example - none
- LoadObject(nSlo, sFilename)
- Load static geometry (a cgf file) into the specified slot. Same as LoadCharacter if the file is chr/cdf/cga.
- return value - returns the slot number if successful, nil if not
- example - Golf/Perform Shot
self.ball:LoadObject(self.cgfSlot, "levels/ar/common/objects/golf/golf_ball_proxSphere.cgf");
- LoadObjectLattice(entity slot containing static geometry)
- use tetrahedral lattice from static geometry for entity physics
- return value - returns slot number
- example - BreakableObject.lua
- LoadSubObject(nSlot, sFilename, sGeomName)
- load subobject in static geometry (cgf) file into a slot
- nSlot - entity slot
- sFilename - geometry file
- sGeomName - subobject name
- DeformMesh(slot, point, radius, strength)
- deform mesh for an explosion-impact style morph object
- by Avatar Reality
- status - untested
- example - none
Material
General
Materials are defined in .mtl files in an XML format. They are exported during asset creation or edited with the Material Editor. Materials can have submaterials and layers.
References:
- Asset Creation Manual - section on Material Setup
- Sandbox Manual - Material Editor Reference
In addition to any materials included with objects loaded in an entity's slots (slot materials), an entity can have a custom material.
- SetMaterial(material)
- Set the entity custom material
- GetMaterial(slot)
- return the name of the entity custom material, if slot is not specified, or of the material on the object in the slot
- ReplaceMaterial(slot, name, replacement)
- replace the material in the entity slot with another material.
- ResetMaterial(slot)
- remove entity material. If the slot contains a character, also remove materials on any attachments.
- CloneMaterial(nSlot)
- set the material in a slot to a clone of itself
Material Parameters
- SetMaterialFloat(nSlot, nSubMtlId, sParamName, fValue)
- set material floating point parameter
- GetMaterialFloat(nSlot,nSubMtlId,sParamName)
- get material floating point parameter
- slot - entity slot containing the material
- ID - submaterial ID (value 0 for SubMtl[1], 1 for SubMtl[2], etc.); if invalid, use the default material
- name - material parameter name
- value - parameter value
- example - Game/Scripts/Entities/AI/Aliens/Alien_x.lua, get the glow value of material
self.mtlBodyGlow = self:GetMaterialFloat(0,0,"glow");
- SetMaterialVec3(nSlot,nSubMtlId,sParamName,vVector)
- set material vector parameter
- slot - entity slot containing the material
- ID - submaterial ID (value 0 for SubMtl[1], 1 for SubMtl[2], etc.); if invalid, use the default material
- name - material parameter name
- value - parameter value
- example - set the Diffuse Color to 127,127,127 for SubMtl[2]:
self:SetMaterialVec3(0,1,"diffuse",{x=.5,y=.5,z=.5});
- GetMaterialVec3(nSlot,nSubMtlId,sParamName)
- get material vector point parameter
- slot - entity slot containing the material
- ID - submaterial ID (value 0 for SubMtl[1], 1 for SubMtl[2], etc.); if invalid, use the default material
- name - material parameter name
- value - parameter value
- SetPublicParam(name,param)
- set shader parameter
- example - none
Layers
Materials have an optional set of layers. The predefined layers can be seen in the Materials Editor.
- EnableMaterialLayer(enable, layer)
- enable/disable a material layer
- enable - true to enable, false to disable
- layer - one of the predefined layers,
- MTL_LAYER_FROZEN
- MTL_LAYER_WET
- example - self:EnableMaterialLayer(true, MTL_LAYER_WET);
Flash
Flash movies can be used in materials just as they are in the HUD.
The procedure for assigning a Flash movie to a material is the same as that of assigning a video.
- MaterialFlashInvoke(slot, materialId, textureSlot, methodName, ...)
- Invoke an Actionscript method on the entity Flash material
- MaterialFlashSetVariable(slot, materialId, textureSlot, variableName, value)
- Set an Actionscript variable on the entity Flash material
Physics
See also general Physics functions.
Simulation
- AddImpulse(partId, pos, dir, impulse, scale, angularImpulse, massScale)
- GetVelocity()
- return velocity vector of entity
- GetSpeed()
- return speed of entity, a number (magnitude of GetVelocity)
- GetAcceleration()
- return acceleration vector of entity
- GetRotVelocity()
- return rotational velocity of entity
- GetRotAcceleration()
- return rotational acceleration of entity
- GetMass()
- returns the mass of an entity
- GetCenterOfMassPos()
- returns the entity center of mass
- GetGravity()
- return gravity at this entity's position
- GetSubmergedFraction()
- return fraction of entity that is submerged
- GetEnergy()
- returns the energy of the entity
- AddConstraint(params)
Raycasting
Also see more used function RayWorldIntersection in Physics
- IntersectRay(slot, rayOrigin, rayDir, maxDistance)
- examples - Game/Scripts/Entities/Other/GUI.lua
Volume
- GetVolume(slot)
- return volume of physical geometry in slot
- slot - entity slot containing the geometry
- example - Game/Scripts/Entities/Physics/PressurizedObject.lua
- GetSubmergedVolume(slot, planeNormal, planeOrigin)
- return volume of physical geometry in slot that is "below" the given plane
Physicalize
An entity's physical aspect must be generated from the contents of a slot
- Physicalize(slot, type, params)
- set physics parameters
- IsPhysicalized()
- checks if the entity has a physics proxy
- PhysicalizeSlot(slot, physicsParams)
- DestroyPhysics()
- Destroys the physics of the entity
- ResetPhysics()
- reset dynamic state of eneity
- AwakePhysics(nAwake)
- if nAwake is 0, put physics for entity to sleep, if nAwake is 1, wake up physics for entity
- EnablePhysics(bEnable)
- Enable/Disable physical simulation
- ActivatePlayerPhysics(bEnable)
- no examples
- SetPhysicParams(paramtype, params))
- set physics parameters of entity
- UpdateSlotPhysics(slot)
- AwakeEnvironment()
- examples - none
Collision
- SetColliderMode(mode)
- mode 0 for default collision, 1 to disable collision
- example - Dynamic Object/Example
- IsColliding()
- returns true if entity is currently colliding with something, false otherwise
- CheckCollisions
- examples - none
- GetTouchedSurfaceID
- GetTouchedPoint
- NoExplosionCollision()
- remove geom_type_collision from physics flags
- example - none
- GetPhysicalStats()
- return table of physics info, with the key-value pairs
- gravity
- mass
- flags
Explosions
BreakToPieces(nSlot, nPiecesSlot, fExplodeImp, vHitPt, vHitImp, fLifeTime, materialEffects)
- slot - slot containing the breakable object
- slot - slot containing the pieces
- explodeImpulse - explosion impulse
- HitPt - point of impact, a vector
- HitImp - impulse at hit point, a vector
- lifetime - particle lifetime
- materialEffect - true, to use material effects, false otherwise
- example - Game/Scripts/Entities/Physics/DestroyableObject.lua, in the Explode function
- GetExplosionObstruction
- GetExplosionImpulse
Areas
An entity can have one or more areas linked to it, that each will detect when an entity with its ENTITY_FLAG_TRIGGER_AREAS flag set enters it. This is automatically true of avatars - for other entities that you want detected by areas, call SetFlags to set ENTITY_FLAG_TRIGGER_AREAS.
Each area forwards enter/leave events to the OnEnterArea or OnLeaveArea callbacks of any entities that are specified as targets.
For example, here is a Shape Area with the minigame entity as its target.
Each area has an ID, which does not have to be unique (so you can use a single ID for several areas to treat them alike).
Tip: when new areas are placed in a level, save the level and re-launch the Editor to ensure the areas get recognized with the following API.
See the Areas section in the Sandbox Editor manual under References>User Interface>RollupBar>Objects Tab>Area.
- IsPointInsideArea(areaId, point)
- return value - true if point is within an area linked to this entity, false otherwise
- IsEntityInsideArea(areaId, entityId)
- return value - true if an entity is within an area linked to this entity, false otherwise
- GetAreas()
- returns a table of area ID's, corresponding to the areas linked to this entity.
Character
Overview
An entity slot can contain a character.
A character consists of a character model and an animation set.
The corresponding files:
- CDF files contain a CHR file and corresponding CAL files
- CHR files contain the skeleton and skin mesh
- CAL files contain lists of animation (CAF) files
- CAF (Crytek Animation Files) contain the animation keys
In general, a skeleton does not have to follow a bone-naming convention, and in fact does not even have to be human, but some features depend on the Crytek bone names.
The animation system can also play animations of articulated rigid geometry, exported as
- CGA files - the geometry
- ANM files - the animation files
Examples include vehicles and rope.
A character and rigid-body animations can be previewed and to some extent modified in the Character Editor.
References:
- Asset Creation Manual - Exporting animations
- Sandbox Manual - Animation graph reference (animation state parameters used in StartAnimationAR), Facial Editor tutorial, Character Editor reference (upcoming), LMG reference (upcoming)
- Blue Mars Asset Creation - exporting animation using the Collada-Cry plugin
An entity can control character animation after the character (a CDF file) has been loaded into one of the entity slots (usually 0), via LoadCharacter.
The following character console variables assist in debugging characters:
- ca_DrawCharacter - if 0, will not draw characters. Defaults to 1.
- ca_DrawBBox - draws the bounding box of the rendered character
- ca_DrawBodyMoveDir - draws the body and move direction
- ca_DrawNormals - draws the normals of the rendered character
- ca_DrawBinormals - draws the binormals of the rendered character
- ca_DrawTangents - draws the tangents of the rendered character
- ca_DrawWireframe - draws the wireframe of the rendered character
- ca_DrawPositionPost - draws the world position of the character (after update)
- ca_DrawPositionPre - draws the world position of the character (before update)
Loading a Character
- LoadCharacter(nSlot, sFilename)
- load an animated character into an entity slot
- GetCharacter(slot)
- returns pointer to the character in a slot
- IsSlotCharacter(slot)
- returns true if slot contains a character, false if not
Skeleton
Here are the standard bone names.
- "Bip01" (=Locomotion Locator)
- "Bip01 Pelvis"
- "Bip01 Spine"
- "Bip01 Spine1"
- "Bip01 Spine2"
- "Bip01 Spine3"
- "Bip01 Neck"
- "Bip01 Head"
- "Bip01 R Clavicle"
- "Bip01 R UpperArm"
- "Bip01 R ForeArm"
- "Bip01 R Hand"
- "Bip01 L Clavicle"
- "Bip01 L UpperArm"
- "Bip01 L ForeArm"
- "Bip01 L Hand"
- "Bip01 L Thigh"
- "Bip01 L Calf"
- "Bip01 L Foot"
- "Bip01 L Toe0"
- "Bip01 R Thigh"
- "Bip01 R Calf"
- "Bip01 R Foot"
- "Bip01 R Toe0"
just for Look-IK
- "Bip01 eye_left" (just procedural animation)
- "Bip01 eye_right"(just procedural animation)
- GetBonePos(name)
- returns the position of a bone, assumes character is in entity slot 0
- name - name of the bone
- GetBoneDir(name)
- returns the forward position of a bone (in world space), assumes character is in entity slot 0
- name - name of the bone
- GetBoneVelocity(characterSlot, boneName)
- returns the bone belocity
- slot - entity slot containing the character
- name - name of the bone
- GetBoneAngularVelocity(characterSlot, boneName)
- returns the bone rotational velocity
- slot - entity slot containing the character
- name - name of the bone
- GetBoneNameFromTable(index)
- return the name of a bone, assumes character is in entity slot 0
- index - the bone index, an integer
The following console variables assist in debugging skeletons:
- ca_DrawSkeleton - if set to 1, the skeleton is drawn. Defaults to 0.
Attachments
Each character has an attachment manager that maintains bone, skin and facial attachments. Attachments are identified by name (each attachment manager has one namespace for both bone and skin attachments, so you cannot use the same name for one of each).
Once an empty attachment (or "attachment socket") has been created, static geometry, a character, an arbitrary entity or particle effect can be bound to the attachment. The attachment (that is, anything bound to it), can be hidden or displayed.
Attachments are documented in the Character Editor section of the Sandbox Editor Manual
Attachments can be set in the Character Editor or created with these script functions.
The following character console variables assist in debugging attachments:
- ca_drawEmptyAttachments - set to 1 for draw boxes around empty attachments. Defaults to 0.
- ca_DrawAttachmentOBB - draw attachment bounding boxes
- ca_DrawAttachments - if 0, will not draw attachments. Defaults to 1.
- CreateBoneAttachment(characterSlot, boneName, attachmentName)
- creates a new bone attachment for a character, if attachment by that name doesn't exist already
- CreateSkinAttachment(characterSlot, attachmentName)
- create a new skin attachment for a character, if no attachment by this name exists
- DestroyAttachment(slot, name)
- removes an attachment from the character's attachment manager
- GetAttachmentBone(characterSlot, attachmentName)
- return the name of the attachment bone
- GetAttachmentCGF(characterSlot, attachmentName)
- return the pathname of the CGF file defining the attachment object, nil if no character, attachment or attached object
- ResetAttachment(characterSlot, attachmentName)
- remove anything bound to the attachment
- SetAttachmentEffect(characterSlot, attachmentName, effectName, offset, dir, scale, flags)
- attach a particle effect. Starts off hidden.
- SetAttachmentObject(characterSlot, attachmentName, entityId, slot, flags)
- attach the static geometry or character of another entity, or the entity itself if it has neither. Starts off hidden.
- SetAttachmentCGF(characterSlot, attachmentName, filePath)
- attach static geometry loaded from a file, starts off hidden
- SetAttachmentMaterial(characterSlot, attachmentName, materialName)
- SetAttachmentLight(characterSlot, attachmentName, lightTable, flags)
- attach a new light, starts of hidden
- SetAttachmentPos(characterSlot, attachmentName, pos)
- set the attachment position, relative to the attachment point
- SetAttachmentAngles(characterSlot, attachmentName, angles)
- set the attachment orientation, relative to the attachment point
- SetAttachmentDir(characterSlot, attachmentName, dir, worldSpace)
- set the attachment direction
- HideAttachment(characterSlot, attachmentName, hide, hideShadow)
- Show/hide an attachment (everything bound to it)
- HideAllAttachments(characterSlot, hide, hideShadow)
- hide/show all attachments for a character
- HideAttachmentMaster(characterSlot, hide)
- enable/disable rendering of the character
Animation
Each character has a number of animation layers. Each layer acts as a queue, since each incoming animation can have a transitional blend duration with the previous animation, at the end of which the previous animation is removed. A queued animation can be accompanied by a second animation that is constantly blended with it.
Layers are numbered. Animations in higher layers by default will overwrite animations in lower layers. A typical usage is to play an upper-body animation in layer 1 and a full-body animation in layer 0, so the net result is the lower-body portion of layer 0 combined with the upper-body animation in layer 1. See the Exporting Animation section of the Sandbox Manual
Higher layer animations can also have a blend-in transitional period with lower layer animations. For example, the upper-body animation in layer 1 can gradually override the upper-body portion of layer 0.
Higher layer animations can also be constantly blended with lower layer animations. The two methods of mixing animations - blending two on a single layer or blending two on separate layers - each has its own advantages and disadvantages:
- mixing on one layer allows you to vary the blend weight over time by calling SetIWeight and the second animation is "time-warped", i.e. stretched or compressed to match the primary animation. Also, there is currently a problem performing transitional blend-ins with dual animations on one layer
- running the animations on separate layers allows you to control the two animation speeds and positions separately, with SetAnimationSpeed and SetAnimationTime, but doesn't allow variation of the blend-weight during the run of the animation.
In summary, the steps taken to process a character's active animations each frame:
- perform keyframe interpolation on each animation
- for dual animations blend the two using the specified weight
- perform transitional blending among animations on the same layer according to the specified transition time
- perform blending/overriding of the resulting animations on multiplayer layers
You can preview animations and experiment with blends and transitions using the Character Editor, documented in the Sandbox Manual
Details on the animation system are explained in the CryEngine Programming Manual
- StartAnimation(characterSlot, animName, layer, blendTime, speed, loop, partial)
- starts playing an animation. This is the function used in the standard CryEngine scripts. For more options, see StartAnimationAR.
- StartAnimationAR(animName/Path, params)
- starts playing an animation. Exposes more animation parameters than StartAnimation.
local animFile = "levels/ar/common/animations/human/" .. self.Bowler[i].player:GetAvatarBaseModel() .. "/minigames/bowling/ARBOWL_bowl_and_walkback.dba";
self.Bowler[i].player:StartAnimationAR(animFile, {blendTime=0, speed=1, loop=false});
- GetAvatarBaseModel()
- returns either Female00 or Male00 according to avatar gender.
- As mentioned in the details of StartAnimationAR, this function is used to construct the animation path according to gender. An example is shown above.
The following functions operate on the current animation, i.e. the one at the front of the animation queue. Keep this in mind if you are blending animations, the most recent animation started might not be the one one that is "current".
- SetIWeight(layer,weight)
- sets the blend weight (or interpolation weight) for a layer that is playing an animation with a secondary animation
- slot - entity slot containing the character (via LoadCharacter).
- layer - layer on which the animation is playing
- weight - blend weight in the range 0.0-1.0. 0 gives full weight to the primary animation, 1 gives full weight to the secondary aniamtion
- GetIWeight(layer,weight)
- returns the blend weight (or interpolation weight) for a layer
- slot - entity slot containing the character (via LoadCharacter).
- layer - layer on which the animation is playing
- StopAnimation(slot, layer)
- stops animations on one or all layers
- slot - integer slot number in which the character is loaded
- layer - integer animation layer. If -1, stop all layers
- StopAnimationAR(params)
- stops animations on one or all layers
- params - table optional parameters
- by Avatar Reality , last modified on 2/10/2008
the parameter table contains the following optional keys:
- slot
- character slot, defaults to 0
- layer
- animation layer, defaults to 0, -1 specifies all layers
- blendOut
- blendOut time, defaults to 0, used for multilayer animations
- ResetAnimation(slot, layer)
- stop and reset animation
- slot - slot containing character
- layer - animation layer. If -1, reset all layers
- GetAnimationTime(slot, layer)
- return play time of animation in seconds
- nSlot - number of slot containing character (usually 0)
- nLayer - number of animation layer (usually 0)
- examples - used to pause animationin AnimObject.lua
- SetAnimationTime(slot,layer,time)
- set current play time of animation
- slot - number of slot containing character
- nSlot - number of slot containing character (usually 0)
- nLayer - number of animation layer
- fTime - number of seconds to set as current animation time
- examples - used to restore current point of animation in AnimObject.lua
- SetAnimationSpeed(slot, layer, speed)
- set animation speed
- slot is slot containing character
- layer is animation layer
- speed is animation speed, 0 for stop, 1 for normal
- examples - AnimObject.lua
- GetAnimationSpeed(slot, layer)
- returns the animation speed
- slot - slot containing character
- layer - animation layer
- GetAnimationLength(slot, animation)
- returns animation lengths in seconds
- characterSlot is the slot number of the character
- animation is the animation name
- examples - typically used in conjunction with SetTimer to trigger behavior when an animation is finished playing
- EnableBoneAnimation(slot, layer, boneName, enable)
- slot - number of slot containing character
- no examples
- EnableBoneAnimationAll(slot, layer, enable)
- slot - number of slot containing character
- no examples
- ForceCharacterUpdate(slot, alwaysUpdate)
- slot - number of slot containing character
- CharacterUpdateAlways(slot, alwaysUpdate)
- slot - number of slot containing character
- CharacterUpdateOnRender(slot, bUpdateOnRender)
- slot - number of slot containing character
- IsAnimationRunning(slot, layer)
- slot - number of slot containing character
ARAvatarAction
These entity.ARAvatarAction functions send a sync signal to the server (so the walk/idle will be started on all clients, not just locally). They can be used in-city where an ARDefaultCamera exists, but not in an independent minigame level (such as Golf, which handles the avatar spawning in the minigame script rather than using the standard spawning/sync'ing).
ARAvatarAction:StartIdle() - start automatic idle animation, sends a sync signal to the server
- Example: avatar_ent.ARAvatarAction:StartIdle();
ARAvatarAction:StartWalk(destPos) - start walking to a location, sends a sync signal to the server
- destPos - vector position of the walk-to location
- Example: avatar_ent.ARAvatarAction:StartWalk(vPos);
Look IK
During each frame, after the data-driven animation, optional procedural animations take place, starting with look IK.
- SetLookIK(slot, FOV, target)
- turn the character head to look at a target
- slot - number of slot containing character
- FOV -
- target - position vector of the target
- ClearLookIK(slot)
- slot - number of slot containing character
The following console variables are relevant:
- ca_DrawLookIK - set to 1 to for a debug display of the look direction, default is 0.
- ca_eyes_procedural - set to 1 to enable procedural eyes animation, default is 1.
Aim IK
- SetAimIK(slot, target)
- slot - number of slot containing character
- ClearAimIK(slot)
- slot - number of slot containing character
The following console variables assist in debugging:
- ca_AimIKFadeout - if set to 0, Aim-IK will not fade out when aiming in extreme directions
Foot Anchoring
See also the footplant setting in the CBA File section of the Sandbox Editor Manual
- SetFootAnchoring(slot)
- slot - number of slot containing character
- ClearFootAnchoring(slot)
- slot - number of slot containing character
The following console variables assist in debugging foot anchoring:
- ca_FootAnchoring - set to 1 to draw debug boxes around the feet
- ca_DrawFootPlants - set to 1 to draw debug boxes around the footplants
- ca_DebugFootPlants - set to 1 to print debug text
Recoil
- ApplyRecoilAnimation(slot,duration,impact)
- slot - number of slot containing character
- duration - duration (in seconds) of the recoil animation
- impact
Facial Animation
Facial animations are morph-based animations. They can be previewed in the Character Editor and edited in the Facial Editor.
- EnableProceduralFacialAnimation(enable)
- enable/disable procedural facial animation
- example - DeadBody.lua disables procedural facial animation before playing a death pose facial animation
- PlayFacialAnimation(name, looping)
- Play facial animation
- name is name of the facial animation
- looping is ignored
- example - DeadBody.lua plays a random death pose facial animation
The following console variables assist in debugging:
- ca_DebugFacial - debug facial playback info
- ca_DebugFacialEyes - debug facial eyes info
Physics
- RagDollize(slot)
- turn character in slot into a ragdoll (does not apply to avatar)
- slot - entity slot containing the character
- example - RagDollize flow event handler in BasicEntity.lua
- SetCharacterPhysicParams(slot,rootBoneName,paramtype,params)
- set character physics parameters
- slot - entity slot containing the character
- name - name of the root bone
- paramType - the physics parameter type, same options as SetPhysicParams
- params - the phycis parameters, same options as SetPhysicParams
- example - Game/Scripts/Entities/Rope.lua
- AwakeCharacterPhysics(nSlot,sRootBoneName,nAwake)
- activate physics on a character
- slot - entity slot containing a character
- name - name of the root bone
- awake - 1 to wake, 0 to sleep
Console Variables
See Console/Character for console variables that affect characters
Avatar
Enabling/Disabling user movement
- EnableMove(bEnable)
- bEnable - bool to enable/disable movement via mouse click or forward key (W or up arrow) actions
- example - in the Elevator and Bowling scripts, user navigation is temporarily disabled with avatar_ent:EnableMove(false);
- EnableClickMove(bEnable)
- bEnable - bool to enable/disable click movement via mouse click only (allowing WASD/arrow navigation)
- example - MMO:GetLocalAvatarEntity():EnableClickMove(false);
Camera
- CreateCameraProxy()
- creates a camera proxy for this entity
For custom cameras, it is recommended to attach a View to an entity. See Cameras for an explanation and examples.
Light
An entity can load a light into a slot. This is how the CryEngine light entities are implemented. See Game/Scripts/Entities/Lights/Light.lua
Notes:
- the other light entity scripts there are obsolete
- Light.lua has properties for optional geometry, but seems to rely on calls to LoadGeometry which is a non-existent function.
To implement a custom light, consider copying one of the standard light scripts and modifying it for a new light entity. For example, a light entity that changes its radius over time would have an OnUpdate callback that calls LoadLight with updated parameters.
For additional description of light entities and their properties, see the Sandbox Manual
- LoadLight(nSlot, tLightDescription))
- load light into slot
- IsSlotLight(slot)
- return value - boolean true if slot contains a light, false if not
Particles
An entity slot can contain a particle effect. An example is the ParticleEffect entity - see Scripts/Entities/Particles/ParticleEffect.lua
To control particles not attached to an entity, see Particles
- LoadParticleEffect(nSlot, sEffectName, params)
- Load a particle effect by name into an entity slot (-1 indicates take the next available)
- PreLoadParticleEffect(sEffectName)
- Called to speed up LoadParticleEffect - ensures that the effect file has been loaded
- IsSlotParticleEmitter(slot)
- returns true if slot contains a particle emitter, false if not
- AttachSurfaceEffect(nSlot, effect, countPerUnit, form, type, countScale, sizeScale)
- example - none
Fog Volume
An entity slot can contain a fog volume (i.e. volumetric fog). This is how the standard fog volume entity is implemented, in Game/Scripts/Entities/Render/FogVolume.lua.
Like clouds, a fog volume is defined in an XML file.
See the Sandbox Manual for a description of the fog volume entity.
- LoadFogVolume(nSlot,tFogVolumeDescription)
- FadeGlobalDensity(nSlot,fFadeTime,fNewGlobalDensity)
- LoadVolumeObject(nSlot,sFilename)
- SetVolumeObjectMovementProperties(nSlot,tVolumeObjectMovementProperties)
Cloud
An entity slot can contain a cloud. This is how the standard Cloud entity is implemented, in Game/Scripts/Entities/Render/Cloud.lua.
Clouds are described in XML files created by the Cloud Tool.
See the the Sandbox Manual for an explanation of cloud entities and the cloud tool.
- LoadCloud(slot, file)
- load cloud into slot
- slot - entity (render proxy) slot
- file - pathname of the cloud XML file
- SetCloudMovementProperties(slot, properties)
- set cloud movement properties from a table
- slot - entity slot containing cloud
- properties - table of properties, same parameters as in a cloud XML file
Helpers
Helpers are placeholders, exported as dummy objects from 3DSMax (in the case of skeletons, bone names are used). For example, they are used for driver positions in vehicles.
- GetHelperPos(helper,useObjectSpace)
- return the vector position of the helper. Searches all slots for the first name that matches.
- helper is the name of the helper
- useObjectSpace optional argument - if true specifies to return the position in the entity object object space, world space otherwise. Defaults to false.
- example - VehicleBase.lua, used to return seat position
- GetHelperDir(helper,useObjectSpace)
- return the vector position of the helper. Searches all slots for the first name that matches.
- helper is the name of the helper
- useObjectSpace optional argument - if true specifies to return the position in the entity object object space, world space otherwise. Defaults to false.
- example - VehicleBase.lua, used to return seat position
- GetSlotHelperPos(slot, helperName, objectSpace)
- return the vector position of the helper in the specified slot
- slot - entity slot containing the object
- helper is the name of the helper
- useObjectSpace optional argument - if true specifies to return the position in the entity object object space, world space otherwise. Defaults to false.
- example - none
Flowgraph
See Entity Script for details on how to specify flow node inputs for an entity.
- ActivateOutput(port, value)
- send a value to a flow node output port
- ProcessBroadcastEvent()
Triggers
Entities can behave as area (more accurately, volume) triggers. When a collision is detected with the entity's trigger bounding box, the entity's OnEnterArea callback is invoked. When an object leaves the bounding box, the the OnLeaveArea callback is invoked. This is how the standard trigger entities, in Game/Scripts/Entities/Triggers, are implemented.
- SetTriggerBBox(min, max)
- sets the entity trigger bounding volume
- GetTriggerBBox()
- returns two values, the min and max points of the trigger bounding box, as set by SetTriggerBBox
- InvalidateTrigger()
- resets the entity trigger, so any objects currently within the trigger bounding box register as colliding
- ForwardTriggerEventsTo(entityId)
- forward trigger events to another entity
Script
Lua control over Entity Scripts
Update
You can control if and how often the OnUpdate callback for an entity script is called, effectively enabling/disabling the script or tuning the update frequency for performance.
- UnSeenFrames()
- IsActive()
- returns bool indicating whether OnUpdate is called.
- SetScriptUpdateRate(nMilliseconds)
- Specify interval between calls to OnUpdate
- SetUpdatePolicy(policy)
- specify OnUpdate according to the specified policy
State
Use these functions to query and transition among entity script states:
- GotoState(sState)
- trigger a state transition
- IsInState(sState)
- Returns true if entity is currently in state sState.
- GetState()
- Returns name of current state
Timer
An entity can set internal timers (only visible to itself) that trigger its own OnTimer callbacks.
- SetTimer(timerId, delay)
- Start a timer.
- KillTimer(timerId)
- Deactivate timer with timerId
Sound
Sounds can be attached to an entity, following the entity's position (with an offset, if specified).
Sound completion is signalled with the Callback/OnSoundDone callback.
To play sounds not attached to an entity, see the Sound functions.
- PlaySound(ID)
- plays a sound, attaching it to this entity
- PlaySoundEvent(sSoundOrEventName, vOffset, vDirection, nFlags, nSemantic)
- play a sound event - same as the Sound function Play but attached to this entity
- PlaySoundEventEx(name, nSoundFlags, nVolume, vOffset, fMinRadius, fMaxRadius, nSemantic)
- play a sound event - same as the Sound function PlayEx but attaches to this entity
- SetSoundSphereSpec(soundId, radius)
- set spherical sound radius for an attached sound
- ID - ID of the attached sound
- radius - new radius of the sound
- example - none
- SetStaticSound(soundId,static)
- specifies whether a sound attached to this entity is static (see StopSound)
- ID - ID of the sound
- static - true makes this sound static, false non-static
- example - none
- StopSound(ID)
- stop playing sound attached to this entity, remove if non-static
- no return value
- ID - ID of the sound
- example - Game/Scripts/Entities/Sound/SoundSpot.lua
- StopAllSounds()
- stop all sounds attached to this entity
- no return value
- example - Game/Scripts/Entities/Physics/DestroyableObject.lua
- PauseSound(ID,pause)
- pause a sound attached to this entity
- no return value
- ID - ID of the sound
- pause - true to pause, false to unpause
- example - none
- SetSoundEffectRadius(fEffectRadius)
- set sound effect radius for this entity - affects all attached sounds
- radius - a float
- example - Game/Scripts/Entities/Sound/AmbientVolume.lua
Links
An entity can refer to a number of other entities via links (an alternative is to call System.GetEntityByName).
Links can be created and have their targets set to other entities in the entity properties panel typically on the right side of the Sandbox Editor.
Note that this is not to be confused with the Link button in the Sandbox Editor - that is equivalent to AttachChild
- CreateLink(name)
- create a link
- name - name of the link
- SetLinkTarget(name, targetId)
- Same as the Set Link Target option in the Sandbox Editor
- GetLinkTarget(name)
- return value - target of the link
- name - string name of the link
- RemoveLink(name)
- RemoveAllLinks()
- GetLink(idx)
- return value - target of the link
- idx - link index, starting with 0 at the bottom of the list
- CountLinks()
Render
Bounding Box
The entity has a render bounding box.
- SetLocalBBox(min, max)
- set the bounding box in local coordinates
- GetLocalBBox()
- returns the min and max coordinate of the bounding box in local coordinates
- GetWorldBBox()
- returns the min and max coordinate of the bounding box in world coordinates
- GetProjectedWorldBBox()
- returns the min and max coordinate of the bounding box in screen coordinates
View Distance
These functions control the view-distance of an entity
- GetViewDistRatio()
- examples - none
- SetViewDistRatio(ratio)
- adjust max view distance settings
- ratio - new view distance raio, if 100, max view distance is used
- examples - none
- SetViewDistUnlimited()
- makes entity visible at any distance
- examples - none
LOD
- GetLodRatio()
examples' - none
- SetLodRatio(ratio)
- adjust LOD distance settings
- ratio - if 100, max LOD distance is used
- examples - none
Decals
An entity can render decals.
- RemoveDecals()
- remove all entity decals
Example, Game/Scripts/Entities/Others/Fan.lua, removes decals in Explosion function
- EnableDecals(slot, enable)
- enable rendering of decals on a character
- slot - entity slot containing a character
- enable - true enables decal rendering, false disables
Example, Game/Scripts/Entities/actor/BasicActor.lua enables decals
AI
Typically used in conjunction with AI functions.
Events
- TriggerEvent
Pipes
- SelectPipe
- InsertSubpipe
- CancelSubpipe
- IsUsingPipe
Console
See Console/Entity for console commands and variables that relate to the entity system.





