Game Development Reference
In-Depth Information
Here we run four tests and if all pass we can say that rectangle A is inside or over-
lapping B. This is done by checking the following conditions:
• The left side of A is always inside or to the left of B
• The right side of A is always inside or to the right of B
• The top of A is always inside or above B
• The bottom of A is always inside or below B
One assumption made by this system is that we are working in a 2D plane, where
Y increases towards the bottom of the screen. If you're working with a traditional
Cartesian co-ordinate system where Y increases towards the top of the screen, ad-
just the algorithm accordingly.
Note
For a great demo of this collision technique, visit http://silentmatt.com/rectangle-
intersection/ .
Now we need to add this in to the game so that when enemies collide with the player
or leave the play area they are destroyed. To do this we will add a RectangleCol-
lider to the Ship class, and create it in the constructor. The next step is to ensure
that we update the RectangleCollider::Position property each time the ship
moves but be careful to offset it to the top left corner of the image rather than just the
position of the ship. We do this to ensure that the bounding rectangle always con-
tains the ship, even when moving. Remember that we render the ship with an origin
in the centre of the image, and the collider doesn't know about this. Here's an ex-
ample of the code we need to add to Ship::LoadTexture to set up the collider:
_collider->Position = XMFLOAT2(_position.x -
_sprite->Origin.x, _position.y -
_sprite->Origin.y);
_collider->Size = _sprite->GetSize();
As you can see, we use the position of the ship, but remove the offset created by the
origin before setting the position of the collider. We also need to set the size of the
collider to the size of the texture once it has loaded.
Search WWH ::




Custom Search