Skip to content

EntityListener and Box2D bodies #188

@lukz

Description

@lukz

Ashely wiki suggests to use EntityListeners to remove Box2D bodies. I also think it's the best way to handle that task.

However, you might be interested in knowing when entities enter or leave a particular family. This can be useful to keep track of when components of a particular type are added to or removed from entities. For example, you may want to know whenever a PhysicsComponent is removed from an entity so you can destroy the physics body from the Box2D World. In this case, you will need to pass in the family to the addEntityListener() method.

So I've created listener:

public class PhysicsComponentListener implements EntityListener {

    @Override
    public void entityAdded(Entity entity) {

    }

    @Override
    public void entityRemoved(Entity entity) {
        PhysicsComponent physComp = Components.PHYSICS.get(entity);

        if(physComp != null) {
            G.engine.getSystem(Box2DWorldSystem.class).getWorld().destroyBody(physComp.body);
        }
    }

}

And added listener to engine:

G.engine.addEntityListener(Family.all(PhysicsComponent.class).get(), new PhysicsComponentListener());

My PhysicsComponent contains Box2D body so I have to get this component in listener to destroy the body but I can't do this because Listener is notified after component removal in case of removing single component from Entity.

Is there any way to resolve that issue?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions