Class Entity
- Namespace
- Vintagestory.API.Common.Entities
- Assembly
- VintagestoryAPI.dll
The basic class for all entities in the game
public abstract class Entity : RegistryObject
- Inheritance
-
Entity
- Derived
- Inherited Members
- Extension Methods
Constructors
Entity()
Creates a new instance of an entity
public Entity()
Entity(int)
Creates a minimally populated entity with configurable tracking range, no Stats, no AnimManager and no animations attribute. Currently used by EntityItem.
protected Entity(int trackingRange)
Parameters
trackingRange
int
Fields
ActivityTimers
An uptime value running activities. Available on the game client and server. Not synchronized.
public Dictionary<string, long> ActivityTimers
Field Value
AirBubbleParticleProps
public static AirBubbleParticles AirBubbleParticleProps
Field Value
Api
The api, if you need it. Available on the game client and server.
public ICoreAPI Api
Field Value
Attributes
Permanently stored entity attributes that are only client or only server side
public SyncedTreeAttribute Attributes
Field Value
ClimbingIntoFace
public BlockFacing ClimbingIntoFace
Field Value
ClimbingOnCollBox
Set by the game client and server.
public Cuboidf ClimbingOnCollBox
Field Value
ClimbingOnFace
The face the entity is climbing on. Null if the entity is not climbing. Set by the game client and server.
public BlockFacing ClimbingOnFace
Field Value
CollidedHorizontally
True if the entity is in touch with something solid on both horizontal axes. Set by the game client and server.
public bool CollidedHorizontally
Field Value
CollidedVertically
True if the entity is in touch with something solid on the vertical axis. Set by the game client and server.
public bool CollidedVertically
Field Value
CollisionBox
The entities collision box. Offseted by the animation system when necessary. Set by the game client and server.
public Cuboidf CollisionBox
Field Value
DebugAttributes
If entity debug mode is on, this info will be transitted to client and displayed above the entities head
public SyncedTreeAttribute DebugAttributes
Field Value
DespawnReason
public EntityDespawnData DespawnReason
Field Value
EntityId
A unique identifier for this entity. Set by the game client and server.
public long EntityId
Field Value
FeetInLiquid
True if the bottom of the collisionbox is inside a liquid. Set by the game client and server.
public bool FeetInLiquid
Field Value
FireParticleProps
public static AdvancedParticleProperties[] FireParticleProps
Field Value
FloatingSedimentParticles
public static FloatingSedimentParticles FloatingSedimentParticles
Field Value
InChunkIndex3d
public long InChunkIndex3d
Field Value
InLava
public bool InLava
Field Value
InLavaBeginTotalMs
public long InLavaBeginTotalMs
Field Value
IsRendered
Set by the client renderer when the entity was rendered last frame
public bool IsRendered
Field Value
IsShadowRendered
Set by the client renderer when the entity shadow was rendered last frame
public bool IsShadowRendered
Field Value
IsTeleport
Used by the PhysicsManager to tell connected clients that the next entity position packet should not have its position change get interpolated. Gets set to false after the packet was sent
public bool IsTeleport
Field Value
IsTracked
Used by PhysicsManager. Added here to increase performance 0 = not tracked, 1 = lowResTracked, 2 = fullyTracked
public byte IsTracked
Field Value
OnFireBeginTotalMs
public long OnFireBeginTotalMs
Field Value
OnGround
True if this entity is in touch with the ground. Set by the game client and server.
public bool OnGround
Field Value
OriginCollisionBox
The entities collision box. Not Offseted. Set by the game client and server.
public Cuboidf OriginCollisionBox
Field Value
OriginSelectionBox
The entities selection box. Not Offseted. Set by the game client and server.
public Cuboidf OriginSelectionBox
Field Value
PhysicsUpdateWatcher
The vanilla physics systems will call this method if a physics behavior was assigned to it. The game client for example requires this to be called for the current player to properly render the player. Available on the game client and server.
public PhysicsTickDelegate PhysicsUpdateWatcher
Field Value
Pos
Client position
public EntityPos Pos
Field Value
PositionBeforeFalling
The position where the entity last had contact with the ground. Set by the game client and server.
public Vec3d PositionBeforeFalling
Field Value
PreviousServerPos
Server simulated position copy. Needed by Entities server system to send pos updatess only if ServerPos differs noticably from PreviousServerPos
public EntityPos PreviousServerPos
Field Value
SelectionBox
The entities selection box. Offseted by the animation system when necessary. Set by the game client and server.
public Cuboidf SelectionBox
Field Value
ServerPos
Server simulated position. May not exactly match the client positon
public EntityPos ServerPos
Field Value
SimulationRange
The range in blocks the entity has to be to a client to do physics and AI. When outside range, then State will be set to inactive
public int SimulationRange
Field Value
SplashParticleProps
public static WaterSplashParticles SplashParticleProps
Field Value
State
The current entity state. NOT stored in WatchedAttributes in from/tobytes when sending to client as always set to Active on client-side Initialize(). Server-side if saved it would likely initially be Despawned when an entity is first loaded from the save due to entities being despawned during the UnloadChunks process, so let's make it always Despawned for consistent behavior (it will be set to Active/Inactive during Initialize() anyhow)
public EnumEntityState State
Field Value
Stats
public EntityStats Stats
Field Value
Swimming
True if the collisionbox is 2/3rds submerged in liquid. Set by the game client and server.
public bool Swimming
Field Value
Teleporting
Used by the teleporter block
public bool Teleporting
Field Value
WatchedAttributes
Permanently stored entity attributes that are sent to client everytime they have been changed
public SyncedTreeAttribute WatchedAttributes
Field Value
World
World where the entity is spawned in. Available on the game client and server.
public IWorldAccessor World
Field Value
alive
protected bool alive
Field Value
bioLumiNoise
public static NormalizedSimplexNoise bioLumiNoise
Field Value
bioLumiParticles
public static SimpleParticleProperties bioLumiParticles
Field Value
customRepulseBehavior
public bool customRepulseBehavior
Field Value
fireDamageAccum
protected float fireDamageAccum
Field Value
hasRepulseBehavior
public bool hasRepulseBehavior
Field Value
minHorRangeToClient
public float minHorRangeToClient
Field Value
ownPosRepulse
public Vec3d ownPosRepulse
Field Value
packet
Used for efficiency in multi-player servers, to avoid regenerating the packet again for each connected client
public object packet
Field Value
requirePosesOnServer
If true, will fully simulate animations on the server so one has access to the positions of all attachment points. If false, only root level attachment points will be available server side
public bool requirePosesOnServer
Field Value
resetLightHsv
protected bool resetLightHsv
Field Value
shapeFresh
protected bool shapeFresh
Field Value
touchDistanceSq
public double touchDistanceSq
Field Value
trickleDownRayIntersects
If true, will call EntityBehavior.IntersectsRay. Default off to increase performance.
public bool trickleDownRayIntersects
Field Value
Properties
Alive
True if the entity is in state active or inactive, or generally not dead (for non-living entities, 'dead' means ready to despawn)
public virtual bool Alive { get; set; }
Property Value
AlwaysActive
Whether this entity should always stay in Active model, regardless on how far away other player are
public virtual bool AlwaysActive { get; set; }
Property Value
AnimManager
Server simulated animations. Only takes care of stopping animations once they're done Set and Called by the Entities ServerSystem
public virtual IAnimationManager AnimManager { get; set; }
Property Value
ApplyGravity
If gravity should applied to this entity
public virtual bool ApplyGravity { get; }
Property Value
Collided
CollidedVertically || CollidedHorizontally
public bool Collided { get; }
Property Value
FrustumSphereRadius
public virtual double FrustumSphereRadius { get; }
Property Value
IdleSoundChanceModifier
public float IdleSoundChanceModifier { get; set; }
Property Value
IsCreature
Used by AItasks for perfomance. When searching for nearby entities we distinguish between (A) Creatures and (B) Inanimate entitie. Inanimate entities are items on the ground, projectiles, armor stands, rafts, falling blocks etc
Note 1: Dead creatures / corpses count as a Creature. EntityPlayer is a Creature of course.
Note 2: Straw Dummy we count as a Creature, because weapons can target it and bees can attack it. In contrast, Armor Stand we count as Inanimate, because nothing should ever attack or target it.
public virtual bool IsCreature { get; }
Property Value
IsInteractable
Should return true when this entity should be interactable by a player or other entities
public virtual bool IsInteractable { get; }
Property Value
IsOnFire
public bool IsOnFire { get; set; }
Property Value
LadderFixDelta
A small offset used to prevent players from clipping through the blocks above ladders: relevant if the entity's collision box is sometimes adjusted by the game code
public virtual double LadderFixDelta { get; }
Property Value
LightHsv
If set, the entity will emit dynamic light
public virtual byte[] LightHsv { get; set; }
Property Value
- byte[]
LocalEyePos
The height of the eyes for the given entity.
public virtual Vec3d LocalEyePos { get; set; }
Property Value
MaterialDensity
Determines on whether an entity floats on liquids or not and how strongly items get pushed by water. Water has a density of 1000. A density below 1000 means the entity floats on top of water if has a physics simulation behavior attached to it.
public virtual float MaterialDensity { get; }
Property Value
Properties
public EntityProperties Properties { get; protected set; }
Property Value
RenderColor
Used by some renderers to apply an overal color tint on the entity
public int RenderColor { get; set; }
Property Value
ShapeFresh
public bool ShapeFresh { get; }
Property Value
ShouldDespawn
If the entity should despawn next server tick. By default returns !Alive for non-creatures and creatures that don't have a Decay behavior
public virtual bool ShouldDespawn { get; }
Property Value
SidedPos
ServerPos on server, Pos on client
public EntityPos SidedPos { get; }
Property Value
SidedProperties
public EntitySidedProperties SidedProperties { get; }
Property Value
StoreWithChunk
Players and whatever the player rides on will be stored seperatly
public virtual bool StoreWithChunk { get; }
Property Value
SwimmingOffsetY
Used for passive physics simulation, together with the MaterialDensity to check how deep in the water the entity should float
public virtual double SwimmingOffsetY { get; }
Property Value
Methods
AddBehavior(EntityBehavior)
Adds given behavior to the entities list of active behaviors
public virtual void AddBehavior(EntityBehavior behavior)
Parameters
behavior
EntityBehavior
AfterInitialized(bool)
public virtual void AfterInitialized(bool onFirstSpawn)
Parameters
onFirstSpawn
bool
ApplyFireDamage(float)
protected void ApplyFireDamage(float dt)
Parameters
dt
float
CanCollect(Entity)
Should return true if this item can be picked up as an itemstack
public virtual bool CanCollect(Entity byEntity)
Parameters
byEntity
Entity
Returns
DidImportOrExport(BlockPos)
This method is called by the BlockSchematic class a moment after a schematic containing this entity has been exported. Since a schematic can be placed anywhere in the world, this method has to make sure the entities position is set to the correct position in relation to the target position of the schematic to be imported.
public virtual void DidImportOrExport(BlockPos startPos)
Parameters
startPos
BlockPos
Die(EnumDespawnReason, DamageSource)
Makes the entity despawn. Entities only drop something on EnumDespawnReason.Death
public virtual void Die(EnumDespawnReason reason = EnumDespawnReason.Death, DamageSource damageSourceForDeath = null)
Parameters
reason
EnumDespawnReasondamageSourceForDeath
DamageSource
DieInLava()
protected void DieInLava()
DoInitialActiveCheck(ICoreAPI)
protected void DoInitialActiveCheck(ICoreAPI api)
Parameters
api
ICoreAPI
FromBytes(BinaryReader, bool)
Loads the entity from a stored byte array from the SaveGame
public virtual void FromBytes(BinaryReader reader, bool isSync)
Parameters
reader
BinaryReaderisSync
boolTrue if this is a sync operation, not a chunk read operation
FromBytes(BinaryReader, bool, Dictionary<string, string>)
In order to maintain legacy mod API compatibility of FromBytes(BinaryReader reader, bool isSync), we create an overload which server-side calling code will actually call, and store the remaps parameter in a field
public virtual void FromBytes(BinaryReader reader, bool isSync, Dictionary<string, string> serversideRemaps)
Parameters
reader
BinaryReaderisSync
boolserversideRemaps
Dictionary<string, string>
GetBehavior(string)
Returns the behavior instance for given entity. Returns null if it doesn't exist.
public virtual EntityBehavior GetBehavior(string name)
Parameters
name
string
Returns
GetBehavior<T>()
Returns the first behavior instance for given entity of given type. Returns null if it doesn't exist.
public virtual T GetBehavior<T>() where T : EntityBehavior
Returns
- T
Type Parameters
T
GetDrops(IWorldAccessor, BlockPos, IPlayer)
Is called before the entity is killed, should return what items this entity should drop. Return null or empty array for no drops.
public virtual ItemStack[] GetDrops(IWorldAccessor world, BlockPos pos, IPlayer byPlayer)
Parameters
world
IWorldAccessorpos
BlockPosbyPlayer
IPlayer
Returns
GetHeadPositionFromWatchedAttributes()
Relevant only for entities with heads, implemented in EntityAgent. Other sub-classes of Entity (if not EntityAgent) should similarly override this if the headYaw/headPitch are relevant to them
protected virtual void GetHeadPositionFromWatchedAttributes()
GetInfoText()
gets the info text for the entity.
public virtual string GetInfoText()
Returns
GetInteractionHelp(IClientWorldAccessor, EntitySelection, IClientPlayer)
Called when a player looks at the entity with interaction help enabled
public virtual WorldInteraction[] GetInteractionHelp(IClientWorldAccessor world, EntitySelection es, IClientPlayer player)
Parameters
world
IClientWorldAccessores
EntitySelectionplayer
IClientPlayer
Returns
GetInterface<T>()
Returns itself or the first behavior that implements the interface T
public virtual T GetInterface<T>() where T : class
Returns
- T
Type Parameters
T
GetName()
Gets the name for this entity
public virtual string GetName()
Returns
GetTextureSource()
public virtual ITexPositionSource GetTextureSource()
Returns
GetTouchDistance()
public virtual double GetTouchDistance()
Returns
HasBehavior(string)
Returns true if the entity has given active behavior
public virtual bool HasBehavior(string behaviorName)
Parameters
behaviorName
string
Returns
HasBehavior<T>()
public virtual bool HasBehavior<T>() where T : EntityBehavior
Returns
Type Parameters
T
Ignite()
public virtual void Ignite()
Initialize(EntityProperties, ICoreAPI, long)
Called when this entity got created or loaded
public virtual void Initialize(EntityProperties properties, ICoreAPI api, long InChunkIndex3d)
Parameters
properties
EntityPropertiesapi
ICoreAPIInChunkIndex3d
long
IntersectsRay(Ray, AABBIntersectionTest, out double, ref int)
To test for player->entity selection.
public virtual bool IntersectsRay(Ray ray, AABBIntersectionTest interesectionTester, out double intersectionDistance, ref int selectionBoxIndex)
Parameters
ray
RayinteresectionTester
AABBIntersectionTestIs already preloaded with the ray
intersectionDistance
doubleselectionBoxIndex
int
Returns
IsActivityRunning(string)
Returns true if given activity is running
public virtual bool IsActivityRunning(string key)
Parameters
key
string
Returns
MarkShapeModified()
public virtual void MarkShapeModified()
Notify(string, object)
This method pings the Notify() method of all behaviors and ai tasks. Can be used to spread information to other creatures.
public virtual void Notify(string key, object data)
Parameters
OnAsyncParticleTick(float, IAsyncParticleManager)
public virtual void OnAsyncParticleTick(float dt, IAsyncParticleManager manager)
Parameters
dt
floatmanager
IAsyncParticleManager
OnCollected(Entity)
Called by BehaviorCollectEntities of nearby entities. Should return the itemstack that should be collected. If the item stack was fully picked up, BehaviorCollectEntities will kill this entity
public virtual ItemStack OnCollected(Entity byEntity)
Parameters
byEntity
Entity
Returns
OnCollideWithLiquid()
Called when the entity got in touch with a liquid
public virtual void OnCollideWithLiquid()
OnCollided()
Called when the entity collided with something solid and Collided was false before
public virtual void OnCollided()
OnEntityDespawn(EntityDespawnData)
Called when the entity despawns
public virtual void OnEntityDespawn(EntityDespawnData despawn)
Parameters
despawn
EntityDespawnData
OnEntityLoaded()
Called when after the got loaded from the savegame (not called during spawn)
public virtual void OnEntityLoaded()
OnEntitySpawn()
Called when the entity spawns (not called when loaded from the savegame).
public virtual void OnEntitySpawn()
OnExitedLiquid()
Called when the entity has left a liquid
public virtual void OnExitedLiquid()
OnFallToGround(double)
Called when the entity collided vertically
public virtual void OnFallToGround(double motionY)
Parameters
motionY
double
OnGameTick(float)
Called every 1/75 second
public virtual void OnGameTick(float dt)
Parameters
dt
float
OnHurt(DamageSource, float)
Called when the entity got hurt. On the client side, dmgSource is null
public virtual void OnHurt(DamageSource dmgSource, float damage)
Parameters
dmgSource
DamageSourcedamage
float
OnInteract(EntityAgent, ItemSlot, Vec3d, EnumInteractMode)
Called when an entity has interacted with this entity
public virtual void OnInteract(EntityAgent byEntity, ItemSlot itemslot, Vec3d hitPosition, EnumInteractMode mode)
Parameters
byEntity
EntityAgentitemslot
ItemSlotIf being interacted with a block/item, this should be the slot the item is being held in
hitPosition
Vec3dRelative position on the entites hitbox where the entity interacted at
mode
EnumInteractMode0 = attack, 1 = interact
OnLoadCollectibleMappings(IWorldAccessor, Dictionary<int, AssetLocation>, Dictionary<int, AssetLocation>, int, bool)
Called by the blockschematic loader so that you may fix any blockid/itemid mappings against the mapping of the savegame, if you store any collectibles in this blockentity. Note: Some vanilla blocks resolve randomized contents in this method. Hint: Use itemstack.FixMapping() to do the job for you.
public virtual void OnLoadCollectibleMappings(IWorldAccessor worldForNewMappings, Dictionary<int, AssetLocation> oldBlockIdMapping, Dictionary<int, AssetLocation> oldItemIdMapping, int schematicSeed, bool resolveImports)
Parameters
worldForNewMappings
IWorldAccessoroldBlockIdMapping
Dictionary<int, AssetLocation>oldItemIdMapping
Dictionary<int, AssetLocation>schematicSeed
intIf you need some sort of randomness consistency accross an imported schematic, you can use this value
resolveImports
boolTurn it off to spawn structures as they are. For example, in this mode, instead of traders, their meta spawners will spawn
OnReceivedClientPacket(IServerPlayer, int, byte[])
Called when on the client side something called capi.Network.SendEntityPacket()
public virtual void OnReceivedClientPacket(IServerPlayer player, int packetid, byte[] data)
Parameters
player
IServerPlayerpacketid
intdata
byte[]
OnReceivedServerAnimations(int[], int, float[])
public virtual void OnReceivedServerAnimations(int[] activeAnimations, int activeAnimationsCount, float[] activeAnimationSpeeds)
Parameters
OnReceivedServerPacket(int, byte[])
Called when on the server side something called sapi.Network.SendEntityPacket() Packetid = 1 is used for teleporting Packetid = 2 is used for BehaviorHarvestable
public virtual void OnReceivedServerPacket(int packetid, byte[] data)
Parameters
OnReceivedServerPos(bool)
Called by client when a new server pos arrived
public virtual void OnReceivedServerPos(bool isTeleport)
Parameters
isTeleport
bool
OnStateChanged(EnumEntityState)
Called on the server when the entity was changed from active to inactive state or vice versa
public virtual void OnStateChanged(EnumEntityState beforeState)
Parameters
beforeState
EnumEntityState
OnStoreCollectibleMappings(Dictionary<int, AssetLocation>, Dictionary<int, AssetLocation>)
Called by the worldedit schematic exporter so that it can also export the mappings of items/blocks stored inside blockentities
public virtual void OnStoreCollectibleMappings(Dictionary<int, AssetLocation> blockIdMapping, Dictionary<int, AssetLocation> itemIdMapping)
Parameters
blockIdMapping
Dictionary<int, AssetLocation>itemIdMapping
Dictionary<int, AssetLocation>
OnTesselated()
public virtual void OnTesselated()
OnTesselation(ref Shape, string)
Called by EntityShapeRenderer.cs before tesselating the entity shape
public virtual void OnTesselation(ref Shape entityShape, string shapePathForLogging)
Parameters
PlayEntitySound(string, IPlayer, bool, float)
Assumes that it is only called on the server
public virtual void PlayEntitySound(string type, IPlayer dualCallByPlayer = null, bool randomizePitch = true, float range = 24)
Parameters
ReceiveDamage(DamageSource, float)
Called when the entity should be receiving damage from given source
public virtual bool ReceiveDamage(DamageSource damageSource, float damage)
Parameters
damageSource
DamageSourcedamage
float
Returns
- bool
True if the entity actually received damage
RemainingActivityTime(string)
Returns the remaining time on an activity in milliesconds
public virtual int RemainingActivityTime(string key)
Parameters
key
string
Returns
RemoveBehavior(EntityBehavior)
Removes given behavior to the entities list of active behaviors. Does nothing if the behavior has already been removed
public virtual void RemoveBehavior(EntityBehavior behavior)
Parameters
behavior
EntityBehavior
Revive()
Revives the entity and heals for 9999.
public virtual void Revive()
SetActivityRunning(string, int)
Starts an activity for a given duration
public virtual void SetActivityRunning(string key, int milliseconds)
Parameters
SetCollisionBox(float, float)
Helper method to set the CollisionBox
public virtual void SetCollisionBox(float length, float height)
Parameters
SetHeadPositionToWatchedAttributes()
Relevant only for entities with heads, implemented in EntityAgent. Other sub-classes of Entity (if not EntityAgent) should similarly override this if the headYaw/headPitch are relevant to them
protected virtual void SetHeadPositionToWatchedAttributes()
SetSelectionBox(float, float)
public virtual void SetSelectionBox(float length, float height)
Parameters
ShouldReceiveDamage(DamageSource, float)
Should return true if the entity can get damaged by given damageSource. Is called by ReceiveDamage.
public virtual bool ShouldReceiveDamage(DamageSource damageSource, float damage)
Parameters
damageSource
DamageSourcedamage
float
Returns
SpawnWaterMovementParticles(float, double, double, double)
protected virtual void SpawnWaterMovementParticles(float quantityMul, double offx = 0, double offy = 0, double offz = 0)
Parameters
StartAnimation(string)
Starts the animation for the entity.
public virtual void StartAnimation(string code)
Parameters
code
string
StopAnimation(string)
stops the animation for the entity.
public virtual void StopAnimation(string code)
Parameters
code
string
TeleportTo(int, int, int)
Teleports the entity to given position
public virtual void TeleportTo(int x, int y, int z)
Parameters
TeleportTo(EntityPos, Action)
Teleports the entity to given position
public virtual void TeleportTo(EntityPos position, Action onTeleported = null)
Parameters
TeleportTo(BlockPos)
Teleports the entity to given position
public virtual void TeleportTo(BlockPos position)
Parameters
position
BlockPos
TeleportTo(Vec3d)
Teleports the entity to given position
public virtual void TeleportTo(Vec3d position)
Parameters
position
Vec3d
TeleportToDouble(double, double, double, Action)
Teleports the entity to given position. Actual teleport is delayed until target chunk is loaded.
public virtual void TeleportToDouble(double x, double y, double z, Action onTeleported = null)
Parameters
ToBytes(BinaryWriter, bool)
Serializes the slots contents to be stored in the SaveGame
public virtual void ToBytes(BinaryWriter writer, bool forClient)
Parameters
writer
BinaryWriterforClient
boolTrue when being used to send an entity to the client
TriggerOnInitialized()
protected void TriggerOnInitialized()
TryGiveItemStack(ItemStack)
Called when something tries to given an itemstack to this entity
public virtual bool TryGiveItemStack(ItemStack itemstack)
Parameters
itemstack
ItemStack
Returns
UpdateAnimationDebugAttributes()
protected virtual void UpdateAnimationDebugAttributes()
UpdateDebugAttributes()
Updates the DebugAttributes tree
public virtual void UpdateDebugAttributes()
WillExport(BlockPos)
This method is called by the BlockSchematic class a moment before a schematic containing this entity is getting exported. Since a schematic can be placed anywhere in the world, this method has to make sure the entities position is set to a value relative of the schematic origin point defined by startPos Right after calling this method, the world edit system will call .ToBytes() to serialize the entity
public virtual void WillExport(BlockPos startPos)
Parameters
startPos
BlockPos
updateColSelBoxes()
protected void updateColSelBoxes()
updateOnFire()
protected void updateOnFire()
Events
OnInitialized
public event Action OnInitialized