How can I change my pygame paddle to move from mouse positioning from keys

Viewed 42
def move(self):
    #reset movement direction
    self.path = 0
    key = pygame.key.get_pressed()
    if key[pygame.K_LEFT] and self.rect.left > 0:
        self.rect.x -= self.speed
        self.path = -1
    if key[pygame.K_RIGHT] and self.rect.right < screenw:
        self.rect.x += self.speed
        self.path = 1

I am getting it to work with the keys but am stuck on how to change it to mouse positioning

1 Answers

Just set the centery attribute of the paddle by the x coordinate of the mouse cursor. The position of the mouse cane be get with pygame.mouse.get_pos. pygame.Rect provides a lot of virtual attributes, which can be used to get and set the location and size of the rectangle.

mouse_pos = pygame.mouse.get_pos()
self.rect.centery = mouse_pos[1]

If you want the paddle to move slowly in the direction of the mouse, you need to calculate the distance from the center of the paddle to the mouse:

mouse_buttons = pygame.mouse.get_pressed()
if any(mouse_buttons)
    mouse_x, mouse_y = pygame.mouse.get_pos()
    dy = mouse_y - self.rect.centery
    if dy < 0:
        self.rect.y -= min(-dy, self.speed)
        self.path = -1
    elif dy > 0:
        self.rect.y += min(dy, self.speed)
        self.path = 1
Related