Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python surface real position coordinates of pygame.mouse.get_pos and Rect.collidepoint

In my python prog i have 2 surfaces :

  • ScreenSurface : the screen
  • FootSurface : another surface blited on ScreenSurface.

I put some rect blitted on the FootSurface, the problem is that Rect.collidepoint() gives me relative coordinates linked to the FootSurface and pygame.mouse.get_pos() gives absolute coordinates.

for example :

pygame.mouse.get_pos() --> (177, 500) related to the main surface named ScreenSurface

Rect.collidepoint() --> related to the second surface named FootSurface where the rect is blitted

Then that can't work. Is there an elegant python way to do this things: have the relative position of mouse on the FootSurface or the absolute position of my Rect; or must I change my code to split Rect in the ScreenSurface.

like image 264
user3619937 Avatar asked Oct 31 '22 23:10

user3619937


1 Answers

You can calculate the relative mouse position to any surface with a simple subtraction.

Consider the following example:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 400))
rect = pygame.Rect(180, 180, 20, 20)
clock = pygame.time.Clock()
d=1
while True:
    for e in pygame.event.get(): 
        if e.type == pygame.QUIT:
            raise

    screen.fill((0, 0, 0))
    pygame.draw.rect(screen, (255, 255, 255), rect)
    rect.move_ip(d, 0)
    if not screen.get_rect().contains(rect):
        d *= -1

    pos = pygame.mouse.get_pos()

    # print the 'absolute' mouse position (relative to the screen)
    print 'absoulte:', pos

    # print the mouse position relative to rect 
    print 'to rect:', pos[0] - rect.x, pos[1] - rect.y 

    clock.tick(100)
    pygame.display.flip()
like image 177
sloth Avatar answered Nov 15 '22 05:11

sloth