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);
}
}
}