在我的 python 程序中,我有 2 个表面:
ScreenSurface
: 屏幕FootSurface
:在ScreenSurface
上绘制的另一个表面。
我在 FootSurface
上放了一些矩形 block ,问题是 Rect.collidepoint()
给我链接到 FootSurface
的相对坐标pygame.mouse.get_pos()
给出绝对坐标。
例如:
pygame.mouse.get_pos()
--> (177, 500) 与名为 ScreenSurface
的主表面相关
Rect.collidepoint()
--> 与名为 FootSurface
的第二个表面相关,其中矩形被 block 化
那是行不通的。有没有一种优雅的 python 方法来做这件事:鼠标在 FootSurface
上的相对位置或我的 Rect
的绝对位置;或者我必须更改我的代码以在 ScreenSurface
中拆分 Rect
。
最佳答案
您可以通过简单的减法计算鼠标相对于任何表面的相对位置。
考虑以下示例:
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()
关于pygame.mouse.get_pos和Rect.collidepoint的Python表面真实位置坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23648450/