In this unity 2d racing game tutorial we will be building a hypercasual racing game for mobile.

This will be a simple unity 2d car game. So what this will entail is having a background that can infinitely scroll.

Some obstacles we need to dodge. Some scoring system.

As well as a way to control our car using our mobile phones accelerometer. We then will implement unity ads to monetize the game for the app store.

Here is the basic mockup design of the game we will be building.

unity 2d racing game mockup

So we have some roadblock signs. A pothole which we need to avoid. A road which we drive on and cannot go off of.

Our yellow car will be our player’s car which will be dodging all sorts of obstacles.

We have some overhead clouds to make it a bit more challenging to see objects.

First I have gone ahead and exported each of the above assets seperately to bring into unity.

So I have done that and you can download the assets for this project by filling in the form below.

Let’s get started with a blank new unity project.

Create unity2d racing game project

Start off with a 2d unity project.

new unity racing game project

Let first setup our scene to fit our mobile screen. Click on Game.

We no need to add a aspect ratio which will fit a mobile device. So go ahead and add a new aspect ratio which is 9:16 for portrait.

To do this click on Free Aspect to get a drop down like this.

Click on the plus at the bottom to add a aspect ratio.

Next we want to configure our build settings for our game to be in portrait mode. So head over to build settings.

Then click on player settings so we can change to portrait.

Change the following option below to portrait.

That should get your project ready for building to mobile. Let us now start on the first portion of getting our game to work. We need to create a background.

Scrolling background for our unity racing game

First create a 3d quad which we can use in our scene to texture our background onto.

Rename it to Background and resize it to fit the viewport or scene size like so.

unity 2d racing game tutorial background

Next take your background sprite and drag it onto the quad. To get something like this.

We now want to add a light to light up our scene so right click in the hierarchy and click and create a directional light.

Once that is done you should have your background light up like this.

unity 2d racing game tutorial – light for road

Once this is done we need to tweak a few settings first of which is we need to change our sprite to a repeat sprite.

To do this go over to your project tab and click on the road.png file.

Then on the right make sure to change the setting in the screenshot below and click apply once done.

Great so now we have this going. We now need to just create a script to control our background scroll.

We going to add some additional options to our script to allow us to scroll other items as well.

Go ahead and create a new folder called scripts.

Once done, right click again and create a new c# script called ScrollingBackground.cs.

Here is what our script will look like.

using System.Collections; using System.Collections.Generic; using UnityEngine; public class ScrollingBackground : MonoBehaviour { Renderer rend; public float scrollSpeed = 10.5f; public bool xAxis; // Start is called before the first frame update void Start() { rend = GetComponent<Renderer>(); } // Update is called once per frame void Update() { float offset = Time.time * scrollSpeed; if (!xAxis) { rend.material.SetTextureOffset("_MainTex", new Vector2(0, offset)); } else { rend.material.SetTextureOffset("_MainTex", new Vector2(offset,0)); } } }

First we declare a renderer which will give us access to our Quads material. Then we setup a scrollSpeed and add a xAxis boolean.

This is so we can control which direction we will scroll in. In the start method we will get our renderer component and assign it to rend.

Then finally in our update method we will calculate our offset which takes our time and multiplies it by our scroll speed. Then we do a check for which axis we are scrolling on and apply a texture shift on that axis.

Once you have your script ready go ahead and drop it onto your Background quad like below.

I have set the scrolling speed to 1 to give it a reasonable scrolling speed. If you have done everything right you should end up with this.

Adding clouds using a similar concept as the scrolling background

So let’s quickly as another easy effect. Lets add scrolling clouds. So again add a new quad to your scene.

Call it Clouds. Then go ahead and drag and drop your clouds.png onto your quad so that it looks like below.

If yours does not look like this you may need to adjust your clouds material. Head over to the materials folder.

Then go ahead and select your clouds material.

On the right you will need to select rendering mode fade like this.

Go back up one folder and select your clouds and make sure you have repeat select and click apply.

Then simply drag the ScrollingBackground script onto the quad and check the xAxis check box. Use the settings I used below.

If you have done all correctly you will end up with this.

Great next we need to create the car controller for our game.

Creating car controller for our unity 2d game

First thing we want to do is just bring our car into our scene. So go over to the car.png file and drag it into the hierarchy.

Resize it to fit the game like below.

Importance of sorting layers

Before we attempt to control our player let’s just fix all our sorting layers. To do this click on the car object in your hierarchy.

On the right you want to look for this option.

Click on the drop down and click on add sorting layer.

Create these sorting layers and re arrange them by dragging them up and down like this.

Once that is done we want to assign them so click on your car again and change your sorting layer to this

Unity 2d Car controller script

To get started on our script you need to add a Rigidbody2D to your car. To do this click on your car in the hierarchy.

Then on the right click on add component. Then search for rigidbody2d and add it.

Next we need to make sure our rigidbody2d is a kinematic body. So on the right make sure your settings look like this.

unity 2d car controller kinematic body

Great now we can create our car controller script. To do this go into your scripts folder and right click and create a c# script called PlayerController. Open up the cs file and drop this in there.

using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { private Rigidbody2D rb; public float moveSpeed = 1.0f; private float direction; // Start is called before the first frame update void Start() { rb = GetComponent<Rigidbody2D>(); } // Update is called once per frame void Update() { direction = Input.GetAxisRaw("Horizontal"); } private void FixedUpdate() { rb.velocity = Vector2.zero; rb.velocity = new Vector2(direction * Time.fixedTime * moveSpeed, 0); } }

So here is how the script works. First we declare a rigidbody2d as rb. Then we declare movespeed and direction.

These will control the direction and speed we moving in. In the start method we initialize our rigidbody2d component.

Then in our update method we get a direction using the GetAxisRaw method on the horizontal axis.

This will also allow us to use our mobile device’s sensors to control our car. Then in our FixedUpdate method we zero out our velocity so that we don’t have acceleration.

Then finally we apply velocity on the x axis using the fixedTime, moveSpeed and direction from our input.

Finally drag this onto your car and use my settings like below.

If all was done correctly you should now be able to hit play and end up with this. If you press the right and left arrow keys you should be able to move the car around.

Next let’s add a basic UI menu which we can use to play our game.

Unity 2d racing game, creating a menu

In order to create a menu for our game we need to first create a new scene. So go to file then click on new scene.

Press ctrl+s or cmd+s if on mac and save it as Menu.

So we going to create a very simple menu like this.

To do this first we want to bring in a canvas. So in your hierarchy right click and create a canvas.

Now our canvas is not going to be the right size at the moment you might see something like this.

Our canvas is not being sized for our camera correctly so to fix this we want to go and make some changes. So click on the canvas on the left.

Then on the right make the following change.

Make sure to drag your main camera for the scene into the render camera slot.

Let’s now add a button so on the left right click on canvas and click on create button.

Now you should have something like this.

Click on text and go ahead and change your text for your button on the right.

Now to decorate I drag in the car and our road background like below.

To get this.

Great now we need a way to manage our UI. So for this we will create a UIManager script. So go over to your scripts folder.

Create yourself a UIManager c# script.

So open that up in visual studio and paste this code in there.

using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class UIManager : MonoBehaviour { public void StartGame() { SceneManager.LoadScene("Main"); } }

So very simple it is important that you do not forget to bring in UnityEngine.SceneManagement.

Once that is done we create a public method StartGame and then inside there we simply load up our main scene.

Once this is done just drag and drop this onto your canvas game object like below.

Next we need to attach our button to our StartGame function. So to do this click on the Button in the hierarchy.

On the right in the inspector we now need to attach a gameobject. So drag and drop your canvas into your on click slot.

Once done click on the No Function drop down. Go over to UI Manager and click on the start game method.

Now go ahead and hit the unity play/run button. Then you should have this.

That’s all we need for our menu and ui for now. Next we need to move on to creating our obstacles.

Unity 2d racing game: spawning objects and obstacles

You want to now go back and make sure you open up your main scene. So go over here and double click.

Let’s bring potholes in has a hazard. So drag the pothole into the scene make sure you size it down to fit the game like this.

What we want to do now is add a rigidbody2d and a collider. So to do that add a rigidbody2d and collider like below. Make sure you have the same settings as well.

Now that you have that we need a way to move our pothole on the road so that it matches our background scroll speed.

So for simplicity sake we are now going to create a Hazard.cs script. Go ahead and add it to your scripts folder and open it up in visual studio.

So for now we are going to keep it very simple. We will move it on the x axis at a fixed velocity which we can set.

Here is our script.

using System.Collections; using System.Collections.Generic; using UnityEngine; public class Hazard : MonoBehaviour { public float moveSpeed = 10f; private Rigidbody2D rb; // Start is called before the first frame update void Start() { rb = GetComponent<Rigidbody2D>(); } // Update is called once per frame void FixedUpdate() { rb.velocity = Vector2.zero; rb.velocity = new Vector2(0, moveSpeed * Time.fixedDeltaTime * -1); } }

So very simple again. We have a move speed, rigidbody. In start we initialize our rigidbody.

Fixed Update we zero our velocity then apply our movespeed with our time.fixedTime and multiply it by -1. Go ahead and attach that to your pothole and add this moveSpeed.

So now you should have something like this.

Great so now what we need to do is just add a collider to our car as well so we can detect collisions. So to do this click on the car in the left hand side and add a box collider 2d.

Now we need to handle the collision open up your CharacterController script again in visual studio and add the following code.

private void OnTriggerEnter2D(Collider2D collision) { Time.timeScale = 0; Destroy(gameObject); }

Time.timeScale 0 is going to pause our game and Destroy will kill our player. OnTriggerEnter2D will detect when we collide and run the code inside of it.

So this is all good and well now, but how to we restart our game. For this we going to add some UI again and use our UIManager to reload our scene.

So first of all lets add a canvas which is rendered by the camera like we learnt earlier and add a button. Set yours up like below.

You should end up with something like this now.

unity 2d racing game restart game

Rename your Canvas to RestartMenu then disable it on the right by unchecking this box.

In our CharacterController script we want to add the following bits of code.

public Canvas RestartMenu;

Save that off. Click on your car on the left and drag in your restart menu into the slot like this.

Now in our CharacterController in our OnTrigger function add this.

private void OnTriggerEnter2D(Collider2D collision) { Time.timeScale = 0; RestartMenu.gameObject.SetActive(true); Destroy(gameObject); }

If you play and the player dies you should now have the menu pop up.

So in our UIManager script we already have a function which will start the game so we can simply drag and drop our UIManager script onto our RestartMenu object like so.

In your UIManager you just need to add this code to your StartGame function to reset our time scale.

Time.timeScale = 1;

Like before click on the restart button on the left and attach the StartGame function.

Make sure you drag your RestartMenu into the slot otherwise it won’t work.

Great you should now have a functioning restart menu.

So that pretty much sums up how to add obstacles and kill the player. You can now easily go recreate more obstacles.

We now going to look at how we can implement a watch ad for monetization.

Implementing Unity Ads in our Game

For this let’s add a basic button to our RestartMenu which will have the text watch ad. So your hierarchy should look like this.

unity 2d racing game tutorial – watch ad menu setup

You now want to open your unity asset store and search for unity monetization.

Download and install this asset pack.

From here it is super easy to add the Video Rewards ads from Unity. Here is the code they provide on their website which works just fine.

Create a script called RewardedAdsButton. Add this code to this script and drag and drop this script onto our Watch Ad button.

using UnityEngine; using UnityEngine.UI; using UnityEngine.Advertisements; [RequireComponent (typeof (Button))] public class RewardedAdsButton : MonoBehaviour, IUnityAdsListener { #if UNITY_IOS private string gameId = "1486551"; #elif UNITY_ANDROID private string gameId = "1486550"; #endif Button myButton; public string myPlacementId = "rewardedVideo"; void Start () { myButton = GetComponent <Button> (); // Set interactivity to be dependent on the Placement’s status: myButton.interactable = Advertisement.IsReady (myPlacementId); // Map the ShowRewardedVideo function to the button’s click listener: if (myButton) myButton.onClick.AddListener (ShowRewardedVideo); // Initialize the Ads listener and service: Advertisement.AddListener (this); Advertisement.Initialize (gameId, true); } // Implement a function for showing a rewarded video ad: void ShowRewardedVideo () { Advertisement.Show (myPlacementId); } // Implement IUnityAdsListener interface methods: public void OnUnityAdsReady (string placementId) { // If the ready Placement is rewarded, activate the button: if (placementId == myPlacementId) { myButton.interactable = true; } } public void OnUnityAdsDidFinish (string placementId, ShowResult showResult) { // Define conditional logic for each ad completion status: if (showResult == ShowResult.Finished) { // Reward the user for watching the ad to completion. } else if (showResult == ShowResult.Skipped) { // Do not reward the user for skipping the ad. } else if (showResult == ShowResult.Failed) { Debug.LogWarning (“The ad did not finish due to an error.”); } } }

So let me try explain what is happening here. We have preprocessor blocks which will decide which unity ads id we will use for Android and IOS.

Then from there we have a button variable to hold our watch ad button. The button will then become ready and available to click when the ad system has been initialized.

We then add a click listener to the button which will trigger the showrewardedvideo function which simply shows the ad.

OnUnityAdsReady will check when the ad system is ready to enable our button. OnUnityAdsDidFinish has a few blocks one which is finished, if you want to reward your player this is where you would do it.

Skipped and failed you would not reward them. That basically is the code needed to show ads. If you have done this correctly you will end up with this when you click Watch Ad.

So that’s it, thats how you can implement a unity 2d racing game from scratch with monetization and UI menus.

There is a lot more which needs to be added to make this a commercial game which can be released on the app store.

However this tutorial has covered all the skills you need to take this project further to build your own game which can be monetized.

Some frequent questions

How to make a racing game? You can easily create a racing game using the unity game engine. Especially 2d racing car games. Which you can easily make with a bit of graphics made in inkscape/aseprite and using a little bit of code to put the game together.

How to make a infinite scrolling background? Usually to make infinite scrolling background in your games you need to use a texture offset with a repeating background.

How to make a unity 2d game? You can make a unity 2d game with some pixel art, then using the unity animation system and c# scripts to build a basic 2d game quite easily.

How to create an awesome racing game? The best thing you can do for your racing game is to have a compelling game narrative. Also add special effects like smoke, fire and other effects you typically will see in racing. This will just spruce up your racing game quite a bit.

How to create a drag racing game? If you are building this for mobile this will be similar to an infinite runner mechanic which will run in landscape mode. So you will just need to create a scene in landscape mode in your game engine and apply physics to your various cars using input.

Final words

If you liked this tutorial please consider sharing it on social media and checking out my YouTube Channel and subscribing. I will be creating a bunch of new tutorials soon as well as publishing some dev logs of some of my games I am developing. So be sure to follow me on twitter, join the discord and subscribe to the YouTube channel.

Here are some more tutorials or articles if you are interested in game development.

Check out some of these videos if you are interested in building a 2d platformer using the godot engine.