Marco
Marco

Reputation: 99

JS acceleration and deceleration

I'm making a simple level based platformer for a game-making comp at my school.

When the user holds the right arrow key the character starts gradually moving right, and speeds up until it reaches a max speed. It keeps travelling at that max speed, until the arrow key is released. When it is released, the character gradually slows down and stops.

I can make it speed up, but when the key is released, the character jumps forward and stops instantly, rather than slowing down then stopping.

Here's my code:

    var maxSpeed = 10; 
    var xForce = 0;
    var CharaXPos = 10;
    var CharaYPos = 200;

var draw = function() {
    background(255, 0, 0);
    image(getImage("creatures/Winston"), CharaXPos, CharaYPos, 50, 50);
        if (keyIsPressed && keyCode === RIGHT) {
            CharaXPos = CharaXPos + xForce;
            xForce = xForce + 0.25;
                if (xForce >= maxSpeed && keyIsPressed) {
                    xForce = maxSpeed;
                }
                }

        if (!keyIsPressed) {
                    while (xForce > 0) {
                        CharaXPos = CharaXPos + xForce;
                        xForce = xForce - xForce*0.25;
                    }}
};

Upvotes: 3

Views: 2165

Answers (1)

nnnnnn
nnnnnn

Reputation: 150010

Change the while loop to an if statement so that the force is decreased a little bit once per call to draw() instead of decreasing all the way to 0 in a single call to draw().

Also, be careful about xForce = xForce - xForce*0.25, because that'll bring xForce closer and closer to 0 without ever quite getting there. Try just xForce = xForce - 0.25 (the opposite of your acceleration code).

Upvotes: 1

Related Questions