An Entity in is an empty container for Components which store data, alone an Entity has little behavior.
They are useful for defining bare bones game objects with custom behavior.
If you want a batteries included prebuilt Entity use an Actor, read more here.
Entities have no behavior by default, only a few lifecycle hooks onInitialize
, and a concept of parent/children.
Building and adding an entity to a game is pretty straightforward.
const game = new ex.Engine({...});
const entity = new ex.Entity();
const entityWithName = new ex.Entity({name: 'Named Entity'});
game.currentScene.add(entity);
Entities can be added as children of other entities, once added child entities move relative to their parents.
Entity.parent
- Returns the parent of this entity, if one exists otherwise returns null
Entity.children
- Returns the list of child entities, otherwise returns an empty list
Entity.unparent()
- Removes this entity from its parent this entity
Entity.addChild(entity)
- Add a child to this entity
Entity.removeChild(entity)
- Remove a child
Entity.removeAllChildren()
- Removal all children
onInitialize
happens before first updateonPreUpdate
happens at the beginning of updateonPostUpdate
happens at the end of the updateComponents can be added and removed from an entity. Only 1 instance of a component type can be part of an entity at at time.
When removing components removal is deferred until the end of the update, unless forced. Deferred removal is useful to prevent bugs where an entity is only partially processed by all applicable systems.
const entity = new ex.Entity()
entity.addComponent(new ex.TransformComponent())
// Remove by type or instances
entity.removeComponent(ex.TransformComponent)
// Force removal
entity.removeComponent(ex.TransformComponent, true)
Components can be retrieved by type name, however if the component doesn't exist undefined will be returned.
const entity = new ex.Entity()
const maybeTransform = entity.get(ex.TransformComponent)
if (maybeTransform) {
console.log(maybeTransform.pos)
}
Entities can be checked for components as well
const entity = new ex.Entity()
if (entity.has(ex.TransformComponent)) {
console.log('Entity has a transform component')
}
All the components can be retrieved at once
const components: Component[] = entity.getComponents()
Tags are special components that are only types. Useful when the presence of a component is all that is needed.
Entity.addTag("sometag")
- Add a tag to an entityEntity.removeTag("sometag")
- Remove a tag on an entityEntity.hasTag("sometag")
- Check if a tag exists