当 Sprite 附加到 Body 时,我应该如何重置它的位置?
我在游戏中使用池来管理子弹。唯一的问题是,当从池中获取刚刚因碰撞而被回收的 Bullet 时,虽然它的 Body 位置在初始化时使用 Body.setTransform()
重置,但 Bullet 的位置Sprite 的位置(用于使用 Sprite.collidesWith(otherSprite)
检测碰撞)重置得不够快(因为它是在物理线程中更新的)。这意味着新创建的子弹在创建时会立即发生碰撞,从而导致单个子弹引起多次碰撞。
我尝试在初始化时调用 Bullet.sprite.setPosition(0,0)
,但这显然会造成干扰,因为使用该行代码根本无法显示项目符号。我应该怎么做才能防止这个问题?
子弹创建:
bullets[bulletCounter] = bulletPool.obtainPoolItem();
bullets[bulletCounter].getBody().setTransform(shipBody.getTransform().getPosition(),0);
bullets[bulletCounter].getBody().setLinearVelocity(shipBody.getLinearVelocity());
bullets[bulletCounter].activate();
碰撞检测:
for(int i = 0; i < BULLET_MAX; i++){
if(bullets[i] != null && bullets[i].isActive()){
for(int j = 0; j < enemies.size(); j++){
//check for collision!
if(bullets[i].getSprite().collidesWith(enemies.get(j).getSprite())){
//-snip-
break;
}
}
}
}
I am using a Pool to manage Bullets in my game. The only problem is when a Bullet is obtained from the pool having just been recycled because it was involved in a collision, although it's Body's location is reset using Body.setTransform()
when it is initialized, the Bullet's Sprite's location (which is used to detect collisions using Sprite.collidesWith(otherSprite)
) is not reset quick enough (as it's updated in a Physics thread). This means the newly created bullet causes a collision the instant it is created, resulting in a single bullet causing more than one collision.
I tried calling Bullet.sprite.setPosition(0,0)
when it is initialized, but this clearly interferes, as Bullets fail to be displayed at all with that line of code in place. What should I do to prevent this problem?
Bullet Creation:
bullets[bulletCounter] = bulletPool.obtainPoolItem();
bullets[bulletCounter].getBody().setTransform(shipBody.getTransform().getPosition(),0);
bullets[bulletCounter].getBody().setLinearVelocity(shipBody.getLinearVelocity());
bullets[bulletCounter].activate();
Collision Detection:
for(int i = 0; i < BULLET_MAX; i++){
if(bullets[i] != null && bullets[i].isActive()){
for(int j = 0; j < enemies.size(); j++){
//check for collision!
if(bullets[i].getSprite().collidesWith(enemies.get(j).getSprite())){
//-snip-
break;
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我很想知道您在调用
onHandleObtainItem
从池中获取子弹时正在做什么。当您调用
onHandleRecycleItem
时,将精灵位置设置为某个离屏值是否没有意义,例如:I'd be interested to see what you're doing around the time you invoke
onHandleObtainItem
to get a bullet from the pool.Would it not make sense to set the sprite position to some offscreen value when you invoke
onHandleRecycleItem
, something like: