Hi, i am currently working on a little project with Box2D and i am having a little problem.
It isn’t hard to solve it, but i am not sure, which solution is the right one, so it is more a design question.
I have some “Model-classes”, which all extend Entity. Inside the consturctor of Entity, i create the Body and set it’s User-Data to “this” (the Model).
The Entity also has an “update(Body b)” method, which is used to update the Bodys properties. So for example if the Entity needs to move left, a property moveLeft is set to true. Inside the update i check this property and if it is set i apply an impulse to the Body, which moves it to the left.
Inside the render loop i go throught all the Bodies in the World and call
Entity e = (Entity)b.getUserData();
e.update(b);
The problem i am now having is, that some Entities (for example a Bullet) need to have some initial speed, it should move to the direction of the mouse.
But as the Body is created inside the Entity class, where i don’t have the direction/initial speed and the direction is passed to the constructor of Bullet (Subclass of Entity) and there i don’t have the Body, i can’t apply that initial impulse.
A few solutions i can think about:
- Add the Body as a member-variable inside Entity. I don’t really like that solution, as then the Body would have a reference to the Model and the Model would have a reference to the Body.
- create the Body in the subclasses, instead of in the constructor. I could use a method “createBody”, to avoid redundant code. However, if that method changes i may need to change the call inside every Entity subclass.
- Use the direction parameter inside the Entity class. I don’t really like that solution, as that param is used only forBullets, why should i pass it to the base class then?
Is there another, cleaner solution or should i rework the whole design?
Thanks