box2dgame-enginegame-physicsentity-systemartemis

How to use entity systems with Box2D?


The approach of developing games with Entity Systems is very clear. You have components, you add them to entities. Depending what kind of component you have different systems start to process the state of each entity. For example you add Position and Velocity components to an entity and entity is being processed my Movement and Collision systems. Movement system is doing Euler Integration (which is a rudimentary model) like:

x = Vx*dt;
y= Vy*dt;
Vx = Ax*dt; 
Vy = Ay*dt;

And collision systems say runs some simple collision algorithm.

Now what if I want to use the power of, for example, Box2D and use the engine of library. Should I have duplicate coordinates and velocities one for Position and Velocity components and another the position of b2Body? Should I sync them? What is the usual approach for this kind of systems, when entity systems and Physics library are working together?

Is there any example on any language that uses for example Artemis and Box2D?


Solution

  • Typically you will keep a Box2D body as a member variable of your entity, and relay all the position information to that body. For example:

    class Entity {
        b2Body* body;
    };
    

    If you also want the Box2D body to have a reference to the entity that owns it, you can set that in the 'user data' of the body:

    body->SetUserData( this );
    

    Instead of duplicating and syncing, the entity can just use information from the Box2D body:

    b2Vec2 Entity::GetPosition() { return body->GetPosition(); }
    float  Entity::GetAngle()    { return body->GetAngle(); }
    
    void Entity::SetPosition( b2Vec2 p ) { body->SetTransform(p, body->GetAngle()); }
    void Entity::SetAngle( float a )     { body->SetTransform(body->GetPosition(), a); }
    

    This may also be useful: https://www.iforce2d.net/b2dtut/drawing-objects