1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Finishing up the Game

By

3 of 3

Collision Detection

Great, now we have bullets in groups all ready for collisions, so let's do it! Here, I've decided to put the collision detection calls inside the main loop. It could have been abstracted a bit, but it's pretty short anyway. If this game got much bigger, you'd probably want to clean that up but as it is right now, this is fine.

 player.update(delta)
enemies.update(delta)

 player.bullets.collide_group(enemies) do|bul,enem|
enem.kill
bul.kill
end

unless enemies.bullets.collide_sprite(player).empty?
player.die
end
 
background.blit( screen, [0,0] )
player.draw( screen )
enemies.draw( screen )
 

Here's a section of the main loop showing the collision detection. As you can see, it's pretty straightforward. The player's bullets are checked for collisions against the entire enemy formation. For every collision, the block which kills both the bullet and the enemy is run. The same thing is repeated for collisions against the alien bullets and the player (only with slightly different conditional syntax).

  1. About.com
  2. Technology
  3. Ruby
  4. Tutorials
  5. Game Programming
  6. Finishing up the Game

©2014 About.com. All rights reserved.