限制物体在某个轴上,一定范围内移动
速度太快的话,一样会穿透过去。
上图,中间是个可移动的模型,两边Cube限制点:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CarTrigger : MonoBehaviour {
public GameObject Point1;//限制点1
public GameObject Point2;//限制点2
public float carSpeed = 6f;//移动速度
public bool isTrigger = false;//是否是触发状态
void Update () {
float v = Input.GetAxis("Vertical");//垂直向量的输入
if (isTrigger==false)//如果不是触发状态
{
//用户按下了W或者S
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S))
{
//模型移动
float smooth = v * carSpeed * Time.deltaTime;
transform.Translate(0, 0, smooth);//往哪个轴的,我这里是z轴的方向
}
}
else//是触发状态下
{
isTrigger = true;
}
}
//触发器触发中的事件
public void OnTriggerStay(Collider other)
{
Debug.Log("OntriggerStay:是" + other.gameObject.name);
//如果触发对象的名字是Point并且按下了W键,,,(怎么判断什么键位自己决定,这里方向就要相反了,不然就不对了)
if (other.gameObject.name == "Point1" &&Input.GetKey(KeyCode.W))
{
isTrigger = false;//触发中的时候,要切换到非触发状态(Update会自动执行非触发状态的条件语句)
//float carSpeed = 2;//重新赋予速度
float smooth = Input.GetAxis("Horizontal") * carSpeed * Time.deltaTime;
transform.Translate(0, 0, smooth);
}
//跟上面差不多
if (other.gameObject.name == "Point2" && Input.GetKey(KeyCode.S))
{
isTrigger = false;
//float carSpeed = 2;
float smooth = Input.GetAxis("Horizontal") * carSpeed * Time.deltaTime;
transform.Translate(0, 0, smooth);
}
}
//触发器刚触发产生的事件
public void OnTriggerEnter(Collider other)
{
Debug.Log("OnTriggerEnter:是" + other.gameObject.name);
if(other.gameObject.name == "Point1"||other.gameObject.name == "Point2")
{
isTrigger = true;//这句就是限制移动的重点
float carSpeed = 0;//速度为0,(Update 执行触发状态的语句)
float smooth = Input.GetAxis("Horizontal") * carSpeed * Time.deltaTime;
transform.Translate(0, 0, smooth);
}
}
}