In the fourth installment of his five-part app developer series, William J. Francis provides the code to be able to detect when the asteroid and the ship collide in this Android game.
The goal of the Android game we are developing in this series is to adjust the flying saucer’s momentum in order to avoid getting smashed to bits by the asteroid. While simplistic, the project incorporates all the essential aspects of a video game: a canvas, sprites, animation, collision detection, and user input.
In our last tutorial we managed to get our sprites moving around the screen. (If you're new to this series, catch up on parts one and two, respectively: Prepare the canvas and Load and display sprites.) Now we need to be able to detect when the asteroid and the ship collide. There are basically two techniques for collision detection: bounding algorithms and image masking. Bounding is easier and takes up fewer CPU cycles than image masking; however, bounding is not normally accurate enough for arcade type games. Just what is the difference? Well, consider our two images. I have them both on a 50x50 pixel background, but the contents of those sprites don't fill the entire 50x50 pixel grid. Take a look at the illustrations in Figure A and Figure B.
Figure A