../

Collisions With Rectangles & Mouse Inputs In Pygame

rect1.colliderect(rect2) – returns a boolean value. If there is a collision it returns 1

rect1.collidepoint((x,y)) – check whether if one point collide with a rectangle

Using The Mouse

There are 2 ways of using the mouse in pygame,

  1. pygame.mouse
  1. event loops

Using pygame.mouse

mouse_position = pygame.mouse.get_pos() # getting the mouse position
if player_rectangle.collidepoint(mouse_position): # if the mouse position collide with the player rectangle (if true)
    print(pygame.mouse.get_pressed()) # return a tuple of boolean values (False,False,False)
    # (left mouse button, middle mouse button, right mouse button)
    # prints true if any of the mouse buttons click on the player rectangle

Using Event loops

MOUSEMOTION (Used to Get the mouse position tuple (x,y))

for event in pygame.event.get():  
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        if event.type == pygame.MOUSEMOTION:
            print(event.pos) # print the coordinates of the mouse movements (234,556)
if event.type == pygame.MOUSEMOTION:
    if player_rectangle.collidepoint((event.pos)):
        print("collision")
# print("Collision") if the mouse touches the player

MOUSEBUTTONDOWN

if event.type == pygame.MOUSEBUTTONDOWN: # Triggers if we click the Mouse
    Print("Mouse Button Down")

MOUSEBUTTONUP

if event.type == pygame.MOUSEBUTTONUP: # Triggers if we release the Mouse button
    Print("Mouse Button Up")

Tags: /python/ /python3/ /pygame/ /gamedev/ /tutorial/ /animation/