我一直在嘗試讓我的代碼正常工作,但我的精靈不受重力影響,當我嘗試一些 print() 以查看出了什麼問題時,似乎我的精靈認為它一直在接觸平台觸摸一次時..?問題的圖片
這是代碼:
tx = 64
ty = 64
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('player.png').convert()
self.movex = 0 # move along X
self.movey = 0 # move along Y
self.isJumping = True
self.isFalling = True
def gravity(self):
if self.isJumping == True:
self.movey += 3.2
def update(self):
platform_hit_list = pygame.sprite.spritecollide(self, platform_list, False)
for p in platform_hit_list:
self.isJumping = False # stop jumping
self.movey = 0
if self.rect.bottom <= p.rect.bottom:
self.rect.bottom = p.rect.top
else:
self.movey += 3.2
self.rect.x = self.rect.x + self.movex
self.rect.y = self.rect.y + self.movey
class Level:
def platform(lvl, tilesX, tilesY):
platform_list = pygame.sprite.Group()
platformLocation = []
i = 0
if lvl == 1:
platformLocation.append((1000, height - tilesY - 100, 0))
while i < len(platformLocation):
j = 0
while j <= platformLocation[i][2]:
platform = Platform((platformLocation[i][0] + (j * tilesX)), platformLocation[i][1], tilesX, tilesY, 'platform.png')
platform_list.add(platform)
j = j + 1
print('run' + str(i) + str(platformLocation[i]))
i = i + 1
return platform_list
platform_list = Level.platform(1, tx, ty)
對問題的一些解決方案和解釋感到高興
您顯示的代碼讓播放器以 開頭self.isJumping = True
,但是一旦它False
在update
函數中設置為(發生碰撞時),就再也不會設置為True
。這就是為什麼當您離開平台邊緣時不會跌倒的原因。
您可能希望在循環碰撞的平台之前設置isJumping
為True
,以便如果沒有碰撞,它將保持為True
。
def update(self):
self.isJumping = True # we're in the air by default
platform_hit_list = pygame.sprite.spritecollide(self, platform_list, False)
for p in platform_hit_list:
self.isJumping = False # unless we collide with something
...
如果您的遊戲中可能存在多種碰撞(例如步行或跳入牆壁的側面),您可能需要比這更複雜的碰撞響應代碼,因為只有平台正好靠近玩家腳的碰撞才會使它們發生停止墜落(否則跳入牆壁或天花板會很奇怪)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句