C# Tutorial – Create a simple platform game in visual studio

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. There will be moving platforms that moves left to right and up and download in the game. We will get the player to travel with those platforms and make it into a nice and interactive little game using only windows forms and c# programming. Please note – this program was done as a prototype or proof of concept in windows form. This is why we didn’t use any pictures in it. All of the elements in the program are picture boxes so you can technically use your own images for the player, coins, door and platforms. So have fun with it and make it even better as your own game.

Lesson Objective –

  1. Create a platform game using picture boxes
  2. Allow the player to land on top of the picture boxes
  3. Run loops to search where the play has landed and take appropriate action
  4. Use foreach loop to search individual components in visual studio controls
  5. Assign TAG’s to platforms and interact with them
  6. Assign TAG’s to coins and interact with them
  7. 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

Full Source Code For this game –

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

// Created by MOOICT.COM
// For educational Purposes Only

namespace Platform_Game_Tutorial_MOO_ICT
{
    public partial class Form1 : Form
    {

        bool goLeft, goRight, jumping, isGameOver;

        int jumpSpeed;
        int force;
        int score = 0;
        int playerSpeed = 7;

        int horizontalSpeed = 5;
        int verticalSpeed = 3;

        int enemyOneSpeed = 5;
        int enemyTwoSpeed = 3;



        public Form1()
        {
            InitializeComponent();
        }

        private void MainGameTimerEvent(object sender, EventArgs e)
        {
            txtScore.Text = "Score: " + score;

            player.Top += jumpSpeed;

            if (goLeft == true)
            {
                player.Left -= playerSpeed;
            }
            if (goRight == true)
            {
                player.Left += playerSpeed;
            }

            if (jumping == true && force < 0)
            {
                jumping = false;
            }

            if (jumping == true)
            {
                jumpSpeed = -8;
                force -= 1;
            }
            else
            {
                jumpSpeed = 10;
            }

            foreach(Control x in this.Controls)
            {
                if (x is PictureBox)
                {


                    if ((string)x.Tag == "platform")
                    {
                        if (player.Bounds.IntersectsWith(x.Bounds))
                        {
                            force = 8;
                            player.Top = x.Top - player.Height;


                            if ((string)x.Name == "horizontalPlatform" && goLeft == false || (string)x.Name == "horizontalPlatform" && goRight == false)
                            {
                                player.Left -= horizontalSpeed;
                            }


                        }

                        x.BringToFront();

                    }

                    if ((string)x.Tag == "coin")
                    {
                        if (player.Bounds.IntersectsWith(x.Bounds) && x.Visible == true)
                        {
                            x.Visible = false;
                            score++;
                        }
                    }


                    if ((string)x.Tag == "enemy")
                    {
                        if (player.Bounds.IntersectsWith(x.Bounds))
                        {
                            gameTimer.Stop();
                            isGameOver = true;
                            txtScore.Text = "Score: " + score + Environment.NewLine + "You were killed in your journey!!";
                        }
                    }

                }
            }


            horizontalPlatform.Left -= horizontalSpeed;

            if (horizontalPlatform.Left < 0 || horizontalPlatform.Left + horizontalPlatform.Width > this.ClientSize.Width)
            {
                horizontalSpeed = -horizontalSpeed;
            }

            verticalPlatform.Top += verticalSpeed;

            if (verticalPlatform.Top < 195 || verticalPlatform.Top > 581)
            {
                verticalSpeed = -verticalSpeed;
            }


            enemyOne.Left -= enemyOneSpeed;

            if (enemyOne.Left < pictureBox5.Left || enemyOne.Left + enemyOne.Width > pictureBox5.Left + pictureBox5.Width)
            {
                enemyOneSpeed = -enemyOneSpeed;
            }

            enemyTwo.Left += enemyTwoSpeed;

            if (enemyTwo.Left < pictureBox2.Left || enemyTwo.Left + enemyTwo.Width > pictureBox2.Left + pictureBox2.Width)
            {
                enemyTwoSpeed = -enemyTwoSpeed;
            }


            if (player.Top + player.Height > this.ClientSize.Height + 50)
            {
                gameTimer.Stop();
                isGameOver = true;
                txtScore.Text = "Score: " + score + Environment.NewLine + "You fell to your death!";
            }

            if (player.Bounds.IntersectsWith(door.Bounds) && score == 26)
            {
                gameTimer.Stop();
                isGameOver = true;
                txtScore.Text = "Score: " + score + Environment.NewLine + "Your quest is complete!";
            }
            else
            {
                txtScore.Text = "Score: " + score + Environment.NewLine + "Collect all the coins";
            }


        }

        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 == false)
            {
                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 == true)
            {
                jumping = false;
            }

            if (e.KeyCode == Keys.Enter && isGameOver == true)
            {
                RestartGame();
            }


        }

        private void RestartGame()
        {

            jumping = false;
            goLeft = false;
            goRight = false;
            isGameOver = false;
            score = 0;

            txtScore.Text = "Score: " + score;

            foreach (Control x in this.Controls)
            {
                if (x is PictureBox && x.Visible == false)
                {
                    x.Visible = true;
                }
            }


            // reset the position of player, platform and enemies

            player.Left = 72;
            player.Top = 656;

            enemyOne.Left = 471;
            enemyTwo.Left = 360;

            horizontalPlatform.Left = 275;
            verticalPlatform.Top = 581;

            gameTimer.Start();


        }
    }
}

 




31 responses to “C# Tutorial – Create a simple platform game in visual studio”

  1. maas says:

    it is not simple!!!!!!!!!!

  2. Anhar Ali says:

    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

  3. Solihull student says:

    Could’ve elaborated more on where the coding goes, but thanks for the help anyway.

  4. Neil says:

    Trying to learn, but one thing is annoying me. When you jump the “player” goes into to the platform. How do you stop that?

  5. Ann says:

    How can I do it in WPF?

  6. Anhar Ali says:

    WPF tutorial on platform game will be on here soon.

  7. Ann says:

    I’m making it but I’m stucking at key move of Player

  8. Pete_r61 says:

    Could you post the code somehow. Because a copy of the current code does not jump.

  9. Anhar Ali says:

    Are you sure where are you stuck on the code?

  10. Motasem says:

    Very helpful really…Thank you very much

  11. Vance says:

    i have visual studio for mac 🙁

  12. Able says:

    Thanks, that was really nice and easy tutorial to get back on the basics of C# and platform games

  13. KW says:

    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!

  14. Dilan says:

    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.

  15. karim Taibi says:

    A real treasure. Thanks for sharing this and spreading Knowledge.

  16. layson says:

    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

  17. Anhar Ali says:

    Looks like simple syntax error. I think it should be player.bounds instead of player.Height double check the code with the tutorial.

  18. Tomas G says:

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

  19. Anhar Ali says:

    Amazing thank you

  20. skia says:

    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?

  21. Ryad says:

    Hi this is very nice and cool but flickering is a big problem thanks for the people who found and shared a solution!

  22. Rados Mirkovic says:

    I get error ‘name player undefined’

  23. Anhar Ali says:

    In the properties window name the player picture box “player” all lower case.

  24. Christophe Kowarski says:

    Excellent tutorial! Clear and concise (for a change 😀 ). Now I’ll just work on changing those squares for pics, background, etc, add sound and voilà! Thanks for that 🙂

  25. Paul says:

    Hi, Thanks for the tutorial it has given me the information I need to migrate my game from python.
    I do not think you are correct re their being a bug C#, the reason for the flicker is that you are constantly moving the player down 10 and then up when they are on the platform. I solved this my introducing an onPlatform bool. Code as follows in the MaoinGameTimerEvent

    Put a test around changing the player top:
    if ((onPlatform == false) || jumping) {
    player.Top += jumpSpeed;
    }

    before the loop add:

    onPlatform = false;

    in the player.Bounds test in the loop:

    if (player.Bounds.IntersectsWith(x.Bounds))
    {

    onPlatform = true;
    force = 8;
    player.Top = x.Top - player.Height + 1;
    if ((string)x.Name == "horizontalPlatform" && goLeft == false || (string)x.Name == "horizontalPlatform" && goRight == false)
    {
    player.Left -= horizontalSpeed;
    }
    }

    No more flashing.
    Paul

  26. Paul says:

    Oh sorry should have said – and remove x.BringToFront()

  27. Anhar Ali says:

    Thanks Paul, this is a clever solution to the glitches.

  28. SirGouki says:

    Regarding flickering. In the form designer, click on the Form itself, open up the properties sheet and find double buffering and set that to Enabled or True. Should be the first step you do before adding anything else. No need for unsafe DLL imports here (or generally anywhere in C# really), that’s definitely beyond the level of who this tutorial seems to be intended for. Also, there should be a check that once the player collides with an object (such as a platform), it 0s out the speed in that direction. For instance, gravity should be handled similarly to:
    if(!grounded)
    {
    player.y += gravity * delta; //Where grounded is a boolean that gets set if the player collides with a platform from above it (and cleared if the player is not colliding with a walkable platform), player.y is the vertical position of the player as a float, gravity is a float for falling speed acceleration, and delta is the time since the last update. Using delta will prevent things from being locked to a specific framerate, and will also make it so that movement is the same if you’re running at 60fps vs 10fps for example. Since .NET by itself is not intended for direct game development, you’ll have to calculate delta but its relatively easy.
    }

  29. Koncz Akos says:

    hello, when i start this my player is starts to fly upwards like a rocket and I don’t know why..

  30. Keertan Natakala says:

    Hi, what happened to the written tutorial?

  31. Emmy says:

    What is Bounds is it a bool, string or what