Sunday, January 18, 2015

Anansi: Enemies


Adding enemies is very easy with the mechanism we have. It's similar to the code in which we add the clouds.

In the original game the alien ship was called a "Tormentor". I took a screenshot of it and use it in the game. Of course as usual you can pick whatever image you prefer. If you'd like to use a plane, simply replace the one in our code with it.

Speaking of code, we create the image for the enemy and load it.

Image tormentor;
...
// enemy ship: tormentor
tormentor = new Image( getClass().getResource( "assets/vehicles/tormentor.png").toExternalForm());

And then we add the enemy at random intervals in our game loop.
// add enemies
// --------------------------
// add enemies at random intervals
if( rnd.nextInt(100) == 0) {
 
  // create sprite
  ImageView enemy = new ImageView( tormentor);

  // random speed
  double speed = rnd.nextDouble() * 1.0 + 1.0;
 
  // x position range: enemy is always fully inside the screen, no part of it is outside
  // y position: right on top of the view, so that it becomes visible with the next game iteration
  Sprite sprite = new Sprite( playfieldLayer, enemy, rnd.nextDouble() * (SCENE_WIDTH - enemy.getImage().getWidth()), -enemy.getImage().getHeight(), 0, speed);
  sprites.add( sprite);

}

The game with the enemies looks like this:


You can clearly distinguish the various layers we have.

Now we're eager to see how it all performs with lots of enemies. It all depends on the power of your machine. I reduced the randomness interval from 100 to 10 and got this still running at 60 FPS:


Even reducing it to 1 and spawning an enemy at every frame didn't cause the FPS to drop. Very awesome!



But let's not get ahead of ourselves. There are still a few things to do which may cost performance, one of them being that we'd like to shoot the enemy and see an explosion.

Code-wise I think we can certainly continue. In the intermediary summary section you've seen the current code base. It's not nice to have it all in one game loop. Moreover our sprites belong to different categories and we should make proper objects of them. It's time for refactoring in one of the next lessons.

No comments:

Post a Comment