Skip to Main Content






Unity tutorial

Script for ball

We will now add a code to make the ball jump.

 

In the Assets folder, right click > Create > Folder, name it "Scripts"

Right click in the folder > Create > C# Script

Name the script "Ball", click on the script to open it in Visual Studio

Copy the following code into the script and save the file:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ball : MonoBehaviour
{

    /*

     Variable -------------------------------->Data Type-------------------------> Usage
     JumpKeywaspressed-------------->Boolean-----------------------------> Changed to true when the space bar is pressed
     space_press_count ---------------->Integer------------------------------> Tracks of the number of jumps(max of 3 without touching the platform) 
     rigidbody_component-------------->Rigidbody--------------------------> Prevent calling the same class/component repeatedly on Update function
     ground_check------------------------>Transform--------------------------> Store the transform component of the gameobject that is used to check if the ball is touching the ground
     SpawnPoint-------------------------->Transform-------------------------->Store the transform component of the gameobject that is used to respawn the ball
    level1---------------------------------->GameObject------------------------>Store the "Level 1" gameobject, which is used to identify if the ball has fallen off

    */

    //Private variable allow the use of this variable on this class ONLY
    //[SerializeField] makes the variable display on the inspector window of unity
    private bool jumpKeywaspressed = false;
    private int space_press_count = 0;
    private float horizontal_Input;
    private Rigidbody rigidbody_component;
    [SerializeField] private Transform ground_check;
    [SerializeField] private Transform SpawnPoint;
    public GameObject level1;

    // Start is called before the first frame update
    void Start()
    {
        rigidbody_component = GetComponent<Rigidbody>();
        level1 = GameObject.Find("Level 1");//In this way the Level 1 doesn't need to be drag into the inspector, the code will find it from the scene
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))  //Check if the space bar was pressed
        {
            jumpKeywaspressed = true;

        }
        horizontal_Input = Input.GetAxis("Horizontal"); //Store input from right-left arrow keys, "A" and "D"

        // Moves the ball to the respawn location if the ball's position is 3 unit below the Level 1's position 
        if (GetComponent<Transform>().position.y < (level1.GetComponent<Transform>().position.y - 3.0f)) // "f" indicate the number is a floating type  
        {
            GetComponent<Transform>().position = SpawnPoint.transform.position;

        }

    }

    private void FixedUpdate()
    {

        //Assinging horizontal velocity to the ball by making horizontal input multiply by 3 
        rigidbody_component.velocity = new Vector3(3 * horizontal_Input, rigidbody_component.velocity.y, 0);

        /* The following if statement checks if the ground_check gameobject at bottom of the ball is colliding with the ground. 
          Physics.OverlapSphere create an imaginary sphere around that gound_check position with the diameter of 0.1 unit and output an array of information of the collision that the imaginary sphere is having. The array length of 1 will indicate the imaginary sphere is colliding with the ball only*/
        if (Physics.OverlapSphere(ground_check.position, 0.1f).Length == 1)
        {
            if (jumpKeywaspressed && space_press_count < 2)
            {
                rigidbody_component.AddForce(Vector3.up * 5, ForceMode.VelocityChange);
                jumpKeywaspressed = false;
                space_press_count = space_press_count + 1;
            }
        }
        else
        {
            space_press_count = 0;
            if (jumpKeywaspressed)
            {
                rigidbody_component.AddForce(Vector3.up * 5, ForceMode.VelocityChange);
                jumpKeywaspressed = false;
                space_press_count = space_press_count + 1;
            }
        }
    }
}

 

Click on the Ball in the Hierarchy window

Click on the Scripts folder and drag the Ball script into the inspector window of the Ball

  • From the Hierarchy window drag the GroundCheck component to the Ground_Check placeholder
  • From the Hierarchy window drag the Spawnpoint component to the Spawnpoint placeholder
  • From the Hierarchy window drag the Level 1 component to the Level 1 placeholder

Script for moving platform

We will now add a code to make the platform move right to left across the camera at a constant speed and get destroyed when they are out of  the camera view

 

Navigate to the Scripts folder

Right-click in the folder > Create > C# Script

Name the script "MovePlatform", click on the script to open it in Visual Studio

Copy the following code into the script and save the file:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovePlatform : MonoBehaviour
{

   /*Variable----------->Datatype--------------------->Usage
     speed-------------->Float--------------------------> Define the speed of the moving platform
     screenbound---->Vector2-----------------------> Use to store the width and height of the camera view
    */
    private float speed = 2;
    private Vector2 screenbound;
 

    // Start is called before the first frame update
    void Start()
    {
        GetComponent<Rigidbody>().velocity = new Vector3(-speed, 0, 0); //platform will move to the left of the screen with the defined speed
        screenbound = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
    }

    // Update is called once per frame
    void Update()
    {

        // If platform goes out screenboundary it will get destroyed to manage the memory space of game 
        if (transform.position.x < screenbound.x * 2)//2x is chosen to make sure the platform is way off the screen
        {
            Destroy(this.gameObject);

        }
    }
}

 

Select the Platform prefab in the Prefab folder

Click on the Scripts folder and drag the MovePlatform script into the inspector window of the Platform prefab

Script for generating platform

We will now add a code to make instantiates of the platform prefab on the right side of the screen(outside the camera video) at a defined time interval, so that the level auto-generates.

 

Navigate to the Scripts folder

Right-click in the folder > Create > C# Script

Name the script "DeployPlatform", click on the script to open it in Visual Studio

Copy the following code into the script and save the file:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DeployPlatform : MonoBehaviour
{

/*

    Variable-------------------->DataType-----------------------> Usuage
    platform-------------------->GameObject-------------------> Store the platform at prefab to instantiate more platform on the game scene
    spawnTimeinterval------>Float------------------------------> time interval between every platform instantiation
    screenbound-------------->Vector2--------------------------> Same as the platform.cs
    number--------------------->Integer--------------------------->Store the random number from 1 to 3 to randomize the platform instantiation level
    levelname----------------->String-----------------------------> Store the level name at which the platform will instantiate 

*/
    [SerializeField] private GameObject platform;
    [SerializeField] float spawnTimeinterval = 1.25f;
    private Vector2 screenbound;
    private int number;
    private GameObject level;
    private string levelname;    // Start is called before the first frame update
    void Start()
    {
        screenbound = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
        StartCoroutine(platformmove()); // We use StartCoroutine to ensure we can only pause the function called and not the whole game.
    }

    //The datatype for StartCoroutine parameter has to be IEnumerator
    IEnumerator platformmove()
    {
        while (true)
        {
            yield return new WaitForSeconds(spawnTimeinterval);//pause the routine for spawn time interval
            deployfloor();
        }
    }

    private void deployfloor()
    {
        GameObject floor = Instantiate(platform) as GameObject; //instantiate or create new platform
        number = Random.Range(1, 4);
        levelname = "Level " + number.ToString();
        level = GameObject.Find(levelname);

        //placing the instantiated platform on the far right(out of game/camera view) of the scene veiw
        floor.transform.position = new Vector3(screenbound.x * -2, level.GetComponent<Transform>().position.y, level.GetComponent<Transform>().position.z);
    }

}

 

Select the Main Camera in the Hierarchy window

Click on the Scripts folder and drag the DeployPlatform script into the inspector window of the Main Camera

  • From the Prefab folder drag the Platform prefab to the Platform placeholder

Adding Momentum

We will now update the Ball code so that it is easier to jump as the ball is falling, due to gravity the velocity when falling down becomes higher so it needs more force when jumping as it is falling.

 

Copy the following code into the Ball script and save the file:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Ball : MonoBehaviour
{
    private bool jumpKeywaspressed = false;
    private int space_press_count = 0;
    private float horizontal_Input;
    private Rigidbody rigidbody_component;
    [SerializeField] private Transform ground_check;
    [SerializeField] private Transform SpawnPoint;
    public GameObject level1;
    // flag==true means the ball hasn't touch any platform yet
    public bool flag = true; //flag is used to check if the ball has touched any platform once, so that the ball have 3 jump even when it spawn

    // Start is called before the first frame update
    void Start()
    {
        rigidbody_component = GetComponent<Rigidbody>();
        level1 = GameObject.Find("Level 1");
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            jumpKeywaspressed = true;

        }
        horizontal_Input = Input.GetAxis("Horizontal");
        if (GetComponent<Transform>().position.y < (level1.GetComponent<Transform>().position.y - 3.0f))
        {
            GetComponent<Transform>().position = SpawnPoint.transform.position;
            flag = true;

        }

    }

    private void FixedUpdate()
    {
        rigidbody_component.velocity = new Vector3(3 * horizontal_Input, rigidbody_component.velocity.y, 0);
        if (Physics.OverlapSphere(ground_check.position, 0.1f).Length == 1)
        {

            // having more upward force when the ball is falling down, will give the ball more momemtum to work against gravity


            /*
             Flag true means the ball is spawning
             */
            if (flag == true)
            {
                if (jumpKeywaspressed && space_press_count < 3 && rigidbody_component.velocity.y < 0)
                {
                    rigidbody_component.AddForce(Vector3.up * 10, ForceMode.VelocityChange);
                    jumpKeywaspressed = false;
                    space_press_count = space_press_count + 1;
                }

                if (jumpKeywaspressed && space_press_count < 3 && rigidbody_component.velocity.y > 0)
                {
                    rigidbody_component.AddForce(Vector3.up * 7, ForceMode.VelocityChange);
                    jumpKeywaspressed = false;
                    space_press_count = space_press_count + 1;
                }
            }
            else
            {
                if (jumpKeywaspressed && space_press_count < 2 && rigidbody_component.velocity.y < 0)
                {
                    rigidbody_component.AddForce(Vector3.up * 10, ForceMode.VelocityChange);
                    jumpKeywaspressed = false;
                    space_press_count = space_press_count + 1;
                }

                if (jumpKeywaspressed && space_press_count < 2 && rigidbody_component.velocity.y > 0)
                {
                    rigidbody_component.AddForce(Vector3.up * 7, ForceMode.VelocityChange);
                    jumpKeywaspressed = false;
                    space_press_count = space_press_count + 1;
                }

            }
        }
        else
        {
            space_press_count = 0;
            if (jumpKeywaspressed)
            {
                flag = false;
                rigidbody_component.AddForce(Vector3.up * 7, ForceMode.VelocityChange);
                jumpKeywaspressed = false;
            }
        }
    }
}