0
\$\begingroup\$

I'm constructing a Body (a box2d body using AndEngine) using multiple Fixtures and later I need to get the world position of these Fixtures.

Currently I am trying something like this;

// Declarations
Body body;
Fixture centerFixture;
Fixture leftFixture;
Vector2 centerPos = new Vector2(0, 0);
Vector2 leftPos = new Vector2(-1.5f, -1.5f);

void setup() {
  BodyDef bodyDef = new BodyDef();
  bodyDef.type = BodyType.DynamicBody;
  bodyDef.position.set(new Vector2(10, 10));

  body = physicsWorld.createBody(bodyDef);

  PolygonShape centerShape = new PolygonShape();        
  centerShape.setAsBox(1, 1, centerPos, 0);
  FixtureDef centerDef = new FixtureDef();
  centerDef.density=1;
  centerDef.shape=centerShape;
  centerFixture = body.createFixture(centerDef);

  PolygonShape leftShape = new PolygonShape();      
  leftShape.setAsBox(0.5f, 0.5f, leftPos, 0);
  FixtureDef leftDef = new FixtureDef();
  leftDef.density=1;
  leftDef.shape=centerShape;
  leftFixture = body.createFixtureleftDef);
}

void someFunction() {

  Transform transform = body.getTransform();
  Vector2 temp = new Vector2(leftPos);

  // These two seems to not be the center of the fixture 
  Vector2 worldPosition = transform.mul(temp);  
  Vector2 pixelPosition = new Vector2(worldPosition.x * PhysicsConstants.PIXELS_PER_METER, worldPosition.y * PhysicsConstants.PIXELS_PER_METER);
}

But is seems that as the body rotates the worldPosition is off.

How do I get the world position of the Fixture?

\$\endgroup\$
2
\$\begingroup\$

As I understood your question, you want to get the coordinates of the points of your body relative to the world, in other words, following the transformations applied to the body.

I did this function not long ago, I hope this will help you and guide you towards an answer:

public Vec2[] getPoints() {
    Vec2[] v = new Vec2[shape.getVertexCount()];
    for (int i = 0; i < shape.getVertexCount(); i++) {
        v[i] = body.getWorldPoint(shape.getVertex(i));
        v[i].x *= world.getMeter();
        v[i].y *= world.getMeter();
    }
    return v;
}

Here I used a PolygonShape for my body, but you can replace this by the vertices of your ficture, I think. What's important is that function:

body.getWorldPoint(shape.getVertex(i));

This will return a point of the body (Ex: (0, 0)) and return the same point with the transformations applied (Ex: (1, 0) if you rotated 90° clock-wise).

\$\endgroup\$
  • \$\begingroup\$ Thank you, my solution actually worked but I had forgotten to add one last offset to the final vector. But your solution is neater and more descriptive so I am going to use that instead. \$\endgroup\$ – bornander Jul 10 '14 at 19:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.