Asteroids, C#, 3D and OpenGL


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...

A Basic 3D Asteroid Game in openGL with C#

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()
      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
      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;


      //Habilita las luces
      //cargar texturas
      //AudioPlayback.SoundDir = "sonidos\\";
      //Color de fondo
      Gl.glClearColor(0, 0, 0, 1);//red green blue alpha 

  private void tmrPaint_Tick(object sender, EventArgs e)
      // limpia opengl
      //dibuja la escena
      //cambia los buffer
      //termina de pintar

      if (started)
          score += 1;
          if (levelCount == 450)
              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)
              count2 = 0;
              if (lives == 0)
                  started = false; 
                  MessageBox.Show("Game Over");
                  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...


C#, Coding4Fun

The Discussion

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.