1 回答
TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個(gè)贊
好的,首先是對(duì)這些問(wèn)題的標(biāo)準(zhǔn)回答:如果你使用PyGame Sprite函數(shù),在最初做一些額外的工作之后,你的程序?qū)⒏菀拙帉?xiě)和維護(hù)。
要在任意對(duì)象上進(jìn)行良好的碰撞,首先需要一個(gè)“邊界框”。這是一個(gè)圍繞您的對(duì)象的矩形。
查看施利滕/雪橇的代碼,我必須從各種繪圖坐標(biāo)中計(jì)算出這一點(diǎn)(但我只是在做一個(gè)快速/粗略的工作)。它看起來(lái)像從 和 渲染擴(kuò)展了另外 31 像素和 75 像素在 .您可能希望臨時(shí)添加一些代碼來(lái)繪制邊界框以進(jìn)行檢查。Schlitten.xSchlitten.yxy
因此,要定義碰撞函數(shù),我們需要一個(gè) 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 矩形只需要坐標(biāo)。需要隨著對(duì)象的移動(dòng)而更新,但我們可以在碰撞測(cè)試之前執(zhí)行此操作。我們添加了,因此我們的代碼不會(huì)到處都是無(wú)意義的數(shù)字。此外,如果雪橇的繪圖發(fā)生變化,則只需在一個(gè)地方調(diào)整這些數(shù)字。.rectself.widthself.height
無(wú)論如何,現(xiàn)在對(duì)于碰撞函數(shù):
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
對(duì)類進(jìn)行類似的更改 - 至少到代碼具有 .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!
注: 樹(shù)繪圖功能將繪制樹(shù),就好像坐標(biāo)是左下角一樣。我所做的更改沒(méi)有考慮到這一點(diǎn),因此要么更改繪圖代碼,要么更改 的位置以適應(yīng)此負(fù) y 布局。yBaum.rect
添加回答
舉報(bào)
