pygame.mouse.get_pos和Rect.collidepoint的Python表面真实位置坐标

标签 python pygame mouse pygame-surface

在我的 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/

相关文章:

python - Django - 如何设置 blank = False, required = False

javascript - JQuery Mousehold 插件的问题

python - pygame python 库中的 pygame.event.wait() 占用 100%CPU

css - 可以在css/html/jquery中给鼠标指针加上阴影吗?

c++ - 如何获得鼠标点击的位置(以 x-y 坐标像素为单位)?

python - 使用python比较来自不同列表的元素

python - 根据 RGB 值更改图像的颜色

python - 如何在 Amazon Linux AMI 2018.03.0 (HVM) 上正确设置 cron 作业?

python - 在 wxpython 中使用小部件需要一些帮助

python - 具有多种状态的 Pygame 动画