Beginning Android Tablet Games Programming by Jeremy Kerfs

Beginning Android Tablet Games Programming by Jeremy Kerfs

Author:Jeremy Kerfs
Language: eng
Format: epub, pdf
Publisher: Apress®
Published: 2011-11-22T16:00:00+00:00


Detecting Collisions Between Sprites

The next big change requires an entirely new function in the SpriteObject class to deal with collisions. If you have done 2D collision detection before, the solution will look familiar. The function tests two rectangles for a collision. Recall that because the screens in Android have their origin in the upper-left corner, if the bottom of the first sprite is less than the top of the other sprite, then there is no collision because the first sprite is above the second one on the screen.

If there is a collision between the two sprites, then the new method returns true. Intriguingly, when you search for collisions, you use the bitmap to gather the width. Your sprite class doesn’t store the width or height directly because it’s already contained in the bitmap. You use this approach to get the dimensions of a sprite later for collisions with walls.

As with any function that requires a series of if statements, your collision detection is moderately expensive in terms of processing. You want to eliminate needless collision routines if possible. This is, however, much better than doing pixel-by-pixel detection that can cause games to reach a near standstill.

Add the function in Listing 5-2 to the SpriteObject class.

Listing 5-2. The collision detection function in SpriteObject class

public boolean collide(SpriteObject entity){

double left, entity_left;

double right, entity_right;

double top, entity_top;

double bottom, entity_bottom;



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.