Asteroids, C#, 3D and OpenGL
- Posted: Feb 22, 2012 at 6:00 AM
- 38,019 Views
- 18 Comments
Loading User Information from Channel 9
Something went wrong getting user information from Channel 9
Loading User Information from MSDN
Something went wrong getting user information from MSDN
Loading Visual Studio Achievements
Something went wrong getting the Visual Studio Achievements
Today's project is a simple example of using OpenGL, C#/WinForm to build a introductory game. What I liked about it is that it really is pretty simple, simple to follow the code, simple to understand and simply easy to get started with...
This article is intended for beginners who want to start with 3D game programming and don’t know where to start. It is programmed in Opengl using VS 2008 and a small graphic engine I made myself called Shadowengine. It has the basics of what a game should have: a Score, levels of difficulty and a life counter. All this is written in a small number of code lines, with the objective of being simple and understandable.
The first problem I had to achieve is the scene to look like outer space. For that issue, I set the background color to black. In opengl, it is set this way:
...
The score is a number which increases over time and it grows faster everytime I pass a level. The level increases every 450 frames.
The last issue I had to address is the problem of asteroid collision. I make for the ship three positions (one for the ship and two for the wings) and every once in a while, I check the distance between all the asteroids and those three positions. If it is under a predefined value, I execute the collision event.
The project has 6 classes:
- AsteroidGenerator.cs - It handles the creation of asteroids in random places and with random sizes and speeds. It also has the method to query whether or not there has been a collision between the spaceship and an asteroid.
- Asteroid.cs - It handles all concerning an asteroid such as the movement, texture selection, drawing, among others.
- Star.cs - It has a method to create random white points and to draw them.
- Camera.cs - It handles the selection of the user camera and to set the right perspective view of the scene.
- SpaceShip.cs - This class contains all methods and attributes regarding the spaceship, such as movement, drawing, etc.
- Controller.cs - This class manages the game creation, game logic and contains all the classes needed to run the game. Here is a portion of code:
- ...
Main.cs - This is the form which contains this visual components of the game. It contains the controller class and gives the player information through proper windows controls. It has a timer to periodically draw the scene and has the code for texture and object loading.
...
While written for VS2008, for me it loaded in VS2010 just fine (once it converted). Once loaded it compiled and ran the first time...
The game is very simple. Using WASD you move your ship to avoid the oncoming asteroids.
And while the comments/strings are not in English the code is easy enough to understand;
public Main()
{
InitializeComponent();
hdc = (uint)pnlViewPort.Handle;
string error = "";
//Comando de inicializacion de la ventana grafica
OpenGLControl.OpenGLInit(ref hdc, pnlViewPort.Width, pnlViewPort.Height, ref error);
//inicia la posicion de la camara asi como define en angulo de perspectiva,etc etc
controladora.Camara.SetPerspective();
if (error != "")
{
MessageBox.Show("Something happened");
}
#region lights
//Configuracion de las luces
float[] materialAmbient = { 0.5F, 0.5F, 0.5F, 1.0F };
float[] materialDiffuse = { 1f, 1f, 1f, 1.0f };
float[] materialSpecular = { 1.0F, 1.0F, 1.0F, 1.0F };
//brillo del material
float[] materialShininess = { 1.0F };
//posicion de la luz
float[] ambientLightPosition = { 10F, -10F, 10F, 1.0F };
// intensidad de la luz en RGB
float[] lightAmbient = { 0.85F, 0.85F, 0.85F, 1.0F };
Lighting.MaterialAmbient = materialAmbient;
Lighting.MaterialDiffuse = materialDiffuse;
Lighting.MaterialSpecular = materialSpecular;
Lighting.MaterialShininess = materialShininess;
Lighting.AmbientLightPosition = ambientLightPosition;
Lighting.LightAmbient = lightAmbient;
#endregion
//Habilita las luces
Lighting.SetupLighting();
//cargar texturas
ContentManager.SetModelList("modelos\\");
ContentManager.LoadModels();
ContentManager.SetTextureList("texturas\\");
ContentManager.LoadTextures();
//AudioPlayback.SoundDir = "sonidos\\";
//AudioPlayback.LoadSounds();
controladora.CreateObjects();
//Color de fondo
Gl.glClearColor(0, 0, 0, 1);//red green blue alpha
Gl.glShadeModel(Gl.GL_SMOOTH);
}
private void tmrPaint_Tick(object sender, EventArgs e)
{
// limpia opengl
Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT);
//dibuja la escena
controladora.DrawScene();
//cambia los buffer
Winapi.SwapBuffers(hdc);
//termina de pintar
Gl.glFlush();
if (started)
{
score += 1;
count1++;
count2++;
levelCount++;
if (levelCount == 450)
{
level++;
AsteroidGenerator.GenerateAsteroid(35, false);
lblLevel.Text = level.ToString();
levelCount = 0;
}
if (count1 == 4)
{
lblScore.Text = score.ToString();
count1 = 0;
lives = controladora.Nave.Vidas;
}
if (count2 == 20)
{
ShowLife(lives);
count2 = 0;
if (lives == 0)
{
started = false;
MessageBox.Show("Game Over");
controladora.ResetGame();
score = 0;
level = 1;
lives = 3;
started = true;
count1 = 0;
count2 = 0;
lblLevel.Text = level.ToString();
}
}
}
}
If you've thought about writing a 3D game, be it space or not, this project might be a good starting place for you...
Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation,
please create a new thread in our Forums,
or
Contact Us and let us know.
Follow the Discussion
Oops, something didn't work.
What does this mean?
Following an item on Channel 9 allows you to watch for new content and comments that you are interested in. You need to be signed in to Channel 9 to use this feature.What does this mean?
Following an item on Channel 9 allows you to watch for new content and comments that you are interested in and view them all on your notifications page.sign up for email notifications?
since this is in C# could this be converted to a Windows Phone game?
Windows Phone doesn't support OpenGL, does it? If not, then the game would have to be converted to Directx in order to be ported to WP7.
Yup, "OpenGL ES"
But on Windows Phone? ermm... don't think so, no.
Does anyone else find it poignant that this sample is using OpenGL rather than DirectX?
Microsoft should actively support and promote a world class .NET API for DirectX running on desktop PCs.
Does anyone else find it poignant that this project uses OpenGL rather than DirectX?
Microsoft should actively support and promote a world class .NET API for DirectX.
Does anyone else realize the lives are the original starcraft icon?
@geoMcC: I think it's good that you can have your pick of 3D platforms when working with C# and I welcome OpenGL to the pool. Besides, I though Microsoft were in fact actively supporting and promoting XNA Game Studio - the official DirectX API for managed code. Whether XNA is "world class", I honestly wouldn't know...
I made that sample game it was for a 3d project in school if you liked visit my dev blog www.vasilydev.blogspot.com
呵呵呵
大家好呀!
Is there any possibility to get sources of this game?
@WhiteAngel:If you click through to the article, you can download it there...
.
Thanks, I learn C# and I need this code to research.
I can't use "quote" function. why ?
This is the best example Program I have seen on this website
i made another game demo its about a car race
http://www.codeproject.com/Tips/357063/A-very-simple-car-race-game-in-Csharp-and-OpenGL
This really is a very good demonstration of C# programming and OpenGL.
Hello! Where I can download OpenGL libs?
Remove this comment
Remove this thread
close