I\'ve been trying to figure out how I can gradually accelerate a sprite on key pressed and then once the key is released, gradually slow down to a stop, muc
Keep two variables.
Your velocity. This is how far you move the ship each time the game "ticks".
Your acceleration. This is how much you increase the velocity each time the game ticks.
To emulate the ship do something like this.
tick() {
if(forward key is pressed) {
howManyTicksTheForwardKeyHasBeenPressedFor++;
currentAcceleration += howManyTicksTheForwardKeyHasBeenPressedFor++; //This is the slow ramp of speed. Notice that as you hold the key longer, your acceleration grows larger.
currentVelocity += currentAcceleration; //This is how the ship actually moves faster.
} else {
howManyTicksTheForwardKeyHasBeenPressedFor--;
currentAcceleration -= howManyTicksTheForwardKeyHasBeenPressedFor; //This is the slow loss of speed. You'll need to make a decision about how this works when a user goes from holding down the forward key to letting go. Here I'm assuming that the speed bleeds off at a constant rate the same way it gets added.
currentVelocity += currentAcceleration; //This is how the ship actually slows down.
}
ship.position += currentVelocity; //This is how you actually move the ship.
}
This only works for a ship going in a single direction along a straight line. You should be able to easily upgrade this to a two dimensional or three dimension space by keeping track of where the ship is pointed, and dividing the velocity amongst x and y and/or z.
You also need to be mindful of clamping values. You'll probably want a maxAcceleration
, and maxVelocity
. If the ship cannot go in reverse, then you want to make sure that currentVelocity
never goes less than 0.
This also only represents constant acceleration. You get the same amount of change in velocity the first second you put on the gas as you do the last second before you let it go. I'm not a car guy, but I think most vehicles accelerate faster after they've had a moment or so to get started. You could emulate that by using a piecewise function to calculate the acceleration where the function f(x) where you put howManyTicksTheForwardKeyHasBeenPressedFor in for x and get out the acceleration to apply to your velocity. Maybe the first 3 ticks add 1, and the other ticks add 2 to your velocity.
Have fun!