I use the following chunk of code to make bullets that fire towards the player's ship:
@Override
public void onTimePassed(final TimerHandler pTimerHandler)
{
pTimerHandler.reset();
if(spawnBullets){
for(int i = 0; i < enemies.size(); i++){
if(enemies.get(i).isShooter()){
//shoot from this enemy to ship
final Vector2 v = new Vector2(ship.getX() - enemies.get(i).getSprite().getX(),ship.getY() - enemies.get(i).getSprite().getY());
v.nor();
v.mul(BULLET_SPEED);
createEnemyBullet(enemies.get(i).getSprite().getX(),enemies.get(i).getSprite().getY(), v);
}
}
}
}
This works fine if the enemy is stationary, i.e. just a Sprite
with no Body
, but when the enemy is moving, my game completely freezes up. Sometimes it will happen immediately (on the first attempt to fire), or sometimes 1 or 2 bullets later.
It gets through this code (a log output after createEnemyBullet
works fine), but locks up somewhere before anything else happens. Disabling this section of code makes the problem go away. What could be going wrong?
Edit
Here is createEnemyBullet()
:
private void createEnemyBullet(float x, float y, Vector2 v){
//remove old bullet
if(enemyBullets[enemyBulletCounter] != null){
makeBulletExplosion(bullets[i].getX(),bullets[i].getY());
mScene.detachChild(bullets[i]);
mBulletPhysicsWorld.destroyBody(bulletsPhysical[i]);
bullets[i] = null;
}
//create new bullet
enemyBullets[enemyBulletCounter] = new AnimatedSprite(x +8, y +8, this.mEnemyBulletTextureRegion); //Nasty magic number, oh well
enemyBulletsBody[enemyBulletCounter] = PhysicsFactory.createCircleBody(this.mBulletPhysicsWorld, enemyBullets[enemyBulletCounter], BodyType.KinematicBody, BULLET_FIXTURE_DEF);
enemyBullets[enemyBulletCounter].animate(55);
enemyBulletsBody[enemyBulletCounter].setLinearVelocity(v);
this.mBulletPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(enemyBullets[enemyBulletCounter], enemyBulletsBody[enemyBulletCounter], true, true));
this.mScene.attachChild(enemyBullets[enemyBulletCounter]);
//update counter
enemyBulletCounter = enemyBulletCounter < ENEMY_BULLET_MAX -1 ? enemyBulletCounter + 1 : 0;
}
createEnemyBullet
function, though there may be a problem with another section of your code that is showing itself whenever you call this function(meaning this function doesn't have any errors at all). \$\endgroup\$createEnemyBullet()
are being calculated once, thencreateEnemyBullet()
is run, if this isn't that case that could potentially cause a problem. \$\endgroup\$