關於VRTK射線檢測回調事件

關於VRTK射線檢測回調事件

在做VR項目開發的時候,我們可能會用到從手柄上發射射線,然後獲取射線碰撞到的那個物體這一類功能。在射線碰撞到物體那一刻,我們想獲取到這個物體,可以通過VRTK裏面的事件回調獲取。在這裏,我進行一些演示:


首先打開unity,導入SteamVR SDK和VRTK 包,然後選擇一個VRTK的案例Scene選擇一個場景

在這裏我選擇了一個通過射線瞬移的案例
然後通過搜索找到VRTK_ControllerPointerEvents_ListenerExample,賦給任意一個手柄,然後打開腳本
添加腳本
打開腳本,可以找到以下方法:

  private void DoPointerIn(object sender, DestinationMarkerEventArgs e)//射線進入
        {
            DebugLogger(VRTK_ControllerReference.GetRealIndex(e.controllerReference), "POINTER IN", e.target, e.raycastHit, e.distance, e.destinationPosition);
        }

        private void DoPointerOut(object sender, DestinationMarkerEventArgs e)射線退出
        {
            DebugLogger(VRTK_ControllerReference.GetRealIndex(e.controllerReference), "POINTER OUT", e.target, e.raycastHit, e.distance, e.destinationPosition);
        }

        private void DoPointerHover(object sender, DestinationMarkerEventArgs e)射線停留
        {
            DebugLogger(VRTK_ControllerReference.GetRealIndex(e.controllerReference), "POINTER HOVER", e.target, e.raycastHit, e.distance, e.destinationPosition);
        }

        private void DoPointerDestinationSet(object sender, DestinationMarkerEventArgs e)//當目標標記在場景中活動時發出,以確定最後的目的地位置(用於選擇和傳送)
        {
            DebugLogger(VRTK_ControllerReference.GetRealIndex(e.controllerReference), "POINTER DESTINATION", e.target, e.raycastHit, e.distance, e.destinationPosition);
        }

在上面的代碼中,e便是射線碰到返回的物體信息,我們可以通過以下方式獲取:
private void DoPointerIn(object sender, DestinationMarkerEventArgs e)
{
print("獲取物體的名字:" + e.target.name);
}

之後便會打印出相應的名字,當然我們也可以另外新建一個腳本,專門來處理這個回調,下面是腳本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using VRTK;
public class Test : MonoBehaviour {
void Start () {
GetComponent<VRTK_DestinationMarker>().DestinationMarkerEnter += new DestinationMarkerEventHandler(DoPointerIn);
GetComponent<VRTK_DestinationMarker>().DestinationMarkerHover += new DestinationMarkerEventHandler(DoPointerHover);
GetComponent<VRTK_DestinationMarker>().DestinationMarkerExit += new DestinationMarkerEventHandler(DoPointerOut);
GetComponent<VRTK_DestinationMarker>().DestinationMarkerSet += new DestinationMarkerEventHandler(DoPointerDestinationSet);
    }

    // Update is called once per frame
    void Update () {

    }
    private void DoPointerIn(object sender, DestinationMarkerEventArgs e)
    {
        print("進入時獲取物體的名字:" + e.target.name);

    }

    private void DoPointerOut(object sender, DestinationMarkerEventArgs e)
    {
        print("退出時獲取物體的名字:" + e.target.name);
    }

    private void DoPointerHover(object sender, DestinationMarkerEventArgs e)
    {
        print("停留時獲取物體的名字:" + e.target.name);
    }

    private void DoPointerDestinationSet(object sender, DestinationMarkerEventArgs e)
    {
        print("最終目標點的名字:" + e.target.name);
    }
}

當然後面這些要註冊的方法也可以自己寫,只要是符合格式即可。

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