Im currently developing a little dungeon crawler. My "Knight" class should have a special ability. He should be able to push forward and break through the Enemys. Im currently using Box2D Bodys for the Enemys and the Player... Any idea how to give the Player Body a push into a direction?
I already tested :
entityBody.applyLinearImpulse(100f, 0, entityBody.getWorldCenter().x, entityBody.getWorldCenter().y, true);
It works but the problem is, that the body is teleported into that direction and not"pushed forward". He also dont collide when moving that fast ... Any ideas ?
Check out what the Wiki has to say: https://github.com/libgdx/libgdx/wiki/box2d#impulsesforces
You may be interested in the Player Movement Example section. They're applying a left or right impulse to a body depending on if and which key is pressed, and if the body hasn't reached a maximum velocity.
Vector2 vel = this.player.body.getLinearVelocity();
Vector2 pos = this.player.body.getPosition();
// apply left impulse, but only if max velocity is not reached yet
if (Gdx.input.isKeyPressed(Keys.A) && vel.x > -MAX_VELOCITY) {
this.player.body.applyLinearImpulse(-0.80f, 0, pos.x, pos.y, true);
}
// apply right impulse, but only if max velocity is not reached yet
if (Gdx.input.isKeyPressed(Keys.D) && vel.x < MAX_VELOCITY) {
this.player.body.applyLinearImpulse(0.80f, 0, pos.x, pos.y, true);
}
For the issue of the collision not happening because the body is moving too fast, you may need to set the bullet flag on the BodyDef of the body:
bodyDef.bullet = true;
You're also setting the x impulse to 100, which basically means set the x velocity to 100 meters per second... pretty darn fast (about 224 mph). If that's desired, then feel free to bash enemies with the speed of a supercar!