How can my character jump in the direction of the left arrow key or right key?

61 Views Asked by At

this is my code. whenever i'm pressing down on left arrow key and when i press the spacebar it stops and jumps and it stops going to the left anymore(same with the right arrow key).

    stop();
    var Gravity = 5;
    var yLimit = 400 - char.height;
var friction = .9;
var velocity = 100;
var djctr = 0;
stage.addEventListener(Event.ENTER_FRAME, entFrame);
stage.addEventListener(KeyboardEvent.KEY_DOWN, control);

function control(event:KeyboardEvent){
    if(char.y >= yLimit || djctr == 2){
        if(event.keyCode == 32 && djctr !=2){
            char.y -= velocity;
            char.x += 7;
            djctr+=2;
        }else if (event.keyCode == 32 && djctr == 2){
            char.y -= velocity * .50;
            djctr+=2;
            }

    }

    if(event.keyCode == 37){
            char.x -= 7;
    }else if(event.keyCode == 39){
            char.x += 7;
    }
    }

function entFrame(e:Event){
    char.y += Gravity;
    if(char.y >= yLimit){
        char.y = 400-char.height;
        djctr = 0;
        }
    }
1

There are 1 best solutions below

0
ugotopia123 On

What I do for movement control is by having two stage KeyboardEvent listeners (KEY_DOWN and KEY_UP), and a Timer that runs every frame. The keyboard events don't handle control, they only handle changing static values such as keyLeftIsDown and keyRightIsDown (in your case you can also handle when the spacebar is pressed), and the Timer listener is what handles control. This is what it might look like:

private var keyLeftIsDown:Boolean;
private var keyRightIsDown:Boolean;

//The '60' in '1000 / 60' is the frames per second the program runs in. Change it as needed
private var movementTimer:Timer = new Timer(1000 / 60);

private function initialize():void {
    stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
    stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
    timer.addEventListener(TimerEvent.TIMER, movementUpdate);
    timer.start();
}

private function keyDown(e:KeyboardEvent):void {
    if (e.keyCode == Keyboard.LEFT) {
        keyLeftIsDown = true;
    }
    else if (e.keyCode == Keyboard.RIGHT) {
        keyRightIsDown = true;
    }
    else if (e.keyCode == Keyboard.SPACE) {
        //jump code goes here
    }
}

private function keyUp(e:KeyboardEvent):void {
    if (e.keyCode == Keyboard.LEFT) {
        keyLeftIsDown = false;
    }
    else if (e.keyCode == Keyboard.RIGHT) {
        keyRightIsDown = false;
    }
}

private function movementUpdate(e:TimerEvent):void {
    if (keyLeftIsDown && !keyRightIsDown) {
        char.x -= char.speed;
    }
    else if (keyRightIsDown && !keyLeftIsDown) {
        char.x += char.speed;
    }
}

This way the character moves in the x direction even if the code is handling jumps!