Pygame – Moving with mouse


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

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


filename = ''pygame.png''
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
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()

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *