cocos2d精灵碰撞
我有一个同时显示的 CCSprites 数组。 每个精灵都有一个移动路径,移动路径是屏幕上的随机点。
所有精灵同时移动到屏幕上的随机点。
我想做的是检测精灵之间的碰撞,然后改变它们的移动路径。
是否可以?
I have an Array of CCSprites that being displayed all at once.
Every sprite has a movement path, a movement path is a random point on screen.
All the sprites are moving all at once to random points on screen.
What I want to do is to detect collision between the sprites and then change their movement path.
Is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
迭代数组中的每个
CCSprite
(将其称为A
),并在每次迭代时再次迭代每个CCSprite
在数组中(当然不包括A
本身)(将此称为B
)。现在,使用CGRectIntersectsRect
和boundingBox
来查找它们之间的碰撞。它是这样的:编辑:但是,当然,如果两个精灵发生碰撞,“碰撞事件”可能会发生两次(首先从精灵 A 的角度来看,然后从精灵 A 的角度来看)精灵 B) 的视角。
如果您只想每次检查时触发一次碰撞事件,则需要记住这些对,以便可以忽略该检查中已经发生的碰撞。
您可以通过无数种方法来检查这一点,但这里有一个示例(更新的代码):
再次编辑:
Iterate through every
CCSprite
in your array (call itA
), and for every iteration iterate again through everyCCSprite
in the array (excludingA
itself of course) (call this oneB
). Now, useCGRectIntersectsRect
along withboundingBox
to find a collision between them. It goes something like this:Edit: But of course, it is possible that if two sprites collide, the "collision event" will occur twice (first from the point of view of sprite A, and then from the point of view of sprite B).
If you only want the collision event to trigger once every check, you will need to memorize the pairs so that you can ignore collisions that already did happen on that check.
There are countless ways you could check for that, but here's an example (updated code):
Edited again:
看看这个SO答案。
您可以使用
CGRectIntersectsRect
和节点boundingBox
进行简单的碰撞检测。如果您需要更高级的功能,请查看物理引擎,例如 chipmunk 或 Box2D。Have a look at this S.O. answers.
You can do simple collision detection using
CGRectIntersectsRect
and the nodeboundingBox
. If you need more advanced features, have a look at a physics engine like chipmunk or Box2D.如果您有兴趣的话,Ray Wenderlich 写了一篇关于使用 Box2D 进行碰撞检测的很好的教程。 http://www .raywenderlich.com/606/how-to-use-box2d-for-just-collision-detection-with-cocos2d-iphone
首先检查你的精灵是否可以近似由矩形。如果是这样,那么@Omega 的回答就很棒了。如果它们不能,可能是因为它们包含大量透明度或出于其他原因,您可能需要使用多边形来近似您的精灵并使用它们。
Ray Wenderlich has written a good tutorial about using Box2D just for collision detection, if you're interested in going that way. http://www.raywenderlich.com/606/how-to-use-box2d-for-just-collision-detection-with-cocos2d-iphone
Check first that your sprites can be approximated by rectangles. If so then @Omega's answer was great. If they can't be, perhaps because they contain a lot of transparency or for some other reason, you might need to approximate your sprites with polys and work with those.