Unity-simple small game to control the ball (4)

trigger detection

First of all, let's solve the ball stop problem first, and use the second detection method to trigger the detection.

In the prefab pick up, check the is trigger of the box collider (trigger), run the program and the ball passes through the food without the food being eliminated. Open the player script, the code is as follows:

    //触发检测
    void OnTriggerEnter(Collider collider)
    {
        if(collider.tag=="pick up")
        {
            Destroy(collider.gameObject);
        }
    }
}

Now, we can eat food, and the food will not block the player's progress.

show score

Create a new UI and click text. Switch to 2D mode, as shown in the figure:

 The entire white line frame is our screen, we want to display the score in the upper left corner, select the text, click the icon on the right, press alt, and select the upper left corner of the picture.

 In this way, the text is fixed at the upper left corner of the screen. Make some adjustments to the position of the text.

using UnityEngine;
using UnityEngine.UI;

public class player : MonoBehaviour
{
    private Rigidbody rd;
    public int force = 5;
    public Text Text;

Written in the player script, because the text is to be referenced, the namespace of the UI must be referenced.

After saving the code, drag the text of the left canvas from the text in the player in the lower right corner:

 The following is the entire code in the player:

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

public class player : MonoBehaviour
{
    private Rigidbody rd;
    public int force = 5;
    public Text text;
    private int score = 0;
    // Start is called before the first frame update
    void Start()
    {
        rd = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        rd.AddForce(new Vector3(h,0,v)*5);
    }
    //碰撞检测
    void OnCollisionEnter(Collision collision)
    {
        if(collision.collider.tag=="pick up")
        {
            Destroy(collision.collider.gameObject);
        }
    }
    //触发检测
    void OnTriggerEnter(Collider collider)
    {
        if(collider.tag=="pick up")
        {
            score++;
            text.text = score.ToString();
            Destroy(collider.gameObject);
        }
    }
}

After saving and running, the score in the upper left corner can increase according to the number of food eaten.

Guess you like

Origin blog.csdn.net/qq_64573579/article/details/127720724