【发布时间】:2014-10-26 10:48:27
【问题描述】:
我正在尝试在 Pygame 中创建一个有效的跳跃系统,但我遇到了一些碰撞检测问题。我有一个级别存储在这样的列表中:
level = [
"WWWWWWWWWWWWWWWWWWWW",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"W W",
"WWWWWWWWWWWWWWWWWWWW",
]
x = y = 0
for row in level:
for col in row:
if col == "W":
Wall((x, y))
x += 32
y += 32
x = 0
每个墙都附加到一个列表中,并根据其在网格中的位置给出一个位置。
这是墙类:
class Wall (pygame.sprite.Sprite):
def __init__(self,pos):
pygame.sprite.Sprite.__init__(self)
walls.append(self)
self.rect = pygame.Rect(pos[0],pos[1],32,32)
当按下向上键并检测到玩家与其中一个图块之间的碰撞时,我尝试将玩家矩形向上移动 30 像素:
if event.type == KEYDOWN and event.key == K_UP:
if player.hitCheck():
player.move(0,-30)
hitCheck(),Player类的一个函数,如下所示:
def hitCheck(self):
for wall in walls:
if self.rect.colliderect(wall.rect):
return True
但是,无论发生任何实际碰撞,该函数都不会返回 True。通过将碰撞播放器侧的值设置为所讨论的对面墙侧的值,我可以移动播放器矩形而不会穿过墙壁,但这不会产生任何结果。
为什么函数在碰撞时不返回 True?
walls 最初被声明为一个空列表。它用于作为播放器类的一部分的移动函数中:
def move_single_axis(self, dx, dy):
# Move the rect
self.rect.x += dx
self.rect.y += dy
for wall in walls:
if self.rect.colliderect(wall.rect):
if dx > 0: # Moving right; Hit the left side of the wall
self.rect.right = wall.rect.left
if dx < 0: # Moving left; Hit the right side of the wall
self.rect.left = wall.rect.right
if dy > 0: # Moving down; Hit the top side of the wall
self.rect.bottom = wall.rect.top
if dy < 0: # Moving up; Hit the bottom side of the wall
self.rect.top = wall.rect.bottom
这没有问题,这就是为什么我无法理解为什么 hitCheck() 无法检测到碰撞。
【问题讨论】:
-
在hitCheck中,最后一条语句怎么没有return False?
-
为了这个问题我删除了它,因为我只想弄清楚为什么 hitCheck 不会返回 True。
-
作为记录,您是否验证了您的墙实际上已添加到墙列表中并且初始化代码中没有某种错误?
-
是的,游戏渲染并且除了跳跃之外还有功能性运动。