Connecting objects to Sprites in Box2D

This topic seems to generate a lot of confusion when people first start using Box2D. Here's a simple explanation. Box2D has nothing to do with display images. Box2D is just a physics engine which means it tracks the position and velocity of the bodies it contains. To display the bodies you need another system. This could be DirectX, OpenGL, JavaFX or any other graphics system.

Once you've got your graphics up and running and you can display images on the screen the question becomes "how do you connect the position and rotation of the sprite with the position and rotation of the body contained within Box2D?".

To solve this problem I wrote a simple connector class which can be used to link a sprite to its corresponding body.

  1. public class Box2DSpriteAdapter {
  2. public final String TAG = this.getClass().getSimpleName();
  3.  
  4. private Body body;
  5. private Vec2 offset = new Vec2();
  6.  
  7. public Box2DSpriteAdapter (Body body, float width, float height) {
  8. this.body = body;
  9. offset.set(width, height);
  10. }
  11.  
  12. public Box2DSpriteAdapter (Body body) {
  13. this.body = body;
  14. }
  15.  
  16. public Vec2 position() {
  17. return body.getPosition();
  18. }
  19.  
  20. public float angleRad() {
  21. return body.getAngle();
  22. }
  23.  
  24. public float angleDeg () {
  25. return 180*body.getAngle()/((float) Math.PI);
  26. }
  27.  
  28. public Vec2 centreOfRotation () {
  29. return body.getLocalCenter();
  30. }
  31.  
  32. public Vec2 offset() {
  33. return offset;
  34. }
  35.  
  36. public void setOffset(float x, float y) {
  37. offset.set(x, y);
  38. }
  39. }

You just need to pass an instance of the body you want to track to construct the class and then pass an instance of the class to your sprite class. If you need the sprite to be offset from the body you just need to set the offset vector. Every frame each of your sprites would perform a query like this:

  1. Vec2 spritePosition = ((Box2DSpriteAdapter) adapter).position;
Tweet: 

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. The supported tag styles are: <foo>, [foo].
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.