PyGame - Moving with Mouse



Moving an object according to movement of mouse pointer is easy. The pygame.mouse module defines get_pos() method. It returns a two-item tuple corresponding to x and y coordinates of current position of mouse.

(mx,my) = pygame.mouse.get_pos()

After capturing mx and my positions, the image is rendered with the help of bilt() function on the Surface object at these coordinates.

Example - Moving Image with Mouse Cursor

Following program continuously renders the given image at moving mouse cursor position.

main.py

import pygame
from pygame.locals import *
from sys import exit

pygame.init()

filename = 'pygame.png'

screen = pygame.display.set_mode((400,300))
pygame.display.set_caption("Moving with mouse")
img = pygame.image.load(filename)
x = 0
y= 150
while True:
   mx,my=pygame.mouse.get_pos()
   screen.fill((255,255,255))
   screen.blit(img, (mx, my))
   for event in pygame.event.get():
      if event.type == QUIT:
         exit()
      pygame.display.update()

Output

The Pygame logo image can be moved up, down, left and right using corresponding keyboard arrow keys.

incremental position
Advertisements