5

私のpythonプログラムには2つの面があります:

  • ScreenSurface: スクリーン
  • FootSurface: 別のサーフェスがブライト化されていScreenSurfaceます。

FootSurface問題は、 にリンクされRect.collidepoint()た相対座標とFootSurface絶対pygame.mouse.get_pos()座標が得られることです。

例えば ​​:

pygame.mouse.get_pos()--> (177, 500) と名付けられた主表面に関連ScreenSurface

Rect.collidepoint()--> FootSurfacerect がブリットされている場所で名前が付けられた 2 番目のサーフェスに関連

それではうまくいきません。これを行うためのエレガントなpythonの方法はありますか:マウスの相対位置FootSurfaceまたは絶対位置を my Rect; または、コードを に分割Rectするように変更する必要がありScreenSurfaceます。

4

1 に答える 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()
于 2014-05-14T08:27:45.197 に答える