C# Tutorial – Create a simple platform game in visual studio
- Subject: C# Tutorials
- Learning Time: 3 hours
In this tutorial we will create a simple platform game in visual studio using C# (sharp) programming language. This game will have points to collect, blocks to jump on to and a door to end the level. This is a basic level programming for a platform game and you should be trying to create another level once this is completed.
Lesson Objective –
- Create a platform game using picture boxes
- Allow the player to land on top of the picture boxes
- Run loops to search where the play has landed and take appropriate action
- Use foreach loop to search individual components in visual studio controls
- Assign TAG’s to platforms and interact with them
- Assign TAG’s to coins and interact with them
- Include a game completion format
Full Video Tutorial –
note- There will be some flickering when the character moves and jumps onto the platform, this is caused because of Visual Studio debugging not because of the code, the game will still be working as usual.
Download Platform Game Project on GitHub
Download written tutorial platform game images for this project.
Note – Written tutorial is slightly different than the video tutorial. In the written tutorial we don’t have the moving platforms you see on the video tutorial, but they are easy to implement.
C# Tutorial – Create a simple Platform game in visual studio
start a new project, Choose windows form application in C# and name it platformgame
In the properties window change the setting to Size – 500, 650 and Text to Platform Game
Add your first picture box to the form.
Change the back colour to Brown
Change TAG to platform
Now you can scale the picture to go across the floor
Lets add the second picture box to form this time we are going to add the player.
Change the name property to player and back colour to blue.
Change the size to 30, 50
This is the player, its full of personality dont you think. Yep lets move on.
Now add a timer to the form
Change enabled = TRUE and Interval to 20.
Adding Events to the form
Click on the from and go to the events panel in the properties window
Find the key down – Type keyisdown and press enter
Find the key up – Type keyisup and press enter
Both of these actions will take you to the code view. We need to do one more thing before we can start coding for this game.
Double click on the timer
<– double click this
Now this what the code view looks like
We have all 3 events done. Let’s get coding
1 2 3 4 5 6 7 |
bool goleft = false; bool goright = false; bool jumping = false; int jumpSpeed = 10; int force = 8; int score = 0; |
These are variables we need for this game.
Go left and go right and jumping are Booleans which will determine the direction of the player.
Integer jumpSpeed is holding the value 10.
Integer force is holding the value 8.
Integer score is zero.
Key down function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
private void keyisdown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Left) { goleft = true; } if (e.KeyCode == Keys.Right) { goright = true; } if (e.KeyCode == Keys.Space && !jumping) { jumping = true; } } |
This is the key is down function. This will trigger each time the buttons are pressed.
When the left button is pressed we can go left to true.
When the right button is pressed we can change the go right to true.
When the space bar is pressed AND the character is not jumping we change the jumping to true.
key is up function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
private void keyisup(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Left) { goleft = false; } if (e.KeyCode == Keys.Right) { goright = false; } if (jumping) { jumping = false; } } |
This function will turn all of Booleans back to false when the users releases each key for example when the LEFT is up we change go left back to false. Same for right and SPACE bar.
Timer event (player movement)
Below are the first part of the timer event codes, enter them inside the function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
player.Top += jumpSpeed; if (jumping && force < 0) { jumping = false; } if(goleft) { player.Left -= 5; } if(goright) { player.Left += 5; } if (jumping) { jumpSpeed = -12; force -= 1; } else { jumpSpeed = 12; } |
First we are starting up with play.Top += jumpSpeed; This line we continuosly drop the player towards the floor. We want it because we want the game to have a gravity effect.
if (jumping && force < 0)
{
jumping = false;
}
This line above is checking if the player is jumping and force of the jump is less than 0 if so then we can change jump back to false.
if(goleft)
{
player.Left -= 5;
}
If go left is true then we can push the character towards left of the screen.
if(goright)
{
player.Left += 5;
}
If go right variable is true then we are going to move the player left towards the right.
if (jumping)
{
jumpSpeed = -12;
force -= 1;
}
If jumping is true then we change the jump speed integer to minus 12 which means it will thrust the player towards the top and we decrease the force by 1. If we don’t do this then character can fly over everything we need to give the jump a limit.
else
{
jumpSpeed = 12;
}
ELSE the character is not jumping then we can keep the jump speed on 12.
Timer event code continued
1 2 3 4 5 6 7 8 9 10 11 |
foreach (Control x in this.Controls) { if (x is PictureBox && x.Tag == "platform") { if (player.Bounds.IntersectsWith(x.Bounds) && !jumping) { force = 8; player.Top = x.Top - player.Height; } } } |
In this piece of code we will scan the whole form to find the picture boxes with this once our player interacts it will have to land on top of it.
For each control x in this.Controls means for each of the windows component we create a variable called X and give it a type of controls.
IF X is a type of picturebox AND tag is equals to “platform”
IF play bounds intersect with the bounds of the platform and out character is not jumping then we change the force integer back to 8 and player will be above the platform.
Try the game out now. You can do this by pressing little green play button on the tool bar or by presing F5 on the keyboard. This will start to debug or build the program into an exectable file and then it will run the program as we want it to.
It stopped when it dropped to the platform
Move left
Move right
Press SPACE to JUMP
Now off course we can’t just have a single platform on a platform game.
Now time to add some more picture boxes to form.
You can choose any back colour you want. For this example we will use the BROWN one.
Note make sure you change the TAG for each of the picture boxes to platform.
Run the game and check.
It worked.
Now you can get creative with the whole thing.
We need to have a way for the player to win or lose the game in case you want to go further with this.
WIN the game
This is the new picture box I’ve added to the screen.
name it door.
Lets add a small code so when we reach the door we can end the game
1 2 3 4 5 |
if (player.Bounds.IntersectsWith(door.Bounds)) { timer1.Stop(); MessageBox.Show("You WIN"); } |
There you go Job done.
It’s a simple
You can also do another picture box which will end the game.
Since all of them are picture boxes we can design the level to make it look more game such see the example below.
You make your own or use some images from the internet and experiment with making your own platform game.
Lets Add some points to the game
Lets add another picture box to form. Give this one a size of 20, 20 and back colour of yellow. Make sure it has TAG of coin.
Now lets add the following code inside the for loop where we have written about the player and platform collision before.
1 2 3 4 5 6 7 8 9 10 11 |
foreach (Control x in this.Controls) { if (x is PictureBox && x.Tag == "platform") { if (player.Bounds.IntersectsWith(x.Bounds) && !jumping) { force = 8; player.Top = x.Top - player.Height; } } } |
This is current for loop we will add the instructions for the coin here now.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
foreach (Control x in this.Controls) { if (x is PictureBox && x.Tag == "platform") { if (player.Bounds.IntersectsWith(x.Bounds) && !jumping) { force = 8; player.Top = x.Top - player.Height; } } if (x is PictureBox && x.Tag == "coin") { if (player.Bounds.IntersectsWith(x.Bounds) && !jumping) { this.Controls.Remove(x); score++; } } } |
We are using the same principle as before except this time we are checking if the picture box has a TAG of coin. If so and it’s in the bounds of the player then we can remove it from the form and add 1 to the score variable.
Clever right. ☺
Test Run
It works. Lets copy and paste the coin all over the level now.
We collected all of the points and completed the level.
Happy learning. Now you can try to build on this yourself and see if you add more points or enemies on the screen and interact with the player. Make sure to add label to screen which can used to show the score. We can do everything for YOU.
Below are the full code for this game.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace platformGame { public partial class Form1 : Form { bool goleft = false; bool goright = false; bool jumping = false; int jumpSpeed = 10; int force = 8; int score = 0; public Form1() { InitializeComponent(); } private void keyisdown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Left) { goleft = true; } if (e.KeyCode == Keys.Right) { goright = true; } if (e.KeyCode == Keys.Space && !jumping) { jumping = true; } } private void keyisup(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Left) { goleft = false; } if (e.KeyCode == Keys.Right) { goright = false; } if (jumping) { jumping = false; } } private void timer1_Tick(object sender, EventArgs e) { player.Top += jumpSpeed; if (jumping && force < 0) { jumping = false; } if (goleft) { player.Left -= 5; } if (goright) { player.Left += 5; } if (jumping) { jumpSpeed = -12; force -= 1; } else { jumpSpeed = 12; } foreach (Control x in this.Controls) { if (x is PictureBox && x.Tag == "platform") { if (player.Bounds.IntersectsWith(x.Bounds) && !jumping) { force = 8; player.Top = x.Top - player.Height; } } if (x is PictureBox && x.Tag == "coin") { if (player.Bounds.IntersectsWith(x.Bounds) && !jumping) { this.Controls.Remove(x); score++; } } } if (player.Bounds.IntersectsWith(door.Bounds)) { timer1.Stop(); MessageBox.Show("You WIN"); } } } } |
it is not simple!!!!!!!!!!
It’s a simple game tutorial, all it takes it is patience and practice. I’ve failed making this lots of times and it only had to work once for me to start understanding what made it work. Don’t give up
Could’ve elaborated more on where the coding goes, but thanks for the help anyway.
Trying to learn, but one thing is annoying me. When you jump the “player” goes into to the platform. How do you stop that?
How can I do it in WPF?
WPF tutorial on platform game will be on here soon.
I’m making it but I’m stucking at key move of Player
Could you post the code somehow. Because a copy of the current code does not jump.
Are you sure where are you stuck on the code?
Very helpful really…Thank you very much
i have visual studio for mac 🙁
Thanks, that was really nice and easy tutorial to get back on the basics of C# and platform games
I was having trouble jumping and thought I’d typed everything perfectly till I realized:
I had written force = -1
instead of
force -= 1
Moral of the story: it might seem tedious, but checking over all your work is the best debug process lol.
Also, retyping the project from scratch taught me a lot more the second go-around. I think I’ll start doing this from now on so I can feel more familiar with methods like these.
Thanks for the tut!
Bro, great code you got there. I just started using c# winforms and this is just great, I got to understand many properties, and for the “lag” in the character I could not find any solution but I can suggest that you can modify the code for the collision in each platform so instead of using the bounds property you should literally find the exact position of your character using .left and .right properties I just finished doing that and now my character will not be able to teleport to the upper part of any platform when touching the platform boundaries and instead it will just fall. Anyways, thanks Moo ICT.
A real treasure. Thanks for sharing this and spreading Knowledge.
I’m getting a CS1001 code with the IntersectsWith and the player.==Height… I am very new to this and would like to know if there is somewhere common I could have messed up
Looks like simple syntax error. I think it should be player.bounds instead of player.Height double check the code with the tutorial.
Hi, first thank you very much for perfect example. How to avoid flickering. Add this class:
class DrawingControl
{
[DllImport(“user32.dll”)]
public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
private const int WM_SETREDRAW = 11;
public static void SuspendDrawing(Control parent)
{
SendMessage(parent.Handle, WM_SETREDRAW, false, 0);
}
public static void ResumeDrawing(Control parent)
{
SendMessage(parent.Handle, WM_SETREDRAW, true, 0);
parent.Refresh();
}
}
then in MainGameTimeEvent:
at begin:
DrawingControl.SuspendDrawing(this);
at end:
DrawingControl.ResumeDrawing(this);
Amazing thank you
why aren’t you using player.bottom = x.top? also what if you where to make a top down Zelda style game? you would just need to reorganize the picture boxes and then put both a x.bounds and y.bounds on each of the forms controls?
Hi this is very nice and cool but flickering is a big problem thanks for the people who found and shared a solution!