Asteroids in C#


Edited by C# Corner Editor

Summary

As my first experiment in a game design, rather than using a DirectX wrapper, I decided to explore the functionality of GDI+. GDI+ has lot of nice features to offer but performance wise it is slow. So GDI+ may not be a good idea to develop practical fast paced games. This game also includes sounds.

Overview

The attached project contains three classes, one class for each object - SpaceShip, Asteroid, and Bullet.

These classes do have many common methods and properties so they could be inherited from the same base class.

The windows form object pulls all these classes together into the same playing field, handles collision detection and player interaction. Everything is treated on a tick by tick basis via the use of a timer object.

Installation

All source/compiled files and resources should be in the same directory.

Collision Detection

Simple use of a rectangle object that represents the space occupied by the object on the screen, using the "IntersectsWith" Method we can find if other rectangles overlap.

The next step is to use the pixel map of the image contained within the rectangle for more precise collision detection, this has been implemented using some 'unsafe' C++ which gives us direct access to the memory space for the images, where we can rapidly test pixel/byte by pixel/byte.

Physics

The physics model is pretty simplistic using thrust and inertia we calculate where the ship will be.

Sound

winmm.dll is imported using InteropServices and its PlaySound Method is used for in game sound.

Performance

Performance wise, you may not be happy with the game specially when you run the game in full screen mode.

The killer lines are in the form constructor:

SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint,
true);
SetStyle(ControlStyles.DoubleBuffer,
true);

The above code provide double buffering process which enhances the speed of drawing. The performance is worse if you comment the double buffering code. The Timer interval is 50 so refresh is about 20 fps.. maybe this could be less.

Conclusion

I hope you find this program useful and fun. I am planning to implement more features in this game. I would be very interested in hearing any comments on performance and alternative ways to handle display with GDI+. Please visit the forums at www.aurora-soft.co.uk

Thanks to:

Mike Gold's article on space Invaders - for the sound implementation and some of the in game sounds :) http://www.c-sharpcorner.com/Graphics/SpaceInvadersMG.asp

Up Next
    Ebook Download
    View all
    Learn
    View all