THIS CONTENT DOWNLOAD SHORTLY

Objective

Main objective of this post is to give an idea about Infinite track generation like road fighter game

 

In Infinite Track Generation games, you might have noticed that, the tracks in background are moving continuously. Here is an example of how to manage track generation in infinite games.

You will get Final Output:

Track Generation

 

Step 1 Create Prefab

Create prefabs for all the tracks.

 

Step 2 Object Pool

In this example, to reduce the load of object instantiation and destruction, object pool is used.

 

2.1 What is Object Pool?

Object pool is a software pattern, which uses a set of initialized objects.When a client program requests for a new object, the object pool first attempts to provide one that has already been created and returned to the pool. If none is available, only then a new is object created. So when you want an object from the pool, you have to request the pool, and pool will return requested object and you could perform operation on it. When the operation on requested objectwould finish, give that object to the pool rather than destroying it. Pool will return again that object whenever requested by you.

 

2.2 Important Methods

Some Important Methods are as under:

CreatePool() Create pool for the gameobject component.
Spawn() Used to get object from ObjectPool instead of Instantiate() method.
Recycle() Used to recycle gameobject to pool, instead of Destroy() method.
 

2.3 Why Object Pool is used?

Object Pool improves performance (as there is no new instances are created and destroyed). The Following C# code is for track management which will create Object Pool for all the track prefabs, allocate new track and recycle the track.

Note

Put this script on empty GameObject and name it as GameController.

 

Step 3 TrackCollection.cs

Some Important Methods are as under:

CreateTracksPool() Method will create ObjectPool for all the tracks.
AllocateTrack() Method will spawn new track from the pool randomly, and will add to the AllocatedTrackList list of the GameManager Class.
RecycleTrack() Method will call RemoveTrack() Method to recycle The track to the ObjectPool. Make sure that if you have just started the game and first track prefab loaded, it will not recycle the current track on Car Trigger event but it will spawn the same track again from the pool.
RemoveTrack() Method will recycle the track AllocatedTrackList[0] to the pool instead of destroying it and will remove the first track from the AllocatedTrack list of GameManager class.
GenerateTrack() Method will be called On trigger Enter event of track prefab's first track child. So, GenetateTrack() method will find its parent object and calculate verticle distance to adjust new track position and will call AllocateTrack() method to spawn a new track.
using UnityEngine;
using System.Collections;
 
public class TrackCollection : MonoBehaviour
{
public GameObject[] tracks;
 
void Awake ()
{
CreateTracksPool ();
AllocateTrack (Vector3.zero);
}
 
private void CreateTracksPool ()
{
foreach (GameObject eachTrack in tracks) {
eachTrack.GetComponent ().CreatePool ();
}
}
 
public void AllocateTrack (Vector3 position)
{
int trackId = Random.Range (0, 3);
Track trackScript = tracks [trackId].GetComponent ().Spawn (position);
GameManager.Instance.AllocatedTrackList.Add (trackScript.gameObject);
}
 
public void RecycleTrack (GameObject trackObject)
{
if (GameManager.Instance.AllocatedTrackList.Count > 1)
RemoveTrack ();
GenerateTrack (trackObject);
}
 
private void RemoveTrack ()
{
GameObject trackGroupObject = GameManager.Instance.AllocatedTrackList [0];
trackGroupObject.GetComponent ().Recycle ();
GameManager.Instance.AllocatedTrackList.Remove (trackGroupObject);
}
 
private void GenerateTrack (GameObject trackObject)
{
Transform parentTransform = trackObject.transform.parent;
GameObject parentObject = parentTransform.gameObject;
Vector3 trackPosition = parentObject.transform.position;
trackPosition.y += Constants.TRACK_LENGTH;
AllocateTrack (trackPosition);
}
}
 

Step 4 MoveTrackByVelocity.cs

The next step is how to move track? All the track prefabs will have attached RigidBody2D with fixedAngle and 0 Gravity Scale. The following c# code snippet will move track vertically down side.

Note

Add this script on all track prefabs.

MoveTrackByVelocity.cs:

using UnityEngine;
using System.Collections;
 
public class MoveTrackByVelocity : MonoBehaviour
{
private Vector2 position;
private float speed = -20f;     // to move track vertically down side.
 
void Awake ()
{
position = Vector2.zero;
position.y = speed;
}
 
void FixedUpdate ()
{
rigidbody2D.velocity = position;
}
}
 

Step 5 Manage Tracks

Now it’s time to generate new track at the end of current track. Every track prefab will have 3 tracks in child. In those of 3, the first track child will have BoxCollider2D attached with trigger on, and ManageTrack.cs script, which will call RecycleTrack() method of TrackCollection Class, and it will allocate new track at the end of current track.

Note

Add this script on first child of every track prefabs.

ManageTracks.cs:

using UnityEngine;
using System.Collections;
 
public class ManageTracks : MonoBehaviour
{
private TrackCollection trackCollectionScript;
 
void Start(){
trackCollectionScript =GameObject.Find ("GameController").GetComponent ();
}
 
void OnTriggerEnter2D (Collider2D otherCollider)
{
if (otherCollider.CompareTag (Constants.TAG_CAR)) {
trackCollectionScript.RecycleTrack(gameObject);
}
}
}

Note

There are two more scripts Constants.cs and GameManager.cs

Add GameManager.cs script on Empty GameObject. There is no need to attach Constansts.cs file to any GameObject.

 

Step 6 Constants.cs and GameManager.cs

 

6.1 Constants.cs: 

This C# contains all the constant values.

using UnityEngine;
using System.Collections;
 
public static class Constants
{
public const string TAG_TRACK = "Track";
public const string TAG_TRACK_GROUP = "TrackGroup";
public const string TAG_CAR = "Car";
 
public const float TRACK_LENGTH = 57.6f;
}
 

6.2 calculate TRACK LENGTH

TRACK_LENGTH may vary; it depends on graphics resolution used for single track.

In this example, 1080 * 1920 graphics resolution is used; so single-track height is 19.2 (resolution height / 100) and there are three child tracks on single-track parent, so my total track length becomes 19.2 * 3 = 57.6.

Now, if you are using graphics resolution 1536 * 2048, then your single-track height is 20.48. So, now you can calculate TRACK_LENGTH as per your requirement like how many child tracks are there and multiplying number of children in single Track Parent with single-track height.

 

6.3 FORMULA

Number of children in single Track parent * height of single track

 

6.4 GameManager.cs

This C# file contains globally accessible variables.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
 
public class GameManager : MonoBehaviour
{
    private static GameManager instance;
    private List allocatedTrackList;
 
    void Awake()
    {
        instance = this;
        allocatedTrackList = new List();
    }
 
    public static GameManager Instance
    {
        get
        {
            return instance;
        }
    }
 
    public List AllocatedTrackList
    {
        get
        {
            return allocatedTrackList;
        }
    }
}

For any query or suggestions please comment below.

Got an Idea of Game Development? What are you still waiting for? Contact us now and see the Idea live soon. Our company has been named as one of the best Game Development Company in India.

I am a creative Game Developer. My aim and focus is on developing attractive games and tempting gamers to play games.

face mask Belial The Demon Headgear Pocket Staff Magic