WPF C# Tutorial – Create a simple racing game in visual studio

In this tutorial we will be making top down racing game in visual studio with WPF and C# programming.  You will control the player yellow car in the game and avoid other cars in the road by going left or right. You can also collect a star in the game to get invincibility for short amount of time. When you collect the star, you won’t be affected by any other traffic while you are in the power mode. This game will be made from WPF components and C# scripts.

Lesson Objectives –

  • Create a simple racing game in visual studio with WPF and C#
  • Move player left and right using the key down and key up events
  • Import images for the player car, player power mode animation and traffic cars
  • Switch traffic car images real time as the game is running
  • Animate the road markings in the WPF Canvas
  • Move traffic cars towards the player and collide with the player
  • Collide with star objects and activate the power mode
  • Speed up the game as you score higher in the game

Video Tutorial –


Download the game images here


Xaml Code –

Inside the XAML code here we are setting up the height and width of the game screen. The we add a Canvas and inside the canvas we are defining the background of the canvas, name of the canvas, key down event and key up event. Its important to set up the Focusable option here because when the game loads we will need to verify which element inside of this game will be the main focus also without the focusable option the key down and key up events won’t register.

After that we have 4 different rectangles defined, these rectangles are the road markings. they will be placed middle of the scene and when the game runs it will move down and give the illusion of a moving straight road.

3 more rectangles are added to the game, 2 of them are the other cars in the road that the player will be interacting with the last rectangle is the player. Inside of the other cars we are defining the Tag, height, width and positions. inside the player car we are doing the same except we don’t need the Tag we will add a name for the player instead.

Lastly we are adding the label to the canvas where we will show how long the player survived in the game.

C# Code for the Racing game

All of the code for the C# programming in this game has been commented, so its all explained in the comments.





Comment on this tutorial and let us know how you got on -