VRTK射線檢測


VRTK射線檢測回調事件

本人在工作中做VR隱患排查項目開發的時候,有個功能需要做到:按下手柄觸摸板發送射線,松開觸摸板的時候處理射線最后檢測到的那個游戲物體。

功能構思:1、按下觸摸板,從手柄上發射射線;

       2、當射線停留在某個游戲物體上時,將此游戲物體添加到List列表中;

       3、當射線移開此物體,停留在下一個游戲物體時,移除List列表中剛剛檢測到的游戲物體(由於射線是一直檢測的,所以當你不停的移動射線時,會不停的添加和移除射線檢測到的游戲物體);

       4、當射線停留在你想處理的某游戲物體上時(此時游戲物體添加到List列表中),松開觸摸板,此時可以對此游戲物體進行一系列邏輯處理;

       5、邏輯處理完成后,會執行移除List列表中的游戲物體,以便於下次使用射線檢測。    

獲取射線碰撞到的某個物體這一類功能。可以通過VRTK里面的事件回調獲取。

想使用VRTK射線檢測,首先需要打開unity,導入SteamVR SDK和VRTK插件,在此不做演示。

在VRTK的腳本中,有VRTK_ControllerPointerEvents_ListenerExample和VRTK_DestinationMarker兩個腳本。

下面貼上本人代碼以供參考:

 

public class Test()
{
  private VRTK_Pointer rightHandPointer;//右手柄Pointer組件
  private List<GameObject> lists = new List<GameObject>();//創建列表
  
  void Start()
  {
    rightHandPointer=VRTK_DeviceFinder.GetControllerRightHand().GetComponent<VRTK_Pointer>();//獲取右手柄的VRTK_Pointer組件
    
    //rightHandPointer.GetComponent<VRTK_DestinationMarker>().DestinationMarkerEnter+= Test_DestinationMarkerEnter;//當射線進入的時候
    
    rightHandPointer.GetComponent<VRTK_DestinationMarker>().DestinationMarkerExit += Test_DestinationMarkerExit;//當射線離開的時候
    
    rightHandPointer.GetComponent<VRTK_DestinationMarker>().DestinationMarkerHover += Test_DestinationMarkerHover;//當射線停留的時候
    
    //rightHandPointer.GetComponent<VRTK_DestinationMarker>().DestinationMarkerSet+= Test_DestinationMarkerSet;//當目標標記在場景中活動時發出,以確定最后的目的地位置(用於選擇和傳送)
  }

  //處理 射線停留在游戲物體上
  private void Test_DestinationMarkerHover(object sender, DestinationMarkerEventArgs e)
  {
    if (e.target != null)
      //當射線檢測到游戲物體時,添加到列表中
      lists.Add(e.target.gameObject);
      Debug.Log("獲取射線檢測到的游戲物體的名字:"+e.target.name);
  }

  //處理 射線移開游戲物體時
  private void Test_DestinationMarkerExit(object sender, DestinationMarkerEventArgs e)
  {
    //這段話意思是:當SelectionButton不再按下的時候,表示選中此游戲物體
    if (!rightHandPointer.IsSelectionButtonPressed())
    {
      //處理選中的游戲物體
      Debug.Log("獲取射線檢測到的游戲物體的名字:"+e.target.name);
    }
    //當射線離開游戲物體時,移出列表
    lists.Remove(e.target.gameObject);
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM