2013-10-12 92 views
1

所以我試圖用Python和Pygame創建一個拼圖遊戲平臺遊戲,但我遇到了一些麻煩。當我爲主要角色使用blitted圖像而不是rect圖像時,如何製作碰撞檢測器?我知道矩形圖像具有左,右,上和下像素函數(這對於碰撞檢測非常有用),但是有沒有像這樣的圖像?或者我只需要爲x和y座標+圖像的寬度/高度創建一個變量?我試過用Pygame碰撞檢測

import pygame, sys 
from pygame.locals import * 

WINDOWWIDTH = 400 
WINDOWHEIGHT = 300 
WHITE = (255, 255, 255) 
catImg = pygame.image.load('cat.png') 
catx = 0 
caty = 0 
catRight = catx + 100 
catBot = caty + 100 

moveRight = False 

pygame.init() 


FPS = 40 # frames per second setting 
fpsClock = pygame.time.Clock() 

# set up the window 
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32) 
pygame.display.set_caption('Animation') 


while True: # the main game loop 
    DISPLAYSURF.fill(WHITE) 

    for event in pygame.event.get(): 
     if event.type == QUIT: 
      pygame.quit() 
      sys.exit() 
     elif event.type == KEYDOWN: 
      if event.key in (K_RIGHT, K_w): 
       moveRight = True 

     elif event.type == KEYUP: 
      if event.key in (K_RIGHT, K_w): 
       moveRight = False 

    if catRight == WINDOWWIDTH: 
     moveRight = False 
    if moveRight == True: 
     catx += 5 

    DISPLAYSURF.blit(catImg, (catx, caty)) 


    pygame.display.update() 
    fpsClock.tick(FPS) 

但是catImg只是繼續走過窗口的盡頭。我究竟做錯了什麼?提前致謝。

回答

0

爲了防止圖像脫離右邊緣,您需要計算其x座標可以具有的最大值,並確保該值始終不超過。因此,在循環之前在它創建值的變量:

CAT_RIGHT_LIMIT = WINDOWWIDTH - catImg.get_width() 

然後在循環檢查:

if catx >= CAT_RIGHT_LIMIT: 
    moveRight = False 
    catx = CAT_RIGHT_LIMIT 
if moveRight == True: 
    catx += 5 

你可以,當然,擴展這個想法到所有其他邊緣。

+0

噢,謝謝,那正是我在找的東西,我不知道catImg.get_width()存在。你完全解決了我的問題。 – user2874724

+0

我不知道'get_width()'是否存在,直到我閱讀[documentation](http://pygame.org/docs/ref/surface.html)。 – martineau

0
if catRight >= WINDOWWIDTH: 
     moveRight = False 
     catright = WINDOWHEIGHT 
    if moveRight == True: 
     catx += 5 

我認爲這是你的錯誤所在。