0
votes

and a nice evening.

I've the following problem:

A Box2d dynamic body with one fixture all vertices placed with positiv x / y from the origin of the body. http://i.stack.imgur.com/MXQRr.png

But the rotation is on body origin 0/0 not on mass center..

So I tried these approaches:

1: Set origin of Body in the Middle of the body(vertices positive and negativ) Problem: rotation works, Sprite positioning is nearly impossible

2: Set mass data center = originOfBody.x + width / 2, originOfBody.y + height / 2 Problem: It's like I'm doing nothing, still rotation around origin of body at 0, 0

In the following Code snippet you can see my instantiation.

    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.DynamicBody;
    bodyDef.position.set(new Vector2(200, 2));

    body = world.createBody(bodyDef);

    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.density = 0.6f;
    fixtureDef.friction = 0.4f;
    fixtureDef.restitution = 0.2f;


    bodyLoader.attachFixture(body, "Rocket1n2", fixtureDef, WIDTH);
    originOfBody = bodyLoader.getOrigin("Rocket1n2", WIDTH);
    MassData data = body.getMassData();
    data.center.set(Box2DUtils.getWidth(body) / 2, 0);
    data.I = body.getMassData().I; //without this line programm fails with assertion
    body.setMassData(data);
    Vector2 cpy = data.center.cpy();

I rotate the player with following code:

body.setAngularVelocity(addition); //addition is predefined(atm 1 / -1)

I currently use Body Physics Editor from aurelia(?) with some hacks it worked, I dont have any Problems with other objects, because I dont rotate them. Placement works like a charm..

I wish I do a significant error.. Normally box2d must calculate the rotationcenter (Mass Center) automatically?

I cant help myself this time.. :(

1

1 Answers

1
votes

I'd recommend getting your first approach to work.

Set origin of Body in the Middle of the body(vertices positive and negativ) Problem: rotation works, Sprite positioning is nearly impossible

The rotation works fine, but the sprite positioning is difficult. I had this same problem when I was making a physics game last year. What helped me was seeing exactly how the positioning worked.

Box2D bodies are center-focused. That means that calling the position of the body will give you the object's middle. Sprites are corner focused, meaning a sprite's position is it's bottom-left corner. Thus, you can't just set each of them as the same thing. I recommend shifting the sprite from the body's position down and to the left by half the body's height and width, respectively.