# Acceleration and Deceleration Help

R

#### Rustyknight

##### Guest
As some of you may know, I am working on a commercial side-scroller game, and although I have plenty programming experience, I have some trouble on some presumably simple things, such as acceleration and deceleration for the player.

The problems: The deceleration integer never decreases below 3. The deceleration variable should increase, but after walking for a short period (.7 to 1 second), the player should ideally walk without deceleration.

Code:
``````move = -keyboard_check(vk_left) + keyboard_check(vk_right);

collidewith = obj_ground;

hsp = spd * move;
acel = hsp / 5;

accel = clamp(acel, 0, 6);
decel = clamp(decel, 0, 4);
spd = clamp(spd, 3, 10);

if(decel = 4){
candecel = false;
decel--;
}

if(keyboard_check(vk_left) && decel < 4 && candecel != false){
candecel = true;
decel++;
}

if(keyboard_check(vk_nokey)){
candecel = true;
}

while(place_meeting(x,y+1,collidewith)){
vsp = 0;
}

show_debug_message("speed decelerating by" + string(decel));

y+=vsp;

x+=hsp;``````

Last edited by a moderator:

#### Simon Gust

##### Member
There is actually way easier methods with some more maths.
Code:
``````move = -keyboard_check(vk_left) + keyboard_check(vk_right);

collidewith = obj_ground;

if (abs(hsp) < 0.05) hsp = 0;

// HARD CAP MAX SPEED
if (abs(hsp) > spd || move == 0)
{
hsp *= 0.80; // the higher this value, the less deceleration
}

// GAIN MOTION
if (abs(hsp) < spd || sign(hsp) != move)
{
hsp += move * spd / 12.00 ; // the higher this value, the less acceleration ( currently spd / 12 )
}

while(place_meeting(x,y+1,collidewith)){
vsp = 0;
}

x+=hsp;
y+=vsp;``````
here, spd is supposed to be the maximum value.

Doing it like this will save you if-statement checks and a lot of variables.

R

#### Rustyknight

##### Guest
There is actually way easier methods with some more maths.
Code:
``````move = -keyboard_check(vk_left) + keyboard_check(vk_right);

collidewith = obj_ground;

if (abs(hsp) < 0.05) hsp = 0;

// HARD CAP MAX SPEED
if (abs(hsp) > spd || move == 0)
{
hsp *= 0.80; // the higher this value, the less deceleration
}

// GAIN MOTION
if (abs(hsp) < spd || sign(hsp) != move)
{
hsp += move * spd / 12.00 ; // the higher this value, the less acceleration ( currently spd / 12 )
}

while(place_meeting(x,y+1,collidewith)){
vsp = 0;
}

x+=hsp;
y+=vsp;``````
here, spd is supposed to be the maximum value.

Doing it like this will save you if-statement checks and a lot of variables.
Thanks for the reply! Anyways, I'll see if I can write something like this. I have a bad habit of using as many if-statements as possible, so knowing this will most definitely help me.