Getting started creating games from scratch - object interaction and UI display

It takes far more time to make tutorials than to develop games yourself... Continue to write game tutorials for Little Dinosaur

The environment is built here

Getting started creating games from scratch - Unity3d environment construction_Momie d's blog-CSDN blog

Material import and basic page introduction are here

Getting started creating games from scratch - using the Unity editor_Momie d's blog-CSDN blog

The game object's movement and interaction logic script is here

Getting Started with Creating Games from Scratch - Script Editing of Game Objects_Momie d's Blog-CSDN Blog


  • object interaction

Last time when I was fixing the bug that dinosaurs could jump infinitely, it was considered an interaction. Next is the code for the interaction between obstacles and dinosaurs.

need:

1. The cactus moves to the left as in the previous scene

2. The game ends when the dinosaur touches the cactus

First of all, requirement 1 is very simple. Just add the last object movement script.

Then add a collision volume, the same as when you created the dinosaur and the floor last time. Then when you test the game, the cactus will appear and wash away the small dinosaur.

 Then if you trigger the interaction that ends the game, you need to add a label to separate the collision of the floor and the collision of the cactus.

Select a game object, and then click [Tag] on the right - [Add Tag]

 Click the plus sign here to add a tag

 Add [Cactus] tag and save

 Then reselect the cactus game object and change the label to [Cactus], so that you can determine which object triggers the judgment based on the tag.

Then add a judgment to the dinosaur script. If the label is [Cactus] is touched, the game will terminate.

public class DinosaurScript : MonoBehaviour
{
    Rigidbody2D rb;//控制物体下落的组件
    public float jumpHeight;//跳的高度
    bool isJumping;//判断是否正在跳

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        isJumping = false;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space)&& isJumping == false)//只有满足按下空格同时能跳时才能跳起
        {
            rb.velocity = new Vector2(0, jumpHeight);
            isJumping = true;//一旦跳起了就变成不能跳了
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        isJumping = false;
        if (collision.gameObject.tag == "Cactus")//如果接触的对象标签为Cactus时
        {
            Time.timeScale = 0;//这是unity的自带时间函数,等于0时游戏停止
        }
    }
}

Then when playing the test game, you can control the small dinosaur to jump until the dinosaur hits the cactus and the animation will stop.


  • Display of game UI

When the game ends, there needs to be a prompt and a button to restart.

The first is to create the text file of Game Over. There are 2 Text formats in Unity.

One is to right-click - UI - text TextMeshPro

When this text is generated, the following window will appear. After clicking Import TMP Essentials, various assets of this text will be added to the asset root directory. However, this format of text does not support the tff format font file of this game, so another type of text is used.

One is to right-click-UI-Old version-Text

After selecting this text object, drag the font file to the position of the font on the right

Adjust the font size and text box size. If the font size is too large and the text box is too small, the text content may not be displayed. 

There is a strange thing here. The text is a sub-object of Canvas (red box), and the range of the Canvas object changes with the size of the game screen, and the text is displayed within this range. But other game objects (dinosaurs and background objects) are actually within a very small range (yellow box).

 

Next, add a game retry button, right-click on the game object - UI - Old version - Button

A button object and the text on the self-object button and the EventSystem object will be generated.

We don’t need the text, so we first delete the text sub-object and modify the button pattern.

Just drag the assets of the reopen button to the source pattern of the image, and then adjust the position and size like the text (green box) 

 If you create an image object first and then create a button component on the right side, it cannot be triggered. I don’t know why, and I am still researching it. And if the image object is created first, the size of the image is no longer in the canvas coordinate system, but in the coordinate system of the default layer.

One thing to note is that the retry button and text must be placed in the same parent object (red box on the left), so that when the parent object is operated, the button and text will appear and disappear at the same time (red box on the right)

Since it will not be displayed until the end, the parent object will be hidden now. That is, remove the √ on the right

 Next, we need to write the UI display timing of the game end and the restart game script of the retry button.


  • Gamemanager script

It is said that every game will have a Gamemanager script, which records all the game attributes and game mechanics of the game.

We create a script called Gamemanager in the assets, and the script icon will automatically turn into a gear.

 After opening the script, add the script for game termination and UI display when the game ends

public class GameManager : MonoBehaviour
{
    public GameObject GameOverScene;//创建名为GameOverScene的游戏对象

    // 游戏结束时游戏终止和UI展示
    public void GameOver()
    {
        Time.timeScale = 0;
        GameOverScene.SetActive(true);//将GameOverScene这个游戏对象显示
    }

    // Start is called before the first frame update
    void Start()
    {
        
    }

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

}

At the same time, modify the dinosaur script and replace the original script that determines the game termination with the gameover function in the Gamemanager script.

public class DinosaurScript : MonoBehaviour
{
    Rigidbody2D rb;//控制物体下落的组件
    public float jumpHeight;//跳的高度
    bool isJumping;//判断是否正在跳

    public GameManager gm;//gamemanager组件

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        isJumping = false;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space)&& isJumping == false)
        {
            rb.velocity = new Vector2(0, jumpHeight);
            isJumping = true;
        }
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        isJumping = false;
        if (collision.gameObject.tag == "Cactus")
        {
            //Time.timeScale = 0;
            //改成使用gm的函数进行游戏终止的操作
            gm.GameOver();
        }
    }
}

But to reference the GM function, you need to create an empty GM object in the game object first, and then drag the GM script into the GM object (red arrow)

At the same time, drag the UI parent object of the game over to the GameOverScene (green arrow)

 Then, drag the GM object into the dinosaur object

When testing the game in this way, when the dinosaur touches the cactus, the game will stop and the UI will be displayed at the same time.


  • Reopen button settings

The next step is to write the script for the reopen button, but first we need to rename the scene name. First click on the scene, then right-click [Open Scene Assets] (upper left box), then modify the name of the scene file in the assets window (lower asset box). After modification, you need to reload the file (middle confirmation window)

Then write a script. Just like the GameOver method, write the Restart method in the GM script. Note that a parameter is added to the start function to reset the game running speed to normal speed.

using UnityEngine.SceneManagement; //需要加上这个类

public class GameManager : MonoBehaviour
{
    public GameObject GameOverScene;

    // Start is called before the first frame update
    void Start()
    {
        /*注意这里加了一个参数,游戏开始先重置游戏速度为1,不然游戏重新载入时会是静止的*/
        Time.timeScale = 1;
    }

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

    // 游戏结束时游戏终止和UI展示
    public void GameOver()
    {
        Time.timeScale = 0;
        GameOverScene.SetActive(true);
    }

    public void Restart()
    {
        SceneManager.LoadScene("lv1"); //unity自带的场景展示函数,读取指定场景名的场景
    }

}

To reopen the icon, you need to click the [+] sign in the [Mouse Single] of the button component.

 

Then drag the GM object into this component (red arrow), and then select the restart function in the GM script in the drop-down box, so that after the Button is displayed when the game is running, clicking it will reload the specified scene.

In this way, the game is complete!

The above are most of the things I learned from the 15-minute game tutorial video of You Tu Turtle. Next, I will study how to further improve the game content, such as increasing health points, randomly refreshing cactus, and randomly flying birds.

Guess you like

Origin blog.csdn.net/dwe147/article/details/126898794