Collisions With Rectangles & Mouse Inputs In Pygame

Vishal Rashmika published on
2 min, 254 words

Categories: 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
  • pygame.mouse.get_pressed - get the state of the mouse buttons
  • pygame.mouse.get_pos - get the mouse cursor position
  • pygame.mouse.get_rel - get the amount of mouse movement
  • pygame.mouse.set_pos - set the mouse cursor position
  • pygame.mouse.set_visible - hide or show the mouse cursor
  • pygame.mouse.get_visible - get the current visibility state of the mouse cursor
  • pygame.mouse.get_focused - check if the display is receiving mouse input
  • pygame.mouse.set_cursor - set the mouse cursor to a new cursor
  • pygame.mouse.get_cursor - get the current mouse cursor
  1. event loops
  • get mousemotion,
  • clicks
  • position etc.

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")