In my python prog i have 2 surfaces :
ScreenSurface
: the screenFootSurface
: 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
.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With