猿问

在python中查找对象之间的距离 - 不起作用

我目前正在Python上制作一个简单的轻飘飘的鸟类游戏。由于某种原因,当管道和鸟接触时,碰撞代码不起作用。


def collision():

    global distanceDown, distanceUp

    distanceUp = math.sqrt(math.pow(pipeUpX - birdX, 2) + math.pow(pipeUpY - birdY, 2))  # distance formula

    distanceDown = math.sqrt(math.pow(pipeDownX - birdX, 2) + math.pow(pipeDownX - birdY, 2))


    if distanceUp <= 20 or distanceDown <= 20:

        return True

    else:

        return False

我已经在主游戏循环中调用了该函数,并要求python结束游戏(如果为真),但鸟只是通过管道。仅供参考,我没有使用OOP和类。以下是值。


pipeWidth = 50

pipeHeight = 130

pipeUpX = 800

pipeUpY = 0

pipeDownY = screenY - pipeHeight

pipeDownX = 900

pipeX_change = 1

另外,我对python和编程作为一个整体非常陌生,所以请用易于理解的代码回答。谢谢你:)


HUWWW
浏览 130回答 1
1回答

德玛西亚99

该代码不会验证到管道的距离。该代码验证到管道起点和终点的距离。这是另一回事。由于您的对象只是矩形,我建议使用和方法。例如,一些伪代码:pygame.Rect objecctscolliderectdef&nbsp;collision():&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;pipeRect&nbsp;=&nbsp;pygame.Rect(pipeLeft,&nbsp;pipeTop,&nbsp;pipeWidth,&nbsp;pipeHeight)&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;birdRect&nbsp;=&nbsp;pygame.Rect(birdLeft,&nbsp;birdTop,&nbsp;birdWidth,&nbsp;birdHeight)&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;pipeRect.colliderect(birdRect)对于“图像”的碰撞,我建议分别使用pygame.精灵.精灵/pygame.sprite.collide_mask()pygame.mask.mask.pygame.mask.mask.overlap()。
随时随地看视频慕课网APP

相关分类

Python
我要回答