Python曲面的实际位置坐标pygame.mouse.get_pos游戏以及直线碰撞点

2024-06-16 11:51:15 发布

您现在位置:Python中文网/ 问答频道 /正文

在python程序中,我有两个曲面:

  • ScreenSurface:屏幕
  • FootSurface:另一个曲面blited在ScreenSurface上。在

我在FootSurface上加了一些直线,问题是Rect.collidepoint()给出了与FootSurface相关的相对坐标,pygame.mouse.get_pos()给出了绝对坐标。在

例如:

pygame.mouse.get_pos()-->;(177500)与名为ScreenSurface的主曲面相关

Rect.collidepoint()-->;与第二个名为FootSurface的曲面相关,其中rect是blited

那就不行了。有没有一种优雅的python方法可以做到这一点:在FootSurface上设置鼠标的相对位置或我的Rect的绝对位置;或者我必须更改代码以在ScreenSurface中拆分{}。在


Tags: posrectgt程序get屏幕pygame直线
1条回答
网友
1楼 · 发布于 2024-06-16 11:51:15

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

考虑以下示例:

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

相关问题 更多 >