English 中文(简体)
Pygame - Moving with mouse
  • 时间:2024-12-22

Pygame - Moving with Mouse


Previous Page Next Page  

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.bpt(img, (mx, my))
   for event in pygame.event.get():
      if event.type == QUIT:
         exit()
pygame.display.update()
Advertisements