简体   繁体   English

如何检测pygame中的碰撞?

[英]How do I detect collisions in pygame?

I am making an asteroids space shooter style game and I can't work out how to do collisions between my bullets and the asteroids/aliens and of course the ship. 我正在制作一个小行星太空射击游戏风格的游戏,我无法弄清楚如何在我的子弹和小行星/外星人之间进行碰撞,当然还有船。

I tried checking positions but my method was overly complicated, lagged the game, and didn't actually work at all. 我尝试检查位置,但我的方法过于复杂,落后于游戏,并且实际上根本没有工作。

My attempt: 我的尝试:

        for missile in missiles:
            for asteroid in asteroids:
                if missiles[missile][0] > asteroids[asteroid][0] or missiles[missile][0] + 20 < asteroids[asteroid][0] + 70:
                    # remove missile and asteroid

Say I have an asteroid and a ship and also a bullet I want it so that when asteroid and bullet collide they both are destroyed and the ship isn't, but when asteroid and ship collide they are both destroyed. 假设我有一颗小行星和一艘船,还有一颗子弹我想要它,这样当小行星和子弹相撞时它们都会被摧毁而船却没有,但是当小行星和船碰撞时它们都被摧毁了。

Collision checks check for overlaps on the horizontal or vertical positions: 碰撞检查检查水平或垂直位置的重叠:

if obj1.y + obj1.radius > obj2.y - obj2.radius
if obj1.y - obj1.radius < obj2.y - obj2.radius

Do the same for the x direction, but remember that the directions are flipped in terms of in which direction the pixels go up x方向执行相同操作,但请记住,按照像素向上的方向翻转方向

PyGame already provides collision detection between Sprites. PyGame已经在Sprites之间提供了碰撞检测。 The collision detection handed off to some C code and is highly optimized. 碰撞检测传递给某些C代码并进行了高度优化。 You shouldn't attempt to re-evaluate collision calculations within Python as it certainly won't be as fast as PyGame's native solution and it is introducing the opportunity for new bugs. 您不应该尝试重新评估Python中的冲突计算,因为它肯定不会像PyGame的本机解决方案那样快,并且它会引入新bug的机会。

Review the documentation here: https://www.pygame.org/docs/ref/sprite.html 查看此处的文档: https//www.pygame.org/docs/ref/sprite.html

It will provide information on how to implement proper collision detection between sprites. 它将提供有关如何在精灵之间实现正确碰撞检测的信息。

For your given example, I am assuming that your individual missiles and astroids are both Sprites within PyGame. 对于你给出的例子,我假设你的单个导弹和星形都是PyGame中的精灵。

Then I am assuming that the individual missiles and astroids are in Sprite Groups called 'missiles' and 'astroids'. 然后我假设单个导弹和星形在Sprite组中称为“导弹”和“星形”。

If that is true, you could simply do the following: 如果是这样,您可以简单地执行以下操作:

pygame.sprite.groupcollide(missiles, astroids, true, true)

This will check for collisions between the missiles and astroids and kill/destroy any of sprites for which a collision is detected. 这将检查导弹和星体之间的碰撞,并杀死/摧毁任何检测到碰撞的精灵。 You can also provide a custom collision calculation function to determine the collisions if your sprites don't have a 'rect' value. 如果精灵没有'rect'值,您还可以提供自定义碰撞计算功能来确定碰撞。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM