How to use entity systems with Box2D?

3.1k views Asked by At

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?

2

There are 2 answers

4
iforce2d On BEST ANSWER

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

0
Sebastian On

I found an example of box2d + artemis here: http://blog.gemserk.com/2012/02/02/how-we-use-box2d-with-artemis/

In short, they made a PhysicsComponent with a box2d.body and box2d.contacts and attached it to their entities.