Sharp Coder is reader-supported, meaning when you buy through links on our site, we may earn an affiliate commission.
HomeBlogUnityGame

Unity Mini Game | CUBEavoid

0 Comments - Mar 28, 2021
329

Mini-game CUBEavoid, made with Unity. Source code, and set up below.

The goal is to avoid the small cube by re-scaling the big cube with the mouse cursor.

Step 1: Create all the necessary scripts

  • Create a new script, call it SC_PlayerCube.cs, remove everything from it, and paste the code below inside it:

SC_PlayerCube.cs

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

public class SC_PlayerCube : MonoBehaviour
{
    //Assign enemy mesh renderer
    public MeshRenderer enemy;
    public Text gameOverText;

    Transform thisT;
    MeshRenderer mr;

    //Global static variable
    public static bool GameOver = false;

    // Start is called before the first frame update
    void Start()
    {
        thisT = transform;
        mr = GetComponent<MeshRenderer>();
        gameOverText.enabled = false;
    }

    // Update is called once per frame
    void Update()
    {
        if (GameOver)
            return;

        if (gameOverText.enabled)
        {
            //Game has resumed, disable game over text
            gameOverText.enabled = false;
        }

        //Scale player cube with mouse movement
        Vector3 playerScale = (new Vector3(Screen.width / 2 - Input.mousePosition.x, 1, Screen.height / 2 - Input.mousePosition.y)).normalized * 10;
        //Keep Y scale at 10
        playerScale.y = 10;
        //Limit minimum X and Z scale to 0.1
        if (playerScale.x >= 0 && playerScale.x < 0.1f)
        {
            playerScale.x = 0.1f;
        }
        else if (playerScale.x < 0 && playerScale.x > -0.1f)
        {
            playerScale.x = -0.1f;
        }
        if (playerScale.z >= 0 && playerScale.z < 0.1f)
        {
            playerScale.z = 0.1f;
        }
        else if (playerScale.z < 0 && playerScale.z > -0.1f)
        {
            playerScale.z = -0.1f;
        }
        thisT.localScale = playerScale;

        //Check if enemy have intersected with the player, if so, stop the game
        if (mr.bounds.Intersects(enemy.bounds))
        {
            GameOver = true;
            gameOverText.enabled = true;
        }
    }
}
  • Create a new script, call it SC_EnemyCube.cs, remove everything from it, and paste the code below inside it:

SC_EnemyCube.cs

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

//This script controls enemy cube AI
public class SC_EnemyCube : MonoBehaviour
{
    //Private variables
    Camera mainCamera;
    float movementTime = 0;
    Vector3 startPoint;
    Vector3 endPoint;

    // Start is called before the first frame update
    void Start()
    {
        //Get camera tagged "MainCamera"
        mainCamera = Camera.main;
        GenerateStartEndPoint();
    }

    //Assign start and end points slightly outside the Camera view
    void GenerateStartEndPoint()
    {
        Vector3 relativeStart;
        Vector3 relativeEnd;

        //Randomly pick whether to go Left <-> Right or Up <-> Down
        if (Random.Range(-10, 10) > 0)
        {
            relativeStart = new Vector3(Random.Range(-10, 10) > 0 ? 1.1f : -0.1f, Random.Range(0.00f, 1.00f), mainCamera.transform.position.y);
            if (relativeStart.y > 0.4f && relativeStart.y < 0.6f)
            {
                if(relativeStart.y >= 0.5f)
                {
                    relativeStart.y = 0.6f;
                }
                else
                {
                    relativeStart.y = 0.4f;
                }
            }
            relativeEnd = relativeStart;
            relativeEnd.x = relativeEnd.x > 1 ? -0.1f : 1.1f;
        }
        else
        {
            relativeStart = new Vector3(Random.Range(0.00f, 1.00f), Random.Range(-10, 10) > 0 ? 1.1f : -0.1f, mainCamera.transform.position.y);
            if (relativeStart.x > 0.4f && relativeStart.x < 0.6f)
            {
                if (relativeStart.x >= 0.5f)
                {
                    relativeStart.x = 0.6f;
                }
                else
                {
                    relativeStart.x = 0.4f;
                }
            }
            relativeEnd = relativeStart;
            relativeEnd.y = relativeEnd.y > 1 ? -0.1f : 1.1f;
        }

        //Convert screen points to world points
        startPoint = mainCamera.ViewportToWorldPoint(relativeStart);
        endPoint = mainCamera.ViewportToWorldPoint(relativeEnd);

        //Reset movement time
        movementTime = 0;
    }

    // Update is called once per frame
    void Update()
    {
        //Game over, wait for click
        if (SC_PlayerCube.GameOver)
        {
            //Click to resume
            if (Input.GetMouseButtonDown(0))
            {
                SC_PlayerCube.GameOver = false;
                GenerateStartEndPoint();
            }
            else
            {
                return;
            }
        }

        //Move enemy from one side to the other
        if(movementTime < 1)
        {
            movementTime += Time.deltaTime * 0.5f;

            transform.position = Vector3.Lerp(startPoint, endPoint, movementTime);
        }
        else
        {
            //Re-generate start / end point
            GenerateStartEndPoint();
        }
    }
}

Step 2: Setup

After the 2 main scripts are created, let's proceed with setting up the game:

  • Create a new Scene if you haven't yet
  • Select Main Camera, change its position to (0, 10, 0) and its rotation to (90, 0, 0)
  • Change Main Camera's Camera component properties: Clear Flags to 'Solid Color', Background to 'white', Projection to 'Orthographic', and Size to '10'

  • Create new Cube (Game Object -> 3D Object -> Cube) and name it "Player"
  • Change "Player" position to (0, 0, 0) and scale to (10, 10, 10)
  • Create new Material (Right-click on Project folder -> Create -> Material) and name it "PlayerMaterial"
  • Change "PlayerMaterial" Shader to Unlit/Color and change its color to black

  • Assign "PlayerMaterial" to "Player" cube
  • Duplicate "Player" cube and rename it to "Enemy"
  • Change "Enemy" scale to (0.7, 0.7, 0.7)
  • Duplicate "PlayerMaterial" and rename it to "EnemyMaterial"
  • Change "EnemyMaterial" hexadecimal color to 157EFB
  • Lastly, assign "EnemyMaterial" to "Enemy" Cube

CUBEavoid Scene View

Let's create a simple UI:

  • Create new UI Text (Game Object -> UI -> Text), rename it to "GameOverText"
  • Make sure the RectTransform alignment for the new Text is set to Middle Center
  • Set Text Pos X and Pos Y to 0
  • Change Height to 100
  • For the Text component, set the text below (make sure Rich Text property is checked):
Game Over
<size=15>Click to Try Again</size>
  • Set Font Size to 25
  • Set Text Alignment to Middle Center
  • Set Text Color to Red

CUBEavoid Game Over Text

Lastly, let's assign the scripts:

  • Select "Player" cube and assign SC_PlayerCube script to it
  • Assign "Enemy" cube to the Enemy variable
  • Assign "GameOverText" to Game Over Text variable

  • Select "Enemy" cube and assign SC_EnemyCube script to it

Now when pressing Play, the blue cube should begin moving across the screen, which you need to avoid by resizing the black cube, using the mouse cursor.

Feel free to improve this game in any way.

You Do Not Have To Do Everything Yourself
Search from thousands of ready-to-use Unity assets.
Visit Asset Store