五.给食物添加触发器(trigger)
1.OnTriggerEnter:
刚触碰
2.OnTriggerExit:
离开
3.OnTriggerStay:
在触发器里
这里使用了OnTriggerEnter
给food prefab 添加一个tag:pickup
然后勾选上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, 0, vertical_move)*10);//添加移动的力,因为不上下移动,所以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 = 0;
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, 0, vertical_move)*10);//添加移动的力,因为不上下移动,所以y轴为0
setcount();
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag =="pickup")
{
Destroy(other.gameObject);
Score++;
}
}
}
然后把辣个player里面的(语无伦次描述不清楚就直接放图了。゜(`Д´)゜。,就是把那个count后面选择Text)
然后就会吃到一个食物就加一分辣!
最吼加了一段当Score==10时(因为我设置了10个食物),就显示“WIN!”的代码,就懒得再贴一次了,然后终于做完我人生中第一个游戏了qwq