在普通的java中,您只需向坐标添加值,如:
object.x += 5;
object.y += 5;
render(object, object.x, object.y);
有没有办法对Box2D机身这样做?因为如果我这样做:
if(Gdx.input.isKeyPressed(Input.Keys.A) && player.getBody().getLinearVelocity().x >= -2.0f) {
player.getBody().applyLinearImpulse(new Vector2(-0.12f, 0.0f), player.getBody().getWorldCenter(), true);
}
然后物体继续向那个方向前进,直到我施加不同的力量。那么有没有什么方法可以将它移动一个恒定的量而不是继续以恒定的速度移动它?我尝试过摩擦试验但看起来很痛苦。
答案 0 :(得分:0)
Body有一个setTransform(float x,float y,float angle)方法。
所以,player.getBody()。setTransform(-0.12f,0.0f,angle-here);
答案 1 :(得分:0)
彼得的代码也有效但我找到了另一种方法,因为setTransform可能会导致潜在的意外故障:
float velX = 0, velY = 0;
if(Gdx.input.isKeyPressed(Input.Keys.W)) {
velY = 2.0f ;
} else if(Gdx.input.isKeyPressed(Input.Keys.D)) {
velX = 2.0f;
} else if(Gdx.input.isKeyPressed(Input.Keys.S)) {
velY = -2.0f;
} else if(Gdx.input.isKeyPressed(Input.Keys.A)) {
= -2.0f;
}
player.getBody().setLinearVelocity(x, y);
每按一次键,设置velocityX或velocityY,如果没有按任何键,默认设置为0。