Game Development Reference
In-Depth Information
int thisx = b.X
( int )(GlobalPosition.X
origin.X) + x;
int thisy = b.Y
( int )(GlobalPosition.Y
origin.Y) + y;
int objx = b.X
( int )(obj.GlobalPosition.X
obj.origin.X) + x;
int objy = b.Y
( int )(obj.GlobalPosition.Y
obj.origin.Y) + y;
Finally, we check if both pixels are not transparent at these local positions. If that is
the case, we have a collision:
if (sprite.GetPixelColor(thisx, thisy).A != 0
&& obj.sprite.GetPixelColor(objx, objy).A != 0)
return true ;
Here you can see that we reuse the GetPixelColor method that we developed in the
Jewel Jam game. Now that our basic collision detection methods are implemented,
we can simply check if two game objects collide by calling the CollidesWith method:
if ( this .CollidesWith(enemy))
ouch...
27.9 Handling Collisions Between the Character and the Tiles
In the Tick Tick game, we need to detect collisions between the character and the tiles.
We will do this in a method called HandleCollisions , which we call from the Update
method in the Player class. The idea behind this is that we do all the calculations for
jumping, falling and running first (we did this in the previous sections). If there is a
collision between the character and the tile, we correct the position of the character
so that it no longer collides. Inside the HandleCollisions method, we walk through the
grid of tiles, and we check if there is a collision between the bounding box of the
character and the bounding box of the tile we are currently examining.
We do not need to check all the tiles in the grid, only those close to the current
location of the player. We can calculate the closest tile to the position of the player
as follows:
TileField tiles = GameWorld.Find("tiles") as TileField;
int x_floor = ( int )position.X / tiles.CellWidth;
int y_floor = ( int )position.Y / tiles.CellHeight;
Now we can use a nested for -instruction to look at the tiles surrounding the player.
In order to account for fast jumping and falling, we will take more tiles into ac-
count in the y direction. Inside the nested for -instruction, we will then check if the
player is colliding with the tile. However, we only need to do that if the tile is not a
background tile. The code to do all that is given as follows:
Search WWH ::




Custom Search