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;
}}
};
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With