close

Unity is not as hard as I thought, although I am a newbie in this field. I believe my little step leads me to the future. After a day of playing in the Unity world for the first time. I felt great when I finished a small project. In this project, I tried to integrate EmguCV, which is a wrapped OpenCV for .net framework,  into the Unity C# program and did a simple face detection. Each face's location represents an NBA player's position. For example, Stephen Curry is corresponding to face #0, Lebron James is face #1, and Ja Morant is face #2. As the video plays, all the NBA players can move to the locations according to their face numbers.

It's so fun for the beginner, isn't it?

Today I decided to learn more from a beginner project called "Roll-a-Ball". Behind my expectations, the speaker's English is specifically slow and the details are told step by step. That's very considerate and good for me to understand what they are talking about. Hooray!

Create a new project

1. Create a new folder named "Template", and then move all files and folders in the "Assets" to the "Template" folder

2. Press Save as in the top menu and then create a new folder called "Scene"

3. Save the above stuff as "MiniGame" in the "Scene" folder

 Well, a new Scene called "MiniGame" is created as shown below:

 

 So far, I've completed the first four steps in this tutorial.

Now I'm done with setting up the game. Add color to both the background and player.

Next, it's time to move the player

 

 Windows >> Package Manager

 Packages>> Unity Registry >> Input System

 

 

 

 on PC, choose x64 for windows users.

 =====================================================================

Add a player input component

choose <Player> object and click <Add component>

choose <Player input>

click <Create Actions> and then you can save a copy from the template.

 

create a new folder called input and save the copy as "inputActions"

then you will see a new component as shown below.

This component is called "inputActions", which is shown in the field of <Actions Asset>.

Since we want to receive the keyboard events, it is necessary to add a <Player input>

choose <Player> object and click <Add component>

choose <Player input> and set Actions to <inputActions

choose <Player> object and click <Add component>

choose <Script> and save as "PlayerController" in the Asssets/Scripts folder

 

using System.Collections;

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
 
public class PlayerController : MonoBehaviour
{
    public float speed = 1.0f;
    private Rigidbody rb;
    private float movementX;
    private float movementY;
 
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        Debug.Log(rb);
    }
    private void OnMove(InputValue movementValue)
    {
        Vector2 movementVector = movementValue.Get<Vector2>();
        movementX = movementVector.x;
        movementY = movementVector.y;
        Debug.Log(movementX);
        Debug.Log(movementY);
    }
    private void FixedUpdate()
    {
        Vector3 movement = new Vector3(movementX, 0.0f, movementY);
        rb.AddForce(movement*speed);
    }
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
Next, we are going to learn a new session: moving the camera
 

 

choose <Player> object and click <Add component>

choose <Script> and save as "CameraController"

 

As usual, move it to the Scripts folder for being organized

 

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class CameraController : MonoBehaviour
{
    public GameObject player;
    private Vector3 offset;
 
    // Start is called before the first frame update
    void Start()
    {
        offset = transform.position - player.transform.position;    
    }
 
    // Update is called once per frame
    void LateUpdate()
    {
        transform.position = player.transform.position + offset;
    }
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
The camera position won't be set until the player has moved for the frame.
This explains why we should call LateUpdate subroutine instead of Update.

 

3.Reference the Player GameObject

Select <Main Camera> and its Player property is referencing None Object.

Drag the player object into the Player of Camera Controller.

We call such an action a reference.

 

 

 

Create an object of Empty and rename it as Walls.

 

 Then select Walls and add a cube into it.

 

 Let's start creating a 3D object -> Cube

 

 Create a wall for the play field

 

The West Wall Transform is set as below:

 

Add a new Material called "Walls" and its color is RGB(79, 79, 79)

and its metallic map is 0 by default.

set its smoothness to 0.25

 

 Finally drag walls material and drop it onto West Wall in the scene view

 Duplicate West Wall and rename it as East Wall.

Set the position of East Wall to (10, 0, 0)

 

 Next, duplicate East Wall again and rename it as North Wall

 

We get North Wall as shown below by changing its X position to 0 and rotating 90 degrees w.r.t Y-axis.

Shift its z-axis to 10

Finally, duplicate South Wall in the same way as mentioned above.

1.Create a collectible GameObject

The transform settings are shown below and we're gonna add a script file by clicking <add component>

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Rotator : MonoBehaviour
{
 
    // Update is called once per frame
    void Update()
    {
        transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
    }
}

 

3.Make PickUp a Prefab

A prefab, which is another form of GameObject, can be duplicated again and again.

One important characteristic of a prefab is that you can change it then all its copies will be dynamically updated without modifying them one by one.

A prefab is like a library that many projects can refer to it. Once you modify the library, all the projects will update themselves automatically.

Now let's create a new folder and rename it as <Prefabs>

 

 

 Drag a GameObject, ex. Pickup item, into Prefabs folder. 

 

After that, you'll see the Pickup turn blue in the Hierarchy. Unity creates a new prefab asset containing a template. or a blueprint, of the GameObject family.

In the next step, we'll instantiate it around the play area for the player to collect.

Now, change the viewpoint from the top. Duplicate twelve copies and arrange them in a circle like this

 

=====================================================================================

1.Disable PickUps with OnTriggerEnter

Open PlayerController script file

 
    private void OnTriggerEnter(Collider other)
    {
        Debug.Log(other.name);
        other.gameObject.SetActive(false);
    }

2. Click PickUp prefab as shown below that it would be in edit mode

Click Tag and choose "Add Tag" when it pops up

Add a new Tag, which is called "PickUP".

Assign PickUp Tag to the prefab. And all the other copies will be updated with the same tag name.

 

3.Write a conditional statement

    private void OnTriggerEnter(Collider other)
    {
        //if(other.gameObject.tag=="PickUp")
        if(other.gameObject.CompareTag("PickUp"))
        {
            other.gameObject.SetActive(false);
        }
   
    }
 

4.Set the Pickup Colliders as triggers

Enable Is Trigger property 

Go back to play mode, you can see that the pickup disappears if it collides with the player.

Because in PlayerController script file, we just deactivated the GameObject(pickup) in the OnTriggerEnter callback function.

 In the Hierarchy, click "+" >> UI >> Text TextMeshPro

 

Then pop up a window and clcik "import TMP Essentials"

 

There is a Text showing in Canvas, ie. the UI text element.

However, I didn't find a GameObject called EventSystem in my Unity

Rename Text(TMP) as CountText

Select CountText and press "F" shortcut

CountText is labeled with "Count Text"

First, hold "Shift + ALT" keys, and select the top-left item in the Anchor Presets.

The text moves to the top left corner

3.Display the count value

Open PlayerController script

1. add a new namespace

using TMPro;  // TextMeshPro

2.  add a public variable that is used for receiving a real instance of TMPro from Unity GUI

public TextMeshProUGUI countText;

3. add a function called 

    void SetCountText()
    {
        countText.text = "Count: " + count.ToString();
    }

4. call SetCountText()

 private void OnTriggerEnter(Collider other)
    {
        //if(other.gameObject.tag=="PickUp")
        if(other.gameObject.CompareTag("PickUp"))
        {
            other.gameObject.SetActive(false);
            count++;
            SetCountText();
        }
   
    }
Close the script and take a look at Player GameObject.
There is nothing in the field of Count Text, ie. None(Text Mesh Pro GUI)

 Drag CountText GrameObject and paste it onto the fieldname of CounterText, as shown below 

Now, go back to play mode.

Count accumulates as the player collides with any pickups.

We're gonna add another TMP to display a message of "You win!" when the player has collected 12 pickups.

Rename it as "WinText" and click "Shift + ALT" buttons to set its location to the center position.

Also lift WinText by setting PosY to 150.

Edit PlayerController script

1. add a public variable of GameObject type 

 public GameObject winText;   // you can use either GameObject or TextMeshProUGUI

2. set itself invisible when the game starts

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        count = 0;
        winText.SetActive(false);
    }

3. set itself visible when the player has collected more than 12 pickups

 private void OnTriggerEnter(Collider other)
    {
        //if(other.gameObject.tag=="PickUp")
        if(other.gameObject.CompareTag("PickUp"))
        {
            other.gameObject.SetActive(false);
            count++;
            SetCountText();
            if (count >= 12)
            {
                winText.SetActive(true);
            }
        }
 
   4. close the script and check player settings, you can see that there is a new field called "Win Text"
   
Associate WinText TexMeshPro in the Canvas with Player's WinText field.

Hooray! Win Text pops up as soon as the player's mission is completed.

======================================================

1.Create a build of your game

Before you build your game, make sure to save your scene one last time.

File -> Build Settings

Drag MiniGame in the Scene asset into the Building Settings.

Build only the current scene

click Player Settings

 

Hooray. Roll-a-ball project has been done successfully.

 

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 me1237guy 的頭像
    me1237guy

    天天向上

    me1237guy 發表在 痞客邦 留言(0) 人氣()