In the last article we created the basic elements we needed for the game like a player, some enemies and some weapons. However none of them could interact – the players bullets (and the player itself) would pass right through an enemy. To enable this sort of interaction this we need some way of detecting collisions.
Our implementation of collision detection here will be quite straight forward: we will simply test to see if the rectangles that define the area of a game element overlap. If they do, we have a collision, in which case one of those elements will be removed from the game. For example if one of the players weapon elements overlaps with an enemy, a collision is detected and the weapon is removed form the game (and, in this demo, the enemy is removed as well).
The Flash version of the game made use of the built in rectangle intersection test to see if two rectangles were overlapping. Silverlight doesn’t have such a test, forcing us to create our own. The function RectIntersect in MathUtils will do that job for us.
MathUtils.cs C# Silverlight source code
The CollisionManager class will be used to check for the collisions between GameObjects. It contains a mapping of which GameObjects (via their collisionNames) collide with each other, and once per frame loops through each GameObject and determines if any are overlapping. If so it fires off a call to the GameObjects collision function.
CollisionManager.cs C# Silverlight source code
As noted earlier each GameObject now have a collisionName property which defines what other game elements it will collide with. This collisionName may well change depending on what startup function is called – for example a weapon could either be a player weapon (through a call to startupPlayerBasicWeapon) or an enemy weapon (through a call to startupEnemyBasicWeapon). Even though it is the same class, by changing the collisionName we can define how it will collide in the game.
Weapon.cs C# Silverlight source code
And finally we define which GameObjects will collide in the ApplicationManager class during the startupApplicationManager function.
ApplicationManager.cs C# Silverlight source code
The end result is a simple collsion detection system, but one that is effective and easy to use. Check out the online demo, and download the source code from the Sourceforge SVN repository, or download an archive containing all the source code here.
Back to Silverlight Game Programming Tutorials