我的碰撞检测无法正常工作

问题描述

我当时正在使用pygame和math模块用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,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,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,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,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,playerY)
collision2 = collide2(sNowX,playerY)
collision3 = collide3(glacierX,playerY)
collision4 = collide4(boardX,playerY)
collision5 = collide5(iceX,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!")

请告诉我我在哪里做错了。

解决方法

现在,仅当距离恰好为27时才发生碰撞。如果假设球体,则当它们小于27像素时,仍可以将它们视为“碰撞”。

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

要注意的另一件事是计算平方根非常慢。首先检查distance_squared <= 27 * 27,然后检查math.pow(distance_squared,0.5) <= 27

,

实际上,您只是在检查玩家是否正在触摸障碍物,但是如果玩家与障碍物相交,则会错过碰撞。您必须评估是否是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,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!")