您的位置:首页 > 其它

限制物体在一定区域内移动(修改BUG版)

2018-02-05 17:31 375 查看
前两天写过一篇这样的文章,最后发现有一点小小的BUG(这个BUG很隐蔽的,特殊操作下,会穿过限制点),这里从新修改一下,

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class CarTrigger : MonoBehaviour {

    public GameObject Point1;//限制点1

    public GameObject Point2;//限制点2

    public float carSpeed = 2f;//移动速度

    public bool WTrigger = false;//是否是触发状态

    public bool STrigger = false;

    void Update () {

        float v = Input.GetAxis("Vertical");//垂直向量的输入

        if (WTrigger == false&&Input.GetKey(KeyCode.W))//如果不是触发状态

        {

                //模型移动

                float smooth = v * carSpeed * Time.deltaTime;

                transform.Translate(0, 0, smooth);//往哪个轴的,我这里是z轴的方向

        }

        if (STrigger == false && Input.GetKey(KeyCode.S))//如果不是触发状态

        {

            //模型移动

            float smooth = v * carSpeed * Time.deltaTime;

            transform.Translate(0, 0, smooth);//往哪个轴的,我这里是z轴的方向

        }

    }

    //触发器离开的事件

    public void OnTriggerExit(Collider other)

    {

        if (Input.GetKey(KeyCode.W)) { STrigger = false; }

        if (Input.GetKey(KeyCode.S)) { WTrigger = false; }

    }

    //触发器刚触发产生的事件

    public void OnTriggerEnter(Collider other)

    {

        if (other.gameObject.name == "Point1") { STrigger = true; }

        if (other.gameObject.name == "Point2") { WTrigger = true; }

    }
}

这里就解决了特殊操作下,穿过限制点的BUG了。希望对有需要的人有帮助!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: