【发布时间】:2016-07-14 23:37:12
【问题描述】:
我正在开发一个简单的 2D 平台游戏,但我的精灵的碰撞箱遇到了一些问题。我使用 pygame.sprite.spritecollide 函数来生成触摸我的玩家精灵的块(平台)列表。
这是我的播放器类:
class Player( pygame.sprite.Sprite ):
def __init__(self,x,y,image):
super( Player, self ).__init__()
self.vel_x = 0
self.vel_y = 0
self.moveSpeed = 3
self.jumpPower = 7
self.direction = idle
self.grounded = False
self.falling = True
self.jumping = False
self.climbing = False
self.image = pygame.Surface((50,50))#pygame.transform.scale( image, (50,50))
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.width = 50
self.height = 50
self.rect.bottom = self.rect.y + self.height
def set_position( self,x,y ):
self.rect.x = x
self.rect.y = y
def experience_gravity(self, gravity = 0.3):
if not self.grounded:
self.vel_y += gravity
self.falling = True
else:
self.vel_y = 0
self.grounded = True
self.falling = False
def jump(self):
self.grounded = False
self.vel_y -= self.jumpPower
def update(self, collidable = pygame.sprite.Group() ):
global collision
self.experience_gravity()
self.rect.x += self.vel_x
self.rect.y += self.vel_y
collision_list = pygame.sprite.spritecollide( self, collidable, False )
for p in collision_list:
if ( self.vel_y > 0 ):
self.vel_y = 0
self.grounded = True
在我的更新方法中,我检查了持有我所有平台(可碰撞参数)的精灵组与玩家之间的碰撞。
这是我的块类:
class Block( pygame.sprite.Sprite ):
def __init__( self, x, y, width, height):
super( Block, self ).__init__()
self.image = pygame.Surface( ( width, height ) )
self.image.fill( black )
self.rect = self.image.get_rect()
self.type = platform
self.rect.x = x
self.rect.y = y
self.width = width
self.height = height
相当不言自明的块类。我的其余代码是将所有内容更新并粘贴到白色背景上。我遇到的问题是,当玩家降落在平台上时,它只有在已经在平台上时才会停止下落(接地)。更奇怪的是,块沉入平台的深度并不一致。有时它会落在 10 像素,其他关系 20 像素。这是玩家卡住的截图:
The player block is stuck inside the platform block
所以这真的让我很困惑,特别是因为块落入的数量是不一致的。如果有人能告诉我如何解决这个问题,我将不胜感激。
致以最诚挚的问候,
德里克
【问题讨论】:
标签: python pygame collision-detection platform