Search code examples
androidbox2dandenginegame-physics

Box2d body setLinearImpulse() function stability


I'm developing a game by Andengine for Android. Game: There is a body(let's say small box). And I want: the player collision with it, player will jump. It is jumping but not jumping the same height(in my code 100px) in every collision! My codes are here:

if (footFake.collidesWith(this))
{  

     player.getBody().applyLinearImpulse(new Vector2(0, 100/PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT), player.getBody().getWorldCenter());

}

And the box body features:

final FixtureDef fixtureDef = PhysicsFactory.createFixtureDef(0, 0, 0);
this.body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, this, BodyType.StaticBody, fixtureDef);
this.body.setUserData("jumpBox");
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(this, this.body, true, true)); 

And player:

final FixtureDef fixtureDef = PhysicsFactory.createFixtureDef(0, 0, 0.1f);
this.body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, this, BodyType.DynamicBody, fixtureDef);

Solution

  • Applying an impulse will not always give the same height jump, because the existing velocity of the body may be different. You could use SetLinearVelocity to set the vertical velocity of the body to make sure that the starting velocity is constant every time.

    Of course like Singhak has said, you should also make sure that there are no other influences (like collisions) on the body that will mess up the velocity that you want.