如何在libGDX(Box2D)中阻止身体的冲动和力量,但不是重力?
问题描述:
我正在制作一个平台游戏,现在我正在制作玩家动作。所以当我按下'A'时,播放器向左移动(player.moveLeft());当我按下'D'时,玩家将移动到最接近的位置(player.moveRigth());当我按'W'时,玩家跳转(player.jump())。如何在libGDX(Box2D)中阻止身体的冲动和力量,但不是重力?
public void moveLeft() {
if(Gdx.input.isKeyPressed(Keys.A) &&
!Gdx.input.isKeyPressed(Keys.D) &&
body.getLinearVelocity().x > -MAXIMUM_VELOCITY){
left = true;
body.applyLinearImpulse(-3, 0, body.getPosition().x, body.getPosition().y, true);
}else if(Gdx.input.isKeyPressed(Keys.D) &&
Gdx.input.isKeyPressed(Keys.A) &&
!inTheAir){
stop();
}else if(!Gdx.input.isKeyPressed(Keys.A) &&
!Gdx.input.isKeyPressed(Keys.D) &&
!inTheAir){
stop();
}
}
public void moveRigth() {
if(Gdx.input.isKeyPressed(Keys.D) &&
!Gdx.input.isKeyPressed(Keys.A) &&
body.getLinearVelocity().x < MAXIMUM_VELOCITY){
rigth = true;
body.applyLinearImpulse(3, 0, body.getPosition().x, body.getPosition().y, true);
}else if(Gdx.input.isKeyPressed(Keys.D) &&
Gdx.input.isKeyPressed(Keys.A) &&
!inTheAir){
stop();
}else if(!Gdx.input.isKeyPressed(Keys.D) &&
!Gdx.input.isKeyPressed(Keys.A) &&
!inTheAir){
stop();
}
}
public void stop(){
body.setLinearVelocity(0, 0);
body.setAngularVelocity(0);
}
public void jump(){
if(!inTheAir && Gdx.input.isKeyPressed(Keys.W)){
inTheAir = true;
body.setLinearVelocity(0, 0);
body.setAngularVelocity(0);
body.applyLinearImpulse(0, 7, body.getPosition().x, body.getPosition().y, true);
}
}
它的工作原理,但我有一个问题:当我跳之前按“A”或“d”,而当玩家跳跃,我松开按键,玩家不断前进。我该如何解决?请帮帮我!!
答
你要操纵X轴速度:
Vector2 vel = body.getLinearVelocity();
vel.x = 0f;
body.setLinearVelocity(vel);
这样,Y轴的速度保持不变,但您的播放器就不会横向移动。
它的工作,非常感谢你! :d – Lordeblader