How can I fix the wrong deceleration when moving to left?

Viewed 82

I just started learning game development in pygame and I want the player object to have a deceleration when the player stops pressing the key.

This is what I have at the moment:

def update(self):
    self.accel_x = 0
    keys = pg.key.get_pressed()
    if keys[pg.K_LEFT]:
        self.accel_x = -0.2
    if keys[pg.K_RIGHT]:
        self.accel_x = 0.2

    if abs(self.vx) >= max_speed:
        self.vx = self.vx/abs(self.vx) * max_speed

    if self.accel_x == 0:
        self.vx *= 0.91

    self.vx += self.accel_x
    self.vy += self.accel_y
    self.rect.x += self.vx
    self.rect.y += self.vy

It's works fine while moving to right but the object doesn't stop on time while going to left. Instead it decelerates to a point and then keeps going with a really slow speed for some time, then stops.

1 Answers

First, let see the math behind the algorithm.

When the button is pressed, the speed and position change based on the acceleration a, at t (number of times the function run), initial values being v0 and x0

v = v0 + a * t

x = x0 + Σ(i=1 to t) i * a
or
x = x0 + (t2+t) * a/2

And when the button is released (accel is 0) the speed v decreases geometrically

v = v0 * 0.91t

after 10 calls, we have ~0.39 v, after 100 calls ~10-5 v. Meaning that, visually, the position x decelerates and stops, v being too small to make a difference after some time.

The math is consistent with what is seen in games.

The question is why that algorithm doesn't work left side.
While it should work the same, left and right.

The difference is, left side,

  • speed v more likely to be negative after LEFT was pressed
  • position x might become negative at some point (and has to be checked)

Since the code provided (probably) does not cover the part to be changed, some recommendations:

  • You could force the speed to 0 if abs(v) is less than, say, 10-5 or another small values from which the position doesn't change visually (less than a pixel).
  • Ensure x values are checked at the limit, especially for negative values.
  • Debug: display/log v and x values especially after LEFT is released. This way when the whole program is running you'll identify more easily when does the problem come from.

If that doesn't address your problem, you could edit your question and add more relevant code.

Related