Sunday, January 25, 2015

Anansi: Collisions - Revisited


We already have the option to detect collsions. But there are a few things we have to consider in addition to the existing mechanism:

  • a sprite should only explode when its health is depleted
  • we only want 1 explosion per sprite
  • the exploding sprite should stop its movement

So we have to extend our checkBulletCollisions and checkMissileCollisions classes. Thinking of it, the classes are very similar - for now. I split them because maybe we'll add a mini-explosion to a detonating missile, but let's combine them until we actually add the mini-explosion.

/**
 * Check if a projectile (eg player bullet/missile) hits an enemy.
 * If a collision is detected, the enemy is damaged. If enemy is killed, an explosion is spawned.
 * @param projectileList
 */
private void checkProjectileCollisions( List projectileList) {
 
 for( SpriteBase projectile: projectileList) {
  for( Enemy enemy: enemyList) {
   
   // consider only alive sprites
   if( !enemy.isAlive())
    continue;

   if( projectile.collidesWith(enemy)) {
    
    // inflict damage, reduce enemy's health
    enemy.getDamagedBy(projectile);

    // explosion animation
    if( !enemy.isAlive()) {
     
     // stop movement of sprite
     enemy.stopMovement();
     
     // let enemy explode
     spawnExplosion( enemy);
    }

    // destroy bullet, set health to 0
    projectile.kill();
    
    // remove the bullet from screen by flagging it as removable
    projectile.remove();
    
   }
  }
 }
}

Blogspot again modifies the code. This would be the correct method signature: checkProjectileCollisions( List<? extends SpriteBase> projectileList)

The modified invocation method.
// check collisions
// ---------------------------
checkProjectileCollisions( playerBulletList);
checkProjectileCollisions( playerMissileList);

We modify the SpriteBase class with the stopMovement code
boolean canMove = true;

...

/**
 * Set flag that the sprite can't move anymore.
 */
public void stopMovement() {
 this.canMove = false;
}

...

public void move() {

 if( !canMove)
  return;
 
 x += dx;
 y += dy;
 r += dr;

} 

Now we can hit something and get animated explosions:



That looks very nice and smooth. Okay, now we're curious about the performance. Let's change the enemy spawning value and our own bullet fire rate to see how it performans with lots of explosions:


It performs quite well. This means we can wreak havoc on screen. Awesome!

No comments:

Post a Comment