2014-03-03 50 views
2

是的,我問有關此計劃的另一個問題是:dpygame的碰撞檢測與對象和矩形

反正我目前在它們之間在屏幕上創建兩行的間隙中的程序,可以滾動。從這裏,我顯然需要看看這兩個物體是否碰撞。因爲我只有一個精靈和一個矩形,所以我認爲這樣做有點毫無意義並且矯枉過正,爲他們製作了兩個類。但是,我只能找到與我顯然不需要的課程相關的教程。所以,我的問題確實是: 是否有可能測試標準圖像和Pygame rect之間的碰撞?如果不是,我如何轉換圖像,矩形或兩個精靈來做到這一點。 (所有優選不使用類。)

注:圖像和矩形都通過以下方式創建的(如果它有差別)

bird = pygame.image.load("bird.png").convert_alpha() 
pipeTop = pygame.draw.rect(screen, (0,200,30), Rect((scrollx,0),(30,height))) 
pipeBottom = pygame.draw.rect(screen, (0,200,30), Rect((scrollx,900),(30,-bheight))) 

回答

3

由本身的圖像不具有位置。你不能測試矩形和未放置在世界中的東西之間的碰撞。我會推薦創建一個類Bird以及一個類,這兩個類都將繼承pygame.Sprite。

Pygame中已經有了碰撞檢測內置

簡單例子

bird = Bird() 
pipes = pygame.Group() 
pipes.add(pipeTop) 
pipes.add(pipeBottom) 

while True:  
    if pygame.sprite.spritecollide(bird,pipes): 
     print "Game Over" 

編輯:

不要怕類,你將不得不遲早反正使用它們。 如果你真的不想使用精靈,你可以使用鳥rect和管道,並呼籲collide_rect檢查它們是否重疊。

EDIT2:

從pygame的文檔

class Bird(pygame.sprite.Sprite): 
    def __init__(self): 
     pygame.sprite.Sprite.__init__(self) 

     self.image = pygame.image.load("bird.png").convert_alpha() 

     # Fetch the rectangle object that has the dimensions of the image 
     # Update the position of this object by setting the values of rect.x and rect.y 
     self.rect = self.image.get_rect() 

然後,您可以添加方法,如移動,這將移動鳥下來重力修改的例子鳥類。

這同樣適用於Pipe,但不是加載圖像,您可以創建一個空表面,並用一種​​顏色填充它。

image = pygame.Surface(width,height) 
image.fill((0,200,30) 
+0

什麼我會在課堂鳥,使之成爲精靈被放?你也可以解釋一下pygame.Sprite的子類嗎?謝謝! – Harvey

1

你可以得到x和y的值並加以比較:

if pipe.x < bird.x < pipe.x+pipe.width: 
    #collision code 
    pass 
+0

我相信這是我最終這樣做的方式。 – Harvey