PyGame: Drag object on screen using mouse
First you have to create some object to drag and variable which will keep information if object is draged
rectangle = pygame.rect.Rect(176, 134, 30, 30)
rectangle_draging = False
You have to use
MOUSEBUTTONDOWN
to check if object was clicked and set drag = True
and remember offset between mouse position and rectangle top-left corner.
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if rectangle.collidepoint(event.pos):
rectangle_draging = True
mouse_x, mouse_y = event.pos
offset_x = rectangle.x - mouse_x
offset_y = rectangle.y - mouse_y
MOUSEBUTTONUP
to set drag = False
elif event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
rectangle_draging = False
MOUSEMOTION
to move object when drag == True
using mouse position and offset.
elif event.type == pygame.MOUSEMOTION:
if rectangle_draging:
mouse_x, mouse_y = event.pos
rectangle.x = mouse_x + offset_x
rectangle.y = mouse_y + offset_y
Working example
import pygame
# --- constants --- (UPPER_CASE names)
SCREEN_WIDTH = 430
SCREEN_HEIGHT = 410
WHITE = (255, 255, 255)
RED = (255, 0, 0)
FPS = 30
# --- main ---
# - init -
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# - objects -
rectangle = pygame.rect.Rect(176, 134, 30, 30)
rectangle_draging = False
# - mainloop -
clock = pygame.time.Clock()
running = True
while running:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if rectangle.collidepoint(event.pos):
rectangle_draging = True
mouse_x, mouse_y = event.pos
offset_x = rectangle.x - mouse_x
offset_y = rectangle.y - mouse_y
elif event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
rectangle_draging = False
elif event.type == pygame.MOUSEMOTION:
if rectangle_draging:
mouse_x, mouse_y = event.pos
rectangle.x = mouse_x + offset_x
rectangle.y = mouse_y + offset_y
# - draws (without updates) -
screen.fill(WHITE)
pygame.draw.rect(screen, RED, rectangle)
pygame.display.flip()
# - constant game speed / FPS -
clock.tick(FPS)
# - end -
pygame.quit()
Other examples with many rectangles or circles and buttons on GitHub: furas/python-examples/pygame/drag-rectangles-circles
https://stackoverflow.com/questions/41332861/click-and-drag-a-rectangle-with-pygame
If you like it
Buy a Coffee
