-
Notifications
You must be signed in to change notification settings - Fork 19
Entities Legacy
Current Wiki index can be found here
Entities represent the bare essential for any game object. By themselves they contain nothing more than a transform. The transform of an entity can either be queried in world space - that is the absolute position, rotation and scale in the world - or relatively to its parent. Entities have a parent/child relationship; any entity can be a parent with one or more children, all of whom take on the transform of their parent, and, once inserted into the scene, have exactly one parent. Entities have their appearance and behaviour defined by attaching one or more components. It is the components who decide how the entities are drawn, and how the motion of the entity is influenced. Entities can also receive commands, targeted by either their unique ID or an assigned command category. Before an entity can be drawn or may influence the scene in any way, they must be explicitly added to the scene graph.
To create an empty entity you need to instantiate it via unique_ptr
, for which there is an alias: xy::Entity::Ptr
.
xy::Entity::Ptr myEntity = xy::Entity::create(messageBus);
Note that this syntax requires a C++14 capable compiler (gcc 4.9 or higher, or any of the latest versions of clang or MSVC), as create()
is an alias for std::make_unique
. It should also be noted that a valid entity can only be created via this factory function. xygine uses special internal memory allocation for entities to optimise fast creation and destruction during runtime, and to help prevent memory fragmentation. Entity
requires a reference to a valid xy::MessageBus
passed to it on construction. Once you have an empty entity you can attach one or more components to it:
auto td = xy::Component::create<SfDrawableComponent<sf::Text>>(messageBus);
td->getDrawable().setString("my text");
td->getDrawable().setFont(myFont);
auto tdPtr = myEntity->addComponent(td);
before adding it to a scene.
scene.addEntity(myEntity, xy::Scene::Layer::UI);
Note that, as components are also unique_ptr
, once added to an entity the entity takes ownership and the component pointer is then invalid. Similarly once an entity is added to a scene the scene takes ownership of the entity and myEntity
becomes invalid in the current scope. This is why the add
functions return a pointer to the newly added component or entity. Care should be taken to prevent these pointers from dangling by handling entity destruction messages via the message bus.
Entities can alternatively be added to another entity to become a child, before adding the parent entity to the scene:
xy::Entity::Ptr parent = xy::Entity::create(messageBus);
xy::Entity::Ptr child = xy::Entity::create(messageBus);
parent->addChild(child);
xy::Entity* myEnt = scene.addEntity(parent, xy::Scene::Layer::UI);
myEnt->setWorldPosition({200.f, 300.f});