WPF C# Tutorial – Create Parallax Scrolling Endless Runner Game in Visual Studio

Main Window Function

This is the default function that’s added to the code when a new project is create. This function runs before any other because it has that intializeComponent() function to run which will load up the necessary components to add all of the design view items to the screen. We can add our own instructions to this function too. The main window function C# code is shown below.

        public MainWindow()
        {
            InitializeComponent();

            //set the focus on my canvas from the WPF
            myCanvas.Focus();

            // assign the game engine event to the game timer tick
            gameTimer.Tick += gameEngine;
            // set the game timer interval to 20 milliseconds
            gameTimer.Interval = TimeSpan.FromMilliseconds(20);

            // first set the background sprite image
            backgroundSprite.ImageSource = new BitmapImage(new Uri("pack://application:,,,/images/background.gif"));
            // add the background sprite to both rectangles
            background.Fill = backgroundSprite;
            background2.Fill = backgroundSprite;
            // run the start game function
            StartGame();

        }

Under the initializeComponent(); line we start adding our own instructions.

myCanvas.Focus(); this line telling this app that we want to mainly focus on the myCanvas element from the XAML code. Since we have the key down and up events linked to this element, we need it to be in focus for those to register.

gameTimer.Tick += gameEngine; this line is linking the gameEngine event we created earlier to the game timer. So each time it ticks it will trigger this gameEngine event.

gameTimer.Interval = TimeSpan.FromLilliseconds(20); this line is stating how often we want the timer to tick, in this case we want the timer to tick every 20 milliseconds. To create seamless animation and smooth movement we need to have the timer ticking faster so it looks like one continuously motion in the game. You can also set the timer interval to seconds but the animation will be really slow and it won’t feel right for this type of game.

backgroundSprite.ImageSource = new BitmapImage(new Uri(“pack://application:,,,/images/background.gif”)); this line of code is loading the background GIF file we imported earlier and loading it inside of the background sprite image brush we made earlier in the code. Inside the image brush class there is a image source function that takes in location of a BITMAP or a image file. Once it linked it will then save that file in the RAM as a texture to be used later on. In this case we are directing this image source function a new image. Inside the quotation It starts with “pack://” which means this current app package so we are looking inside this package and then going inside the application location semi colon: 3 commas,,, and then we have the images folder and finally the file name and extension.

Background.Fill = backgroundSprite and background2.Fill = backgroundSprite line is simply adding the background image we loaded earlier to both of the background rectangles on the screen.

Lastly we run the start game function by stating startGame();

Key down and Key up event

These are the two events we added earlier from the XAML code. Lets see what they do.

        private void Canvas_KeyDown(object sender, KeyEventArgs e)
        {
            // if the game over boolean is true and the enter key is pressed
            if (e.Key == Key.Enter && gameover)
            {
                // run the start game function
                StartGame();
            }
        }

Key down event has a single selection inside which is a IF statement. Inside of the if statement we are checking IF (Key pressed is equals to ENTER AND game over Boolean is true) then we can run the start game function. This event will be triggered when the game is over and the player presses the enter key. While the game running pressing the enter key will not work because in this if statement both of these statement needs to be true in order for the selection to do anything.

Below is the key up event

        private void Canvas_KeyUp(object sender, KeyEventArgs e)
        {
            // if the space key is pressed AND jumping boolean is true AND player y location is above 260 pixels
            if (e.Key == Key.Space && !jumping && Canvas.GetTop(player) > 260)
            {
                // set jumping to true
                jumping = true;
                // set force integer to 15
                force = 15;
                // set speed integer to -12
                speed = -12;
                // change the player sprite so it looks like he's jumping
                playerSprite.ImageSource = new BitmapImage(new Uri("pack://application:,,,/images/newRunner_02.gif"));
                
            }
           
        }

We are programming the jump function of the player inside of the key up event because we don’t want the player to simply hold down the space bar and the player character will be jumping continuously we want them to release the key to jump and press release again to jump this way we can add restrictions to the game play.

Similar to the key down function in this key up function we have one IF statement, but inside of this if statement it takes in 3 different conditions all of those conditions must be met before any action is taken.

IF(SPACE key is pressed AND jumping is false AND player top position is greater than 260 pixels)

THEN

Set jumping to true

Force set to 15

Speed set to -12

Player sprite image brush is loading the newrunner_02.gif file inside of it so we can change the characters image when they successfully jump on the screen.

Go to page 5 for start game function source code




7 responses to “WPF C# Tutorial – Create Parallax Scrolling Endless Runner Game in Visual Studio”

  1. Pascal F says:

    Very nice tutorial, I really appreciate it.

    But i got one question:

    How do i get a moving ground into the game? when i put an image with the same length as the background and also the nearly same code i fall through the ground.

    Pascal

  2. Anhar Ali says:

    Hi Pascal, glad you liked the tutorial, worked really hard on this one. For your question about moving the ground, you can use similar techniques as being used with the background scrolling animation , have two separate ground rectangles and move them the same way as the backgrounds are. Within the rectangles you can images as it’s texture so it looks like the ground is scrolling with the background.

    I think the reason your character is falling through it is because it’s not checking whether you have landed on the ground rectangle. See if that helps.

    Happy programming.

  3. kobubu says:

    Dude your tutorials get better.
    I love how you explain the things now.
    Thanks for everything you do to us!

  4. anti says:

    realy nice tutorial! big thanks =)
    but i have a problem. if i execute the code in vs it is realy slow and lags all the time but if i start the exe under win10 its totaly smooth. so it must be a vs display failure. Do you know a solution for me to solve this issur in vs? its maybe a dump loading property which make it slow. thanks. have a nice day..

  5. anti says:

    maybe its the dispatcher timer because if i try to make a stop watch the displayed counting lags too. it’s the same as i do a normal clock or a timer for a media file. the time is always correct but the displaying is uneven and laggy. i hope you can help me. thanks.

  6. Stela Kostova says:

    Hello, I was wondering whether this could be done in Win Forms?

  7. Anhar Ali says:

    Yes you can do similar games in windows form. You won’t get the transparency with the player image and background if you use picture-boxes. This is why I’ve used WPF for this tutorial, it’s a lot easier to have transparency with sprite animation.