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

use*_*937 5 python mouse pygame pygame-surface

在我的 python prog 中,我有 2 个表面:

  • ScreenSurface : 屏幕
  • FootSurface: 另一个表面闪烁ScreenSurface

我在 上放了一些矩形FootSurface,问题是Rect.collidepoint()给了我链接到 的相对坐标FootSurfacepygame.mouse.get_pos()给出了绝对坐标。

例如 :

pygame.mouse.get_pos() --> (177, 500) 与主表面命名相关 ScreenSurface

Rect.collidepoint()--> 与第二个表面有关,FootSurface其中 rect 被 blitted

那么就行不通了。有没有一种优雅的python方式来做这件事:将鼠标的相对位置放在我的FootSurface或绝对位置上Rect;或者必须将我的代码更改分裂RectScreenSurface

slo*_*oth 2

您可以通过简单的减法来计算鼠标相对于任何表面的位置。

考虑以下示例:

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()
Run Code Online (Sandbox Code Playgroud)