Search code examples
actionscript-3flashsmoothing

AS3 Smooth Jumping


I would like to know how to make a smooth jump in my game. Its a 2D game and the code is really simple but I would want to know how to make it better for it to slow down when it gets to the max height and then smooth drop.

This is all I have for jumping:

Player.y -= 50;

Solution

  • Your best bet would be to use a physics engine (Box2d etc). If you don't want the overhead of one though (if the only thing you'd use it for is jumping and not collisions) then you just need to add some friction to your logic.

    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 = 50;  //how much to move every increment, reset every jump to default value
    var direction   :int = -1;  //reset this to -1 every time the jump starts
    
    function jumpLoop(){ //lets assume this is running every frame while jumping 
        player.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(player.y > stage.stageHeight - player.height){  //stage.stageheight being wherever your floor is
            player.y = stage.stageHeight - player.height; //put player on the floor exactly
            //jump is over, stop the jumpLoop
        }
    }