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

5 投票
1 回答
4300 浏览
提问于 2025-04-18 06:30

在我的Python程序中,我有两个表面:

  • ScreenSurface:就是屏幕
  • FootSurface:另一个在ScreenSurface上显示的表面。

我在FootSurface上放了一些矩形(rect),但问题是,Rect.collidepoint()给出的坐标是相对于FootSurface的,而pygame.mouse.get_pos()给出的坐标是绝对坐标。

举个例子:

pygame.mouse.get_pos() --> (177, 500),这是相对于主表面ScreenSurface的坐标

Rect.collidepoint() --> 这是相对于第二个表面FootSurface的坐标,矩形是在这个表面上显示的

所以这样是行不通的。有没有什么简单的方法可以做到这一点:获取鼠标在FootSurface上的相对位置,或者获取我的Rect的绝对位置?还是说我必须修改代码,把Rect放到ScreenSurface上?

1 个回答

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()

撰写回答