2014-05-14 14 views
3

以我蟒PROG我有2個表面:Python的表面真實位置座標和Rect.collidepoint

  • ScreenSurface:屏幕
  • FootSurface:另一表面上blited ScreenSurface

我把一些矩形圖混合的FootSurface,該問題是Rect.collidepoint()給我掛FootSurface相對座標和pygame.mouse.get_pos()給出絕對座標。

例如:

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

Rect.collidepoint() - >相關的命名FootSurface第二表面,其中矩形是位圖混合

然後,這是行不通的。有沒有一個優雅的Python方法來做到這一點:在FootSurface或我的Rect絕對位置的鼠標的相對位置;或者我必須更改我的代碼以在ScreenSurface中拆分Rect

回答

1

您可以用簡單的減法計算相對鼠標位置到任何表面。

請看下面的例子:

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