Upgrade Your Game: SpaceBlitz (Visual Basic)


  This article enhances Space Blitz sample application by adding new features.
The Z Buffer

Difficulty: Intermediate
Time Required: 1-3 hours
Cost: Free
Software: Visual Basic or Visual C# Express Editions


Video Demo


Download Video

Visual Basic Upgrade Your Game Series



Welcome to the Upgrade Your Game series of tutorials. There are four tutorials, each covering how to write a simple computer game using Visual Studio Express products. Though the games are simple, each one teaches some game development techniques and builds on the last to improve your skills. The skills can be applied to more complex games including 3D games using Microsoft DirectX.

You probably noticed that the animation in the previous game was not as smooth as you would have expected for such a simple game with so little going on. The main reason for this is because of my choice of picture boxes for the sprites. As I mentioned, this is not something that is recommended because there is a lot of overhead that comes with Windows controls. It really is overkill to use a Windows control just to draw a rectangle or any other graphic on the screen. However, it served its purpose for making a simple game with only a few lines of code.

For the third game you will take on another classic, a Space Invaders type game. Because this game has sprites that are very clearly not rectangles, and because there are a lot more of them to draw, this example will implement the sprites using bitmap graphics.

Since most developers are not graphically inclined, this is the time that your game development team needs to grow. Most games these days use graphics that are far more complex than the original Space Invaders or Pac-man and it's just not realistic to create them yourself. You may be lucky enough to find some royalty-free artwork on the Internet, but if you intend to sell your game, be sure to check the specific licensing for that artwork. The safest thing to do, if you are not rich enough to hire someone to produce your art, is to make friends with someone who can.

Note: This documentation assumes that you have a basic knowledge of programming concepts and the Visual Basic environment. You can learn more about these topics in the product documentation by clicking Help on the menu bar, and then clicking Contents, Index, or Search. You can also access Help by positioning the mouse cursor on language keywords or user interface elements such as windows or dialog boxes, and pressing F1.

Getting Started

Building and running SpaceBlitz

Once your project is loaded into the Visual Basic environment, you can compile and run the program in one step.

To build and run SpaceBlitz:

  • Press F5 to build and start the game under the debugger.

The game launches and you can control the base ship using the left and right arrows. Use the spacebar to fire.


  • Alien.vb
    Inherits from Sprite. Represents a single alien.
  • Aliens.vb
    Inherits from GameObject. Represents the group of aliens. Movement of aliens is done as a group. This file also has routines that work on the whole group such as random selection of an alien to drop a bomb.
  • Base.vb
    Inherits from Sprite. Represents the bases you can shelter behind. Contains routine for per pixel collision and erosion of the bases.
  • BaseShip.vb
    Inherits from Sprite. Represents the ship. Contains routines for movement controlled by the keyboard.
  • Bomb.vb
    Inherits from Sprite. Represents bombs. Contains code for collision detection.
  • GameObject.vb
    Abstract base class that represents an object that requires updating and drawing once per frame.
  • GameState.vb
    Stores the current state of the game and controls all gameplay.
  • Keyboard.vb
    Static class that stores the current up/down state of the control keys.
  • Missile.vb
    Inherits from Sprite. Represents missiles. Contains code for collision detection.
  • PointFMath.vb
    Helper routines for common PointF calculations not included in the PointF class.
  • Saucer.vb
    Inherits from Sprite. Represent the bonus flying saucer.
  • SpaceBlitz.vb
    The main display form. Other than UI initialization and keyboard events, little gameplay code is performed in here. Most code calls into GameState.
  • Sprite.vb
    Inherits from GameObject. Handles basic 2D sprite manipulation and loading.

Game Development Concepts

If you are new to 2D game development, check out the 2D Game Primer (Visual Basic).

Bitmap Sprites

Drawing a bitmap to the screen only requires a few lines of code. Using the code from the TinyTennis sample, you can add a new member variable to store the bitmap and a new constructor that takes the file name of the bitmap file. The bitmap constructor takes a file name, which means it's very easy to load and store.

Protected _frame As Bitmap
Public Sub New(ByVal gameState As GameState, ByVal x As Single, ByVal y As Single,
ByVal filename As String)
'Load the bitmap
_frame = New Bitmap(filename)
End Sub

Drawing the bitmap is almost as trivial. Drawing to a Windows Form is done using the GDI graphics API, which is contained in the System.Drawing namespace. All GDI drawing is done to a Graphics object. This means that you have to provide the graphics object to the Sprite.Draw call. Fortunately, the Paint event gets the Graphics object for the window as part of its EventArgs, so this turns out to be simple to get hold of. Drawing the bitmap to the graphics surface is also a single line of code using the DrawImage method.

Public Overrides Sub Draw(ByVal graphics As Graphics)
'Draw the correct frame at the current point
graphics.DrawImage(_frame, Location.X, Location.Y, Size.Width, Size.Height)
End Sub

All of the movement code comes right across from the TinyTennis sample. The aliens move based on a velocity assigned to them. The base ship moves based on a velocity set by the user pressing keys on the keyboard. Once a velocity is set, the Sprite base class will continue to animate as time goes by. In addition, the rectangle collision code can be used to check for collisions between missile, aliens, base ships, and saucers. Reuse is great!

Animating Sprites by Flipping the Image

Animation isn't just about moving things around the screen. Our aliens need to waggle their arms, legs, and antennae. If you look in the graphics folder, you will see that the artist provided two poses for each alien. To get the animation effect, you simply have to draw the images one after the other. Since this game only has two frames of animation, I have created a constructor that takes the two file names and stores them in a list of bitmaps. If you are new to .NET 2.0, generics may be new to you so you may want to go and read an introductory article. In the Draw call a decision has to be made which frame to draw and this is done by using the CurrentFrame member variable. CurrentFrame will be set in one of the Update() methods, usually in an inherited class, depending on how fast or slow the animation is to be. For this game, only the aliens need image flipping animation so the member is left at its default value of 0 for all of the other sprites.

Notice that just like the movement animation, the flipping speed is tied to the game time. Almost everything that happens in the Update() methods will be tied to the time, so that, no matter which machine you run on, the timing will stay exactly the same.

Protected _frames As List(Of Bitmap) = New List(Of Bitmap)()
Public Sub New(ByVal gameState As GameState, ByVal x As Single, ByVal y As Single,
ByVal filename1 As String, ByVal filename2 As String)
'Load the 2 animation frames
_frames.Add(New Bitmap(filename1))
_frames.Add(New Bitmap(filename2))
End Sub

Public Overrides Sub Draw(ByVal graphics As Graphics)
'Draw the correct frame at the current point
graphics.DrawImage(_frames(CurrentFrame), Location.X, Location.Y, Size.Width, Size.Height)
End Sub
Per Pixel Collisions

For the bases, checking the rectangle as you did in TinyTennis will not be sufficient because the shapes need to slowly get destroyed by the base ships' bullets and the aliens' missiles. This means that the shape to collide against becomes non-rectangular very quickly. In this case, it's necessary to check the bitmap itself to see if the bullet has hit a non-black pixel. For a perfect collision, you need to check every pixel of the first sprite against the second sprite which, as you can imagine, gets slow very quickly. So, just like the bounding shape checks were an approximation to the perfect check, you can look for other ways to approximate this kind of collision. Since you know that our bullets only move in the Y direction, there is no need to check for anything other than the leading edge of the bullet, which cuts the pixel checks down to 6 pixels. But what if you just check the 2 leading corner pixels? You would miss any collisions that happen between them, but that's just 4 pixels and, for this game, this is an acceptable performance/accuracy trade off.

Public Function CheckPixel(ByVal point As PointF) As Boolean
'Check this pixel and one 6 to its right (the size of missiles and bombs) to see if we have hit anything
Return (isPixelOpaque(CInt(point.X - Location.X), CInt(point.Y - Location.Y)) _
OrElse isPixelOpaque(CInt(point.X - Location.X + 6), CInt(point.Y - Location.Y)))
End Function

Private Function isPixelOpaque(ByVal x As Integer, ByVal y As Integer) As Boolean
'If the pixel is out of range that counts as black
If x < 0 OrElse x > _frames(0).Width - 1 OrElse y < 0 OrElse y > _frames(0).Height - 1 Then
Return False
End If
'Otherwise check for anything that is not black
Return (_frames(0).GetPixel(x, y) <> Color.FromArgb(0, 0, 0))
End Function

[from Aliens.Update()]
sprite.CurrentFrame = CInt(Int(((gameTime * _speed) / 50.0F) Mod 2.0F))
Destroying Bitmaps

Now that you can collide on a per pixel basis with the bases, the sprites need to be updated so that they appear to get damaged over time. It's important to do this not just because you draw the sprites in every frame, but because a user could switch applications or minimize the game. When the game is restored, you need to be able to redraw the whole screen.

Since each sprite stores its own copy of the bitmap, it's possible for the Base sprite to set certain pixels within itself to black so that they slowly get removed. Setting the pixels to black means that any future missile will not pass the per pixel test. For this game, I have chosen to draw a black circle of a random radius at the point of collision.

Public Sub Erode(ByVal point As PointF)
'Draw a black circle in the bitmap over the point of intersection
Using graphics As Graphics = Drawing.Graphics.FromImage(_frames(0))
graphics.FillEllipse(Brushes.Black, point.X - Location.X - _sizeX / 2 + 3,
point.Y - Location.Y - _sizeY / 2, _sizeX, _sizeY)
End Using
End Sub

The gameplay here, though not as advanced as in any modern game, is still something that needs to be managed properly. The game needs to be able to detect when all of the aliens are destroyed and recreate a new wave of aliens; it needs to randomly select an alien to drop a missile; and it needs to randomly add the bonus flying saucer to the screen.

If you are not careful with your code structure you will find that these sorts of tasks get randomly scattered around your code. For this game, I have chosen to encapsulate as much of this logic in one place: the GameState class. In the TinyTennis sample, this was used to store the scores, but in this game you will use it to store the scores, the level, whether you are currently dropping a missile, how many aliens are left, and several other things that pertain to the current state of the game.

You will also remember that for the collisions in TinyTennis you had to pass in references to the bats to the Ball object. Obviously this isn't something that is scalable beyond a handful of objects, so for this game the GameState class stores collections of all of the game objects and is passed into each object during creation. This means any object has access to any other object if it needs to query it for collisions or any other reason.

Take a look at the GameState object (there is too much code to post in the tutorial), and see how all the mechanics of the game play function.

Extending SpaceBlitz

  • Make some of the aliens detach themselves from the formation and fly down as in the arcade game Galaxian and others.
  • Add a second base ship controlled by a second player for a cooperative experience.
  • Go back to TinyTennis and change it to use bitmaps for the sprites rather than the Windows controls.
  • Add a high-score table and save the high scores so that they are remembered next time you play.

The Discussion

  • User profile image

    Hi I've installed vb.net express but when I try to install space.vsi I'm getting the following error:

    "Could not find any resources appropriate for the specified culture or the neutral culture......."

    Can you help with this?

  • User profile image

    can someone teach me to

    create a 2D and 3D game please teach me

    games like alien shooter or RPG games

    Using Visual Basic 2008, C# 2008 ,C++ 2008

    Im a beginner need help

    heres my   Email:  Dragonseed90@yahoo.com

    or teach me the basic

    like how to move the image and setting the control when you use it on


    jumping = space bar

    w = forward

    a = left

    s = backward

    d = right

    and when you press

    w and d  = goes up diagonal to the right

    also the mouse part the click = move

    can you teach me this things

    and how do you make the map or the world

    and walk through it and the navigation bar the small one that you see where your location is when playing like on the runescape or pokemon

    please help me send me a tutorial of it or sample    

    plus the source code and the working program

    thank a lot using Visual basic 2008 , C# 2008 ,

    C++ 2008.

    and teach me how to make it into an installer

    who helps me i give you my own original games for free when im done making

    of course i need to learn those first the one that i mentioned from the above

    hope you teach me those things and i will surely give you free copy of my work when im done


    hope you help me


  • User profile image

    @dragonseed90 looking at the classes quickly, you may want to look at Keyboard.vb.  Also check out http://creators.xna.com they have tons of gaming solutions.  We even have other XNA examples past just this.

  • User profile image
  • User profile image

    hey there

    can sum1 teach me how to make RPG game in VB which can save progress

    can you teach me how to move characters with keyboard keys like w for up

    and combination directions like wd for up-right

    how to make maps and etc

    and how to make the characters move..

    pls mail me.


    thanks alot

    hope to recieve emails.....

    "the sun follows the moon, the moon chases the sun"

Comments closed

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.