In most 2D games (except for maybe some puzzle games), you have one or more characters moving around the screen that interact with each other, called Sprites. Each sprite has a position (x,y coordinate) and occupies a region on the screen. You need move these sprites and check them for collisions with other sprites, for example to see if the player will collide with an enemy.
One easy way to implement Sprites in Silverlight is to simply create a User Control. You can even create and design the User Control in an Expression Blend project and then use it inside your Visual Studio solution.
However, if we start creating oodles of User Controls within Blend and use them as Sprites, we will quickly find that we are adding repetitive code to each user control to manage the sprite. So why not create a base class that defines the basics of what we need from a sprite, and then have the user control inherit from that base class?
This is the approach I took for Destroy All Invaders (you can grab the source code for this game here). If we look at the source code, you will see a SpriteBase.cs class:
Notice that SpriteBase defines the position, bounds, current direction (angle of movement), speed, and whether or not the sprite is active. Another very important note is that SpriteBase inherits from Control:
public class SpriteBase: Control
... this inheritance is very important because it allows us to extend our "User Control Sprites" by inheriting from SpriteBase instead of Control.
So to use this base class, we simply need to change what our User Controls inherit from. So instead of using the default code generated by the user control designer...
public class MyUserControl : Control
... we can instead inherit from SpriteBase:
public class MyUserControl : SpriteBase
Another advantage to this OOP approach is that we can deal with Sprites at the generic SpriteBase level for any collision detection routines, etc. So to create a method to see if a sprite is off screen, we can pass in a generic SpriteBase to the following code:
public bool IsSpriteOffScreen(SpriteBase sprite)
/// Determines if a sprite is off the viewable screen
if ((sprite.x + sprite.Width < -_scrollOffsetX) ||
(sprite.x > -_scrollOffsetX + this.Width) ||
(sprite.y + sprite.Height < -_scrollOffsetY) ||
(sprite.y > -_scrollOffsetY + this.Height))
That's it! Just a simple touch of OOP to increase code reuse. Happy coding!