简体   繁体   中英

AS3 Character jumping/falling problems

I am having problems with getting the character to jump/fail when the up arrow is pressed. I'm trying to make it so when the up arrow key is pressed once it will jump a certain height then fall.

Here is my movement code:

public var gravity:int = 2;



public function fireboyMovement(e:KeyboardEvent):void
    {
        if (e.keyCode == 37) //right
        {
            fireboy1.x = fireboy1.x -5;
            checkBorder()

        }
        else if (e.keyCode == 39) //left
        {
            fireboy1.x = fireboy1.x +5;
            checkBorder()

        }
        if (e.keyCode == 38) //up
        {
            fireboy1.y = fireboy1.y -20;
            fireboy1.y += gravity;
            checkBorder()
        }

Your issue is you need to increment the players position over time (and not all at once).

You can either use a tweening engine (like tweenlite), or roll your own timer or enter frame handler.

Here is an example of the latter:

    if (e.keyCode == 38) //up
    {
        if(!isJumping){
            isJumping = true;
            velocity = 50;  //how much to move every increment, reset every jump to default value
            direction = -1; //start by going upwards
            this.addEventListener(Event.ENTER_FRAME,jumpLoop);
        }
    }

var isJumping:Boolean = false;
var friction:Number = .85; //how fast to slow down / speed up - the lower the number the quicker (must be less than 1, and more than 0 to work properly)
var velocity:Number;
var direction:int = -1;

function jumpLoop(){ //this is running every frame while jumping 
    fireboy1.y += velocity * direction; //take the current velocity, and apply it in the current direction
    if(direction < 0){
        velocity *= friction; //reduce velocity as player ascends
    }else{
        velocity *= 1 + (1 - friction); //increase velocity now that player is falling
    }

    if(velocity < 1) direction = 1; //if player is moving less than 1 pixel now, change direction
    if(fireboy1.y > stage.stageHeight - fireboy1.height){  //stage.stageheight being wherever your floor is
        fireboy1.y = stage.stageHeight - fireboy1.height; //put player on the floor exactly
        //jump is over, stop the jumpLoop
        this.removeEventListener(Event.ENTER_FRAME,jumpLoop);
        isJumping = false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM