Difference between revisions of "Simple Racer"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(The Draw Method)
(The Car)
Line 116: Line 116:
  
 
=The Car=
 
=The Car=
 +
Create a new class in your project and call it Car.cs.
 +
 +
We will need to add the following to the using section of your new class:
 +
 +
<syntaxhighlight lang=c#>
 +
using Microsoft.Xna.Framework;
 +
using Microsoft.Xna.Framework.Graphics;
 +
using Microsoft.Xna.Framework.Input;
 +
using System;
 +
using System.IO;
 +
using System.Collections.Generic;
 +
</syntaxhighlight>
 +
 +
Now in the Car class declare the following variables:
 +
 +
<syntaxhighlight lang=c#>
 +
        Texture2D texture;
 +
        Texture2D tyre;
 +
        Vector2 position;
 +
        Vector2 origin;
 +
        float steer =0;
 +
</syntaxhighlight>
 +
 +
Now we need to create an init method to set up the car. This accepts the texture, position of the car and also calculates the origin point of the car (we will use this to rotate the car):
 +
 +
<syntaxhighlight lang=c#>
 +
        public void Init(Texture2D t,  Vector2 pos)
 +
        {
 +
            position = pos;
 +
            texture = t;
 +
            origin = new Vector2(t.Width / 2, t.Height / 2);
 +
        }
 +
</syntaxhighlight>
 +
 +
Now create a new method called GetInputs, this is used to control the car. It accepts the KeyboardState, which is checked for the key pressed. If the left arrow is pressed we are going to minus 0.05 from the current steer value. If the right arrow is pressed we are going to ad 0.05 onto the steer value:
 +
<syntaxhighlight lang=c#>
 +
        public void GetInputs(KeyboardState input)
 +
        {
 +
            if (input.IsKeyDown(Keys.Left))
 +
            {
 +
                steer -= (.05f);
 +
            }
 +
 +
            if (input.IsKeyDown(Keys.Right))
 +
            {
 +
                steer += (.05f);
 +
            }
 +
        }
 +
</syntaxhighlight>
 +
 +
Now create an Update method, it needs to accept the gameTime passed, the only code you need inside is to run the CheckInputs method above:
 +
 +
<syntaxhighlight lang=c#>
 +
        public void Update(GameTime gameTime)
 +
        {
 +
            GetInputs(Keyboard.GetState());
 +
 +
        }
 +
</syntaxhighlight>
 +
 +
Finally we need to add a Draw method. This is more complex than before because we need to rotate the texture.
 +
 +
<syntaxhighlight lang=c#>
 +
        public void Draw(SpriteBatch spriteBatch)
 +
        {
 +
            spriteBatch.Draw(texture, center,null,null,center,steer,null,null,SpriteEffects.FlipHorizontally,0);
 +
        }
 +
    }
 +
</syntaxhighlight>
 +
 +
==Create a car in Game1==

Revision as of 14:20, 8 December 2017

This tutorial will show you how to create a top down racing game, you will create a track, and your car will be able to complete a lap, time the lap, and potentially to complete a set number of laps. It will also cover simple AI to make the a ghost car drive around your circuit.

You could go on to learn about adding traction or skidding, adding collectables or weapons

Creating the Map

Tiled

You will firstly need to install the Tiled program from the website and link below. In college the Tiled executeables are on moodle, under project, technical skill, monogame, and tiled. I have also added links to other tutorials for using Tiled.

Tiled Website and Download

Tiled Map Editor

Tutorials for using Tiled

Offical Tiled Tutorials

Tiled Basics

Tiled Youtube Playlist Series

Written Version of Above Tutorials

Create a Map in Tiled

Map Settings

You will need to create a new map in tiled, the settings window below should be displayed:

Tiled settings.gif

The Tile size will need to match the tile size of your tileset. You can also specify the number of tiles in your your map, this and the tile size will create a map of a given size in pixels. The tiles i will use are 128 x 128 pixels, this will create quite a large map but we are only going to show the area around the car and not the whole map at once. You should be able to leave everything else the same.

You should now have an empty map, later on we will use Square.Tiled to draw the map this only supports maps in the Base64 GZIP format. So in the properties panel set the Tile Layer Format to Base64 (gzip compressed):

File:Tiled compression setting.gif

The map itself

I have created a map with 3 different tile layers, one for the collision which includes all of the tyres, a track layer which only contains the track peices, and a layer for the mud or grass for the background.

I have also created an object layer with the players starting location, the 2 check points and the start line all stored as objects. I have also created a custom property for the number of checkpoints (this may change depending on the track).

Racer map.gif

MonoGame Project

Create a new MonoGame project, mine is a Windows project.

Setup Square.Tiled

If you have a project ready, create a new class in your project. Click project and new class and call it Tiled.cs, then copy the code from this document over the code in your new class: Square.Tiled Class

Remember to set the name space to Squared.Tiled.

You will need to add references in the using section for the following:

using System.IO;
using Squared.Tiled;

While you add those you may as also add the following for the use of List later:

using System.Collections.Generic;

Code to Display Map

Map Variables

At the top of your Game1 class add these additional variables:

Map map;
Layer collision;
Vector2 viewportPosition;
int tilepixel;

Game1 constructor

I have set the width and height in the constructor:

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            graphics.PreferredBackBufferWidth = 1280;
            graphics.PreferredBackBufferHeight = 720;
        }

LoadContent for map

In the LoadContent method add the following lines to load the map, the collision layer and to set the texture of the player. The variable tilepixel assumes your tiles are square, the number of pixels is taken from the map:

map = Map.Load(Path.Combine(Content.RootDirectory, "SimpleRacer.tmx"), Content);
collision = map.Layers["Collision"];
tilepixel = map.TileWidth;
viewportPosition = = new Vector2(map.ObjectGroups["Objects"].Objects["Player"].X - 640, map.ObjectGroups["Objects"].Objects["Player"].Y-360);

The Update Method

You will also need to update the viewportPosition, this will center the map onto the player:

viewportPosition= new Vector2(map.ObjectGroups["objects"].Objects["Player"].X - (graphics.PreferredBackBufferWidth/2), map.ObjectGroups["objects"].Objects["Player"].Y - (graphics.PreferredBackBufferHeight/2));

The Draw Method

Add the following to the draw method to draw the map and hero to the screen.

If you already have spriteBatch.Begin() or spriteBatch.End() then just place the middle line inbetween your lines.

spriteBatch.Begin();
map.Draw(spriteBatch, new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height), viewportPosition);
spriteBatch.End();

At this point your project should run an display your map centered onto the player location.

The Car

Create a new class in your project and call it Car.cs.

We will need to add the following to the using section of your new class:

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.IO;
using System.Collections.Generic;

Now in the Car class declare the following variables:

        Texture2D texture;
        Texture2D tyre;
        Vector2 position;
        Vector2 origin;
        float steer =0;

Now we need to create an init method to set up the car. This accepts the texture, position of the car and also calculates the origin point of the car (we will use this to rotate the car):

        public void Init(Texture2D t,  Vector2 pos)
        {
            position = pos;
            texture = t;
            origin = new Vector2(t.Width / 2, t.Height / 2);
        }

Now create a new method called GetInputs, this is used to control the car. It accepts the KeyboardState, which is checked for the key pressed. If the left arrow is pressed we are going to minus 0.05 from the current steer value. If the right arrow is pressed we are going to ad 0.05 onto the steer value:

        public void GetInputs(KeyboardState input)
        {
            if (input.IsKeyDown(Keys.Left))
            {
                steer -= (.05f);
            }

            if (input.IsKeyDown(Keys.Right))
            {
                steer += (.05f);
            }
        }

Now create an Update method, it needs to accept the gameTime passed, the only code you need inside is to run the CheckInputs method above:

        public void Update(GameTime gameTime)
        {
            GetInputs(Keyboard.GetState());

        }

Finally we need to add a Draw method. This is more complex than before because we need to rotate the texture.

        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(texture, center,null,null,center,steer,null,null,SpriteEffects.FlipHorizontally,0);
        }
    }

Create a car in Game1