Jbox2D - Body moving randomly

199 views Asked by At

I'm having a little problem with jbox2d.

As soon as the method world.step is called my dynamic body moves out of the original position. I tried to print everything else (the position of static bodies and the movement of the dynamic body) and it's correct.

I though it had to do with the gravity (which I don't need), but after I set the world and dynamic body to 0.0f, it still gives the same problem.

what could it be?

code:

Level (constructor)

world = new World(new Vec2(0,10.0f));

Level (update method)

world.step(1/60.0f, 8, 3);

Dynamic entity (constructor)

physicsX = x / Map.METER_IN_PIXELS;
physicsY = y / Map.METER_IN_PIXELS;
initPhysicalBody(world);

init method:

public void initPhysicalBody(World world)
{
    BodyDef bd = new BodyDef();
    bd.type = BodyType.DYNAMIC;
    bd.position.set(physicsX, physicsY);
    bd.gravityScale = 0;
    PolygonShape ps = new PolygonShape();
    ps.setAsBox(getFrameSize().width(), getFrameSize().height());
    FixtureDef fd = new FixtureDef();
    fd.density = 1;
    fd.shape = ps;
    body = world.createBody(bd);
    body.createFixture(fd);
    System.out.println(body.getPosition());
}

update method

body.setLinearVelocity(new Vec2(getLastDirection().getX() * getSpeed(), 
    getLastDirection().getY() * getSpeed()));

what could it be? thanks a lot!

2

There are 2 answers

0
aug13 On

I think the problem lies in this line

body.setLinearVelocity(new Vec2(getLastDirection().getX() * getSpeed(), 
getLastDirection().getY() * getSpeed()));

Comment this line and run your program.

0
Paras Mittal On

@Epi if you dont need gravity at all. then you could do

world = new World(new Vec2(0,0));

bt according to your solution you have set the gravity scale of body to 0 which will definately work fine.

Bt i think in the update method you are setting the linear velocity of body which definaltely doesnot have to do with the gravity.

so when you call world.step(---) it sets the velocity of body and your body dissapers in an instance.

so i think you should debug what your value are coming for

(new Vec2(getLastDirection().getX() * getSpeed(), getLastDirection().getY() * getSpeed())

Whole your problem lies in this line only.. Playing with it will solve your problem.