开发者

How should I reset a Sprite's location when it is attached to a Body?

开发者 https://www.devze.com 2023-03-31 22:46 出处:网络
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 loc

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;
            }
        }
    }
}


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:

@Override
protected void onHandleRecycleItem(final Bullet pBullet) {
    pBullet.disable();
    pBullet.getSprite().setPosition(-1, -1);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消