我的碰撞检测工作不正常



我使用pygame和数学模块在python中编程游戏。我写这些代码是为了进行碰撞检测(我制作了5个障碍物,我希望我的玩家与之碰撞(,但问题是在玩游戏的过程中,有时有效,有时无效。

这些是我定义的碰撞函数

def collide1(binX, binY, playerX, playerY):
distance = math.sqrt(math.pow(binX - playerX, 2) + math.pow(binY - playerY, 2))
if distance == 27:
return True
else:
return False

def collide2(snowX, snowY, playerX, playerY):
distance = math.sqrt(math.pow(snowX - playerX, 2) + math.pow(snowY - playerY, 2))
if distance == 27:
return True
else:
return False

def collide3(glacierX, glacierY, playerX, playerY):
distance = math.sqrt(math.pow(glacierX - playerX, 2) + math.pow(glacierY - playerY, 2))
if distance == 27:
return True
else:
return False

def collide4(boardX, boardY, playerX, playerY):
distance = math.sqrt(math.pow(boardX - playerX, 2) + math.pow(boardY - playerY, 2))
if distance == 27:
return True
else:
return False

def collide5(iceX, iceY, playerX, playerY):
distance = math.sqrt(math.pow(iceX - playerX, 2) + math.pow(iceY - playerY, 2))
if distance == 27:
return True
else:
return False

在while循环中

# Collision Detection
collision1 = collide1(binX, binY, playerX, playerY)
collision2 = collide2(snowX, snowY, playerX, playerY)
collision3 = collide3(glacierX, glacierY, playerX, playerY)
collision4 = collide4(boardX, boardY, playerX, playerY)
collision5 = collide5(iceX, iceY, playerX, playerY)
if collision1:
print("You have collided!")
elif collision2:
print("You have collided!")
elif collision3:
print("You have collided!")
elif collision4:
print("You have collided!")
elif collision5:
print("You have collided!")

请告诉我我哪里做错了。

实际上,你只是在检查玩家是否碰到了障碍物,但如果玩家遇到障碍物,你会错过碰撞。您必须评估是distance <= 27而不是distance == 27。此外,为碰撞测试实现1个功能是完全足够的。

def collide(x1, y1, x2, y2):
distance = math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2))
if distance <= 27:
return True
else:
return False

功能可以进一步简化:

def collide(x1, y1, x2, y2):
distance = math.hypot(x1 - x2, y1 - y2)
return distance <= 27

使用循环进行碰撞测试:

obstacles = [(binX, binY), (snowX, snowY), (glacierX, glacierY), (boardX, boardY), (iceX, iceY)]
for x, y in obstacles:
collision = collide(x, y, playerX, playerY)
if collision:
print("You have collided!")

现在,只有当距离正好为27时,才会发生碰撞。如果你假设球体,你仍然可以考虑它们;"碰撞";如果它们小于27像素appert。

因此,用if distance <= 27:替换所有距离。注意小于或等于。

另一件需要注意的事情是计算平方根非常慢。检查distance_squared <= 27 * 27比检查math.pow(distance_squared, 0.5) <= 27快得多。

最新更新