Hello, I wanted to add a bit of a gradual X-axis acceleration and deceleration to my player sprite, and I am having a slight issue with deceleration. When I release the movement keys, the character almost stops, but inches ever so slightly to the right (A few pixels per second probably). This is how I'm doing it:
if(!isRightPressed && !isLeftPressed)
{
if(playerXVel > 0)
playerXVel -= 8;
if(playerXVel < 0)
playerXVel += 8;
}
I thought that these two statements would eventually neutralize each other and make the velocity zero, but I guess not.
That's all the code I think is necessary to post, because changing the lines inside the block to just
if(!isRightPressed && !isLeftPressed)
{
playerXVel = 0;
}
solves the problem but gets rid of the deceleration. How can I do this differently and fix the bug?
Without seeing more code I can already see some issues with your first try the 'playerXVel -= 8;' stuff. Lets say going into the check that 'playerXVel' is actually greater than 0 but not an increment of 8, lets say it is 3. So then you have 3-8 = -5, so now you are slowly drifting, but then your next loop sees that its -5<0, so it goes -5+8 = 3....see where i'm going?
Have it decel at the rate you want, but have a secondary check in there that says once its speed is !=0 but is still under a small threshold, then make it 0. Such as:
if(!isRightPressed && !isLeftPressed)
{
if(playerXVel > 0 && playerXVel > 8)
playerXVel -= 8;
else if(playerXVel > 0 && playerXVel <=8)
playerXVel = 0;
if(playerXVel < 0 && playerXVel < -8)
playerXVel += 8;
else if(playerXVel < 0 && playerXVel >=-8)
playerXVel = 0;
}
I'm sure there are better ways to do this but for a cheap fix this should work