我正在尝试制作一款平台游戏,其中没有斜坡。我试图让碰撞检测失效,但我无法在pygame中找到一种方法来获取哪一侧与另一个精灵相撞。任何人都可以给我一个很好的方法来做到这一点,这不是太笨重,但在我的情况下也会很好用吗?
这是我的玩家类:
class Player(pg.sprite.Sprite):
def __init__(self,game):
pg.sprite.Sprite.__init__(self)
self.image = pg.Surface((30, 40))
self.game = game
self.image.fill(YELLOW)
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, HEIGHT / 2)
self.pos = vec(WIDTH / 2, HEIGHT / 2)
self.vel = vec(0, 0)
self.acc = vec(0, 0)
def jump(self):
self.rect.y += 1
hits = pg.sprite.spritecollide(self, self.game.platforms, False)
self.rect.y -= 1
if hits:
self.vel.y = -15
def update(self):
self.acc = vec(0, PLAYER_GRAV)
keys = pg.key.get_pressed()
if keys[pg.K_LEFT]:
self.acc.x = -PLAYER_ACC
if keys[pg.K_RIGHT]:
self.acc.x = PLAYER_ACC
self.acc.x += self.vel.x * PLAYER_FRICTION
self.vel += self.acc
self.pos += self.vel + 0.5 * self.acc
self.rect.midbottom = self.pos
这是我的平台类:
class Platform(pg.sprite.Sprite):
def __init__(self, x, y ,w, h):
pg.sprite.Sprite.__init__(self)
self.image = pg.Surface((w,h))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.centerx = x+(w/2)
self.centery = y+(h/2)
以下是我目前如何进行碰撞(仅适用于平台顶部)
hits = pg.sprite.spritecollide(self.player,self.platforms, False)
if hits:
self.player.pos.y = hits[0].rect.top+1
self.player.vel.y = 0
编辑:
我已将此添加到我的播放器类中,并且每次播放器更新时都会运行它,它几乎可以正常运行。
def wall_collisions(self):
self.rect.centerx = self.pos.x
for wall in pg.sprite.spritecollide(self, self.walls, False):
if self.vel.x > 0:
self.rect.right = wall.rect.left
self.vel.x = 0
elif self.vel.x < 0:
self.rect.left = wall.rect.right
self.vel.x = 0
self.pos.x = self.rect.centerx
self.rect.centery = self.pos.y
for wall in pg.sprite.spritecollide(self, self.walls, False):
if self.vel.y > 0:
self.rect.bottom = wall.rect.top
self.vel.y = 0
elif self.vel.y < 0:
self.rect.top = wall.rect.bottom
self.vel.y = 0
self.pos.y = self.rect.centery
平台游戏顶部的碰撞工作,并且ALMOST侧面的碰撞始终有效,除非我按下玩家然后跳跃。如果我试图击中平台底部的播放器,它会将我射向平台的任何一侧。有什么帮助吗?
答案 0 :(得分:0)
我找到了一个有效的解决方案。以下代码非常有效。
def wall_collisions(self):
self.rect.centerx = self.pos.x
for wall in pg.sprite.spritecollide(self, self.walls, False):
if self.vel.x > 0:
self.rect.right = wall.rect.left
self.vel.x = 0
elif self.vel.x < 0:
self.rect.left = wall.rect.right
self.vel.x = 0
self.pos.x = self.rect.centerx
self.rect.centery = self.pos.y
for wall in pg.sprite.spritecollide(self, self.walls, False):
if self.vel.y > 0:
self.rect.bottom = wall.rect.top
self.vel.y = 0
elif self.vel.y < 0:
self.rect.top = wall.rect.bottom
self.vel.y = 0
self.pos.y = self.rect.centery