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

 

posted @ 2019-05-15 14:17  挽风入我怀  阅读(2079)  评论(0编辑  收藏  举报