spritecollide
,同时更新位置:我正在使用pygame广告制作tilemap平台游戏,我为玩家定义了X和Y运动,还定义了代表重力以使其正确跳跃的Y力。但是,当我的玩家掉落到地面并开始游戏时,由于使他往下压]的重力,它既不能正确地向右也不能正确地向左移动。除此之外,当玩家跳跃并且我将其向右移动时,就好像它无法识别与墙底矩形的碰撞(请参见下面的gif的视觉说明)。 >
我曾尝试在玩家撞击地面时禁用该重力,并在玩家跳跃时启用重力,但它并未按预期工作,并且在管理碰撞时遇到问题(此外,禁用重力吧?)
这是我的播放器类:class Player(pg.sprite.Sprite):
def __init__(self, game, x, y):
self.groups = game.sprites
pg.sprite.Sprite.__init__(self, self.groups)
self.game = game
self.image = pg.Surface((TILESIZE, TILESIZE))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.move_left = self.move_right = False
self.pos = pg.math.Vector2(x, y)
self.acc = pg.math.Vector2(0, GRAVITY)
self.vel = pg.math.Vector2(0, 0)
def jump(self):
self.vel.y -= 3
def update(self):
self.vel.x = 0
if self.move_left:
self.vel.x = -PLAYER_SPEED
if self.move_right:
self.vel.x = PLAYER_SPEED
self.vel += self.acc
self.pos += self.vel
self.rect.x = self.pos.x * TILESIZE
self.rect.y = self.pos.y * TILESIZE
if self.vel.y > 0.5:
self.vel.y = 0.5
hits = pg.sprite.spritecollide(self, self.game.walls, False)
if hits:
if self.vel.x > 0:
self.pos -= self.vel
self.rect.right = hits[0].rect.left
self.vel.x = 0
if self.vel.x < 0:
self.pos -= self.vel
self.rect.left = hits[0].rect.right
self.vel.x = 0
hits = pg.sprite.spritecollide(self, self.game.walls, False)
if hits:
if self.vel.y > 0:
self.pos -= self.vel
self.rect.bottom = hits[0].rect.top
self.vel.y = 0
if self.vel.y < 0:
self.pos -= self.vel
self.rect.top = hits[0].rect.bottom
self.vel.y = 0
我正在使用pygame广告制作tilemap平台游戏,我为玩家定义了X和Y运动,还定义了代表重力以使其正确跳跃的Y力。但是,当我的播放器...
spritecollide
,同时更新位置: hits = pg.sprite.spritecollide(self, self.game.walls, False)
if hits:
# If one of these conditions are true, the position will be updated,
# continuing the previous velocity, i.e. going through the roof.
if self.vel.x > 0:
self.pos -= self.vel
# [...]
if self.vel.x < 0:
self.pos -= self.vel
# [...]
# After you go through the roof, there's no more collision...
hits = pg.sprite.spritecollide(self, self.game.walls, False)
if hits:
if self.vel.y > 0:
self.pos -= self.vel
# [...]
self.vel.y = 0
两种情况,使用当前代码:
spritecollide
确实返回了一个非空的hits
,您将在屋顶反弹。if hits:
为False。hits = pg.sprite.spritecollide(self, self.game.walls, False)
一次,并且在更新所有速度之前请勿更改位置。spritecollide
,同时更新位置: