i'm creating a bullet with physics body. Bullet class (extends Sprite class) has die() method, which unregister physics connector, hide sprite and put it in pool
public void die() {
Log.d("bulletDie", "See you in hell!");
if (this.isVisible()) {
this.setVisible(false);
mPhysicsWorld.unregisterPhysicsConnector(physicsConnector);
physicsConnector.setUpdatePosition(false);
body.setActive(false);
this.setIgnoreUpdate(true);
bulletsPool.recyclePoolItem(this);
}
}
in onUpdate method of PhysicsConnector i executes die method, when sprite leaves screen
physicsConnector = new PhysicsConnector(this,body,true,false)
{
@Override
public void onUpdate(final float pSecondsElapsed) {
super.onUpdate(pSecondsElapsed);
if (!camera.isRectangularShapeVisible(_bullet)) {
Log.d("bulletDie","Dead?");
_bullet.die();
}
}
};
it works as i expected, but _bullet.die() executes TWICE.
what i`m doing wrong and is it right way to hide sprites?
here is full code of Bullet class (it is inner class of class that represents player)
private class Bullet extends Sprite implements PhysicsConstants {
private final Body body;
private final PhysicsConnector physicsConnector;
private final Bullet _bullet;
private int id;
public Bullet(float x, float y, ITextureRegion texture, VertexBufferObjectManager vertexBufferObjectManager) {
super(x,y,texture,vertexBufferObjectManager);
_bullet = this;
id = bulletId++;
body = PhysicsFactory.createCircleBody(mPhysicsWorld, this, BodyDef.BodyType.DynamicBody, bulletFixture);
physicsConnector = new PhysicsConnector(this,body,true,false)
{
@Override
public void onUpdate(final float pSecondsElapsed) {
super.onUpdate(pSecondsElapsed);
if (!camera.isRectangularShapeVisible(_bullet)) {
Log.d("bulletDie","Dead?");
Log.d("bulletDie",id+"");
_bullet.die();
}
}
};
mPhysicsWorld.registerPhysicsConnector(physicsConnector);
$this.getParent().attachChild(this);
}
public void reset() {
final float angle = canon.getRotation();
final float x = (float) ((Math.cos(MathUtils.degToRad(angle))*radius) + centerX) / PIXEL_TO_METER_RATIO_DEFAULT;
final float y = (float) ((Math.sin(MathUtils.degToRad(angle))*radius) + centerY) / PIXEL_TO_METER_RATIO_DEFAULT;
this.setVisible(true);
this.setIgnoreUpdate(false);
body.setActive(true);
mPhysicsWorld.registerPhysicsConnector(physicsConnector);
body.setTransform(new Vector2(x,y),0);
}
public Body getBody() {
return body;
}
public void setLinearVelocity(Vector2 velocity) {
body.setLinearVelocity(velocity);
}
public void die() {
Log.d("bulletDie", "See you in hell!");
if (this.isVisible()) {
this.setVisible(false);
mPhysicsWorld.unregisterPhysicsConnector(physicsConnector);
physicsConnector.setUpdatePosition(false);
body.setActive(false);
this.setIgnoreUpdate(true);
bulletsPool.recyclePoolItem(this);
}
}
}