五.給食物添加觸發器(trigger)
1.OnTriggerEnter:
剛觸碰
2.OnTriggerExit:
離開
3.OnTriggerStay:
在觸發器裡
這裡使用了OnTriggerEnter
給food prefab 添加一個tag:pickup
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAzNvwVZ2x2bzNXak9CX90TQNNkRrFlQKBTSvwFbslmZvwFMwQzLcVmepNHdu9mZvwFVywUNMZTY18CX052bm9CXzUlaNBTVU9UeRpHW4Z0MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2LcRHelR3LcJzLctmch1mclRXY39zN0cjNxQDNyEjNxgDM4EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
然後勾選上Is Trigger(将它設定為碰撞觸發器)
然後在play的辣個腳本裡面添加一段代碼
就變成了:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playercontroller : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float horizontal_move = Input.GetAxis("Horizontal");//控制左右
float vertical_move = Input.GetAxis("Vertical");//控制前後
GetComponent<Rigidbody>().AddForce(new Vector3(horizontal_move, , vertical_move)*);//添加移動的力,因為不上下移動,是以y軸為0
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag =="pickup")
{
Destroy(other.gameObject);
}
}
}
六.添加一個記分哒
建立: create-UI-Text
然後又要在player的辣個腳本裡面加東西了;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class playercontroller : MonoBehaviour {
private int Score;
public Text count;
void setcount()//用于更新或重置分數
{
count.text = "Score:" + Score;
}
// Use this for initialization
void Start () {
Score = ;
setcount();
}
// Update is called once per frame
void Update () {
float horizontal_move = Input.GetAxis("Horizontal");//控制左右
float vertical_move = Input.GetAxis("Vertical");//控制前後
GetComponent<Rigidbody>().AddForce(new Vector3(horizontal_move, , vertical_move)*);//添加移動的力,因為不上下移動,是以y軸為0
setcount();
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag =="pickup")
{
Destroy(other.gameObject);
Score++;
}
}
}
然後把辣個player裡面的
(語無倫次描述不清楚就直接放圖了。゜(`Д´)゜。,就是把那個count後面選擇Text)
然後就會吃到一個食物就加一分辣!
最吼加了一段當Score==10時(因為我設定了10個食物),就顯示“WIN!”的代碼,就懶得再貼一次了,然後終于做完我人生中第一個遊戲了qwq