1 回答

TA貢獻1836條經驗 獲得超4個贊
好的,首先是對這些問題的標準回答:如果你使用PyGame Sprite函數,在最初做一些額外的工作之后,你的程序將更容易編寫和維護。
要在任意對象上進行良好的碰撞,首先需要一個“邊界框”。這是一個圍繞您的對象的矩形。
查看施利滕/雪橇的代碼,我必須從各種繪圖坐標中計算出這一點(但我只是在做一個快速/粗略的工作)。它看起來像從 和 渲染擴展了另外 31 像素和 75 像素在 .您可能希望臨時添加一些代碼來繪制邊界框以進行檢查。Schlitten.xSchlitten.yxy
因此,要定義碰撞函數,我們需要一個 PyGame 矩形。
class Schlitten:
def __init__( self ):
self.x = px
self.y = py
self.width = 31
self.height = 75
self.rect = pygame.Rect( px, py, self.width, self.height )
從代碼中可以看出,PyGame 矩形只需要坐標。需要隨著對象的移動而更新,但我們可以在碰撞測試之前執行此操作。我們添加了,因此我們的代碼不會到處都是無意義的數字。此外,如果雪橇的繪圖發生變化,則只需在一個地方調整這些數字。.rectself.widthself.height
無論如何,現在對于碰撞函數:
class Schlitten:
...
def collideWith( self, other_rect ):
""" Has the sleigh collided with the other object """
self.rect.x = self.x # update the rect position
self.rect.y = self.y
collision = self.rect.colliderect( other_rect )
return collision
對類進行類似的更改 - 至少到代碼具有 .Baumbaum.rect
class Baum():
def __init__( self, pos_x, pos_y, pscreen, pschlitten ):
self.x = pos_x
self.y = pos_y
self.width = 50
self.height = 95
self.rect = pygame.Rect( pos_x, pos_y, self.width, self.height )
def bewegung( self ):
self.y += 5
self.rect.y += 5
def spawn( self ):
if self.y > 600:
self.y = -50
self.x = random.randrange(0,700)
self.rect.x = x
self.rect.y = y
然后,這允許代碼快速輕松地檢查沖突:
alles_baumen = [ Baum1, Baum2, Baum3 ] # all tree objects
# main loop
while not exiting:
...
for baum in alles_baumen: # for each tree
baum.draw()
baum.bewegung()
baum.spawn()
if ( speiler1.collideWith( baum.rect ) ): # player hits tree?
speiler1.kollision() # Oh-noes!
注: 樹繪圖功能將繪制樹,就好像坐標是左下角一樣。我所做的更改沒有考慮到這一點,因此要么更改繪圖代碼,要么更改 的位置以適應此負 y 布局。yBaum.rect
添加回答
舉報