0

I have a sprite that moves around when a one of the arrow keys is pressed however I would like the sprite to carry on moving in the direction of the key for a small amount of time after the key has been released, as if it was sliding around on ice.

'''

 mv_speed = 5

  def move(self):
     global mv_speed
    
     keys = pg.key.get_pressed()

    
     self.pos_x += (mv_speed * (keys[pg.K_RIGHT] - keys[pg.K_LEFT]))
     self.pos_y += (mv_speed * (keys[pg.K_DOWN] -  keys[pg.K_UP]))
    
     if keys == False:
         self.pos_x += 50 * (keys[pg.K_RIGHT] - keys[pg.K_LEFT])
         self.pos_y += 50 * (keys[pg.K_DOWN] -  keys[pg.K_UP])
    
     self.rect.center = [self.pos_x,self.pos_y]

'''

2 Answers2

0

Add an attribute that indicates the direction and speed of movement. Increase the speed a small amount for each frame that the button is pressed. Scale the speed in every frame by a friction factor:

class Player:
    def __init__(self):
        # [...]

        self.speed_x = 0
        self.speed_y = 0
        self.acceleration = 0.1
        self.friction = 0.98
        self.max_speed = 5

    def move(self):
        self.speed_x += self.acceleration * (keys[pg.K_RIGHT] - keys[pg.K_LEFT])
        self.speed_y += self.acceleration * (keys[pg.K_DOWN] - keys[pg.K_UP])
        self.speed_x = max(-self.max_speed, min(self.max_speed, self.speed_x))
        self.speed_y = max(-self.max_speed, min(self.max_speed, self.speed_y))  
        
        self.pos_x += self.speed_x 
        self.pos_y += self.speed_y      
        self.rect.center = round(self.pos_x), round(self.pos_y)

        self.speed_x *= self.friction
        self.speed_y *= self.friction        
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
0

Ultimately there's lots of ways of doing it, depending on the effect you're going for. This might give you a similar sort of effect, adding both acceleration and deceleration.

mv_speed = 5
skidding = 0
speed_x=[0,0,0,0,0]
speed_y=[0,0,0,0,0]

  def move(self):
     global mv_speed
    
     keys = pg.key.get_pressed()
     speed_x.insert(0,mv_speed * (keys[pg.K_RIGHT] - keys[pg.K_LEFT]))
     speed_y.insert(0,mv_speed * (keys[pg.K_DOWN] -  keys[pg.K_UP]))
        
     self.pos_x += speed_x.pop()
     self.pos_y += speed_y.pop()
    
     self.rect.center = [self.pos_x,self.pos_y]
JeffUK
  • 4,107
  • 2
  • 20
  • 34