Reputation: 96
I'm making a plataformer game and now I'm making the player movements. So when I press 'A', the player moves to the left (player.moveLeft()); when I press 'D' the player moves to the rigth (player.moveRigth()); and when I press 'W', the player jumps (player.jump()).
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);
}
}
It works but I've got a problem: when I press 'A' or 'D' before jumping, and when the player is jumping and I release the key, the player keeps moving. How can I fix it?? Please help me!!
Upvotes: 1
Views: 947
Reputation: 5597
You have to manipulate the X-axis velocity:
Vector2 vel = body.getLinearVelocity();
vel.x = 0f;
body.setLinearVelocity(vel);
This way, the Y-axis velocity remains the same, but your player won't move sideways.
Upvotes: 1