AS3 Character jumping/falling problems

2019-08-27 18:47发布

问题:

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()
        }

回答1:

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;
    }
}