- Home /
My character can't jump while already moving
If I'm moving left or right, I can't jump until the left/right keys are released. Once in the air I can move, however. Any help? Here's my code
var moveLeft: KeyCode; var moveRight: KeyCode; var jump: KeyCode; var moveSpeed: float; var jumpSpeed: float;
private var isFalling = false;
function Start () {
};
function Update () {
if (Input.GetKey(moveLeft)) {
rigidbody2D.velocity.x = moveSpeed *-1;
}
else if (Input.GetKey(moveRight)) {
rigidbody2D.velocity.x = moveSpeed;
}
else if (Input.GetKey(jump) && isFalling == false) {
rigidbody2D.velocity.y = jumpSpeed;
isFalling = true;
}
else {
rigidbody2D.velocity.x = 0;
};
};
function OnCollisionEnter2D() {
isFalling = false;
}
Your code is badly formatted. Please watch the video tutorial to learn how to post code on this site.
Answer by Graham-Dunnett · Nov 26, 2014 at 10:14 PM
Your line 8 says "if the other keys haven't been pressed"... So, if they are pressed, your jump code is skipped.
Answer by Uldeim · Nov 26, 2014 at 10:16 PM
Your problem is that your if (jump)
code is in an else block. Look at it, then read it as English:
If I'm pressing left, move left. Otherwise, if I'm pressing right, move right. Otherwise, if I'm pressing jump, jump.
See how the last condition requires the previous two to be false?
Try instead putting them in two different blocks:
if (left)
//left
else if (right)
//right
else
//velocity.x = 0;
if (jump)
//jump