Keyboard code makes character jump straight up, but not move left nor right when it's in the air

StackOverflow https://stackoverflow.com/questions/22770444

  •  24-06-2023
  •  | 
  •  

سؤال

public function movementChar()
{   
    if (upKey)
    {
        this.y -= 10;
        this.gotoAndStop("jump");
        //this.scaleX = -1;     
    }
    else
    if (leftKey)
    {
        this.x -= xSpeed;
        this.gotoAndStop("run");
        this.scaleX = -1;
    }
    else if (rightKey)
    {
        this.x += xSpeed;
        this.gotoAndStop("run");
        this.scaleX = 1;
    }
    else if(!leftKey || !rightKey)
    {
        this.gotoAndStop("stop");
    }
}

When I hold down left I can move left and whilst holding down right I can then move right, however when I press up, the character jumps and doesn't move but only moves up when I hold down the left key and up key || right key and up key.

here is the rest of the code if it helps.

private function keyUp(e:KeyboardEvent):void 
{
    if (e.keyCode == 37)
    {
        leftKey = false;
    }
    if (e.keyCode == 39)
    {
        rightKey = false;
    }   
    if (e.keyCode == 38)
    {
        upKey = false;
    }       
}

private function keyDown(e:KeyboardEvent):void 
{
    if (e.keyCode == 37)
    {
        leftKey = true;
    }
    if (e.keyCode == 39)
    {
        rightKey = true;
    }
    if (e.keyCode == 38)
    {
        upKey = true;
    }
}
هل كانت مفيدة؟

المحلول

The problem is that you set it up in a if/if else conditional, but it should be only if conditionals. Like

if(leftKey){
...
}
if(rightKey){
..
}
if(upKey){
...
}

because think about it, in your code you first check if the upKey is pressed, if this evaluates to true it will execute that part and skip all the rest because all the other if conditionals can only be executed if upKey is false.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top