快速开发实用工具VRTK-006

006_Controller_UsingADoor

打开门

在左右手柄上挂载,VRTK_ControllerEvents、VRTK_Interact Touch、VRTK_Interact Grab和VRTK_Interact Use。如下图所示:

然后在门上挂载脚本Openable_Door,继承自VRTK_Interactable Object。在抓取的四个脚本添加之后,又添加了VRTK_Interact Use(按下控制器上默认的扳机键来使用一个对象,释放该按钮停止使用该对象)。
在与可交互对象产生交互时,对象上往往需要一个脚本组件,该组件既可以使VRTK_InteractableObject,也可以是继承于该类的子类。Openable_Door就是VRTK_InteractableObject的子类。

 

namespace VRTK.Examples
{
    using UnityEngine;
    //

    public class Openable_Door : VRTK_InteractableObject
    {
        //控制打开门的方向
        public bool flipped = false;
        public bool rotated = false;

        private float sideFlip = -1;
        private float side = -1;
        private float smooth = 270.0f;
        private float doorOpenAngle = -90f;
        private bool open = false;
        /// <summary>
        /// 关闭状态下的旋转(0,0,0)
        /// </summary>
        private Vector3 defaultRotation;
        /// <summary>
        /// 保存打开状态下的旋转
        /// </summary>
        private Vector3 openRotation;
        /// <summary>
        /// 当打开门触发时,执行的回调函数
        /// </summary>
        /// <param name="usingObject"></param>
        public override void StartUsing(VRTK_InteractUse usingObject)
        {
            base.StartUsing(usingObject);
            SetDoorRotation(usingObject.transform.position);
            SetRotation();
            open = !open;
        }

        protected void Start()
        {
            //初始状态下门的旋转(0,0,0)
            defaultRotation = transform.eulerAngles;
            SetRotation();
            sideFlip = (flipped ? 1 : -1);
        }

        protected override void Update()
        {
            base.Update();
            if (open)
            {
                transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(openRotation), Time.deltaTime * smooth);
            }
            else
            {
                transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(defaultRotation), Time.deltaTime * smooth);
            }
        }
        /// <summary>
        /// 计算打开门的旋转角度
        /// </summary>
        private void SetRotation()
        {
            openRotation = new Vector3(defaultRotation.x, defaultRotation.y + (doorOpenAngle * (sideFlip * side)), defaultRotation.z);
        }
        /// <summary>
        /// 控制门的打开方向
        /// </summary>
        /// <param name="interacterPosition"></param>
        private void SetDoorRotation(Vector3 interacterPosition)
        {
            side = ((rotated == false && interacterPosition.z > transform.position.z) || (rotated == true && interacterPosition.x > transform.position.x) ? -1 : 1);
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章