如果我知道主体,如何将精灵附加到 box2d 主体上?
碰撞检测后,我可以获得碰撞的物体,但是如何获得附加到这些物体上的精灵,以便我也可以将它们从场景中删除?
例如,如果我有一个身体(玩家),这个身体与另一个身体(敌人)碰撞,我可以从接触侦听器中获取哪些身体发生碰撞,如下所示:
pContact.getFixtureA().getBody()
pContact.getFixtureB().getBody()
因此,如果我们假设我们有很多敌人,我怎样才能获得准确的精灵附着在每一具尸体上,这样我就可以将它们移除?
After collision detection I can get the bodies that collided, but how can I get the sprites attached to these bodies so I can remove them from the scene also?
For example if I had a body (player) this body collided with another body (enemy), I can get which bodies collide from the contact listener like this:
pContact.getFixtureA().getBody()
pContact.getFixtureB().getBody()
So if we assume that we have a lot of enemies how can I get the exact sprite attached to each one of the bodies so I can remove them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
免责声明:我的经验是在 iOS 中使用 Cocos2d/Box2D,但在 Android 中应该类似。
通常,当使用 Box2D 主体和精灵时,您可以使用精灵设置主体定义的 UserData 属性。示例:
设置 userData:
接触后检索精灵:
disclaimer: My experience is with Cocos2d/Box2D in iOS, but should be similar in Android.
Typically, when using Box2D bodies and sprites you set the UserData property of the Body Definition with the sprite. Example:
setting userData:
retrieving sprite after contact:
您应该有一个
Enemy
类,它有Body
和Sprite
。如果您有一个物体与另一个物体发生过接触,您可以迭代您的Enemy
对象列表,通过简单地比较它们来找到谁的物体。然后你就可以轻松获取这个Enemy
对象的精灵。希望我已经足够清楚地解释了我的想法。You should have an
Enemy
class, that has itsBody
andSprite
. If you have a body that had a contact with an another body, you can iterate over the list of yourEnemy
objects to find whose body was that by simply comparing them. Then you can easily get thisEnemy
object's sprite. Hope I've explained my idea clear enough.阅读此后AndEngine 论坛上的帖子,这是我的解决方案:
创建一个新的“UserData”类:
使用 UserData 类设置所有
body
的 UserData:然后您可以检测到碰撞和获取你的自定义精灵:
After read this thread on AndEngine forums, this is my solution:
Create a new "UserData" class:
Set the UserData of all your
body
s with the UserData class:Then you can detect the collision and get your CustomSprite:
在检查时:
做某事:
And while checking:
Doing something: