<p>
完成VR中的物体交互动作,包括射线移入和移出物体,单击和双击物体时实现对应的功能。(使用SDK为VR_Sample中的VRStandardAssets.Utils,这里主要用到了:VRIput,VREyeRaycaster,Reticle,VRInteractiveItem这几个类)
</p>
一、实现功能
- 射线移入到交互物体时变色,移出恢复原来颜色;
- 移入物体时,单击物体改变颜色,双击物体改变成另外一种颜色;
二、步骤
首先新建Scene,命名为InterActive,保存在Scenes文件夹内。
1.建立准心,用来显示射线的碰撞位置。
准心为一个UI元素,始终和摄像机保持一定的距离,所以把UI作为摄像机的一个子对象来实现,同时把Canvas的render mode设置为space world,其余组件属性如下图:

另外,UI是不需要进行交互的,所以把下图的组件Graphic Raycaster移除:

完成Canvas后,新建准心的Image,属性设置如下图:

2.Camera的脚本关联
完成准心的设置后,进行Camera的设置,将VRIput,VREyeRaycaster,Reticle三个脚本关联上并设置好相应字段的初值,如下图:



3.交互物体设置
- 点击、移入和移出设置
首先先新建Materials对应移入移出,点击时的颜色:

完成后,通过代码订阅相应的事件,新建InterItem脚本:
[SerializeField]//这个修饰标示可以在检视栏中显示
private VRInteractiveItem m_VRInteractiveItem; //声明注册事件的对象
[SerializeField]
Renderer m_Render; //声明Renderer组件
[SerializeField]
private Material m_Normal; //声明Renderer组件,以便做材质颜色的动态变更
[SerializeField]
private Material m_Click; //单击的Material
[SerializeField]
private Material m_DoubleClick; //双击的Material
[SerializeField]
private Material m_Over; //移入时的Material
//向m_VRInteractiveItem中订阅相应的事件
private void OnEnable()
{
m_VRInteractiveItem.OnOver += Over;
m_VRInteractiveItem.OnOut += Out;
m_VRInteractiveItem.OnClick += Click;
m_VRInteractiveItem.OnDoubleClick += DoubleClick;
}
//移入时,Material的相应改变
void Over()
{
m_Render.material = m_Over;
}
//移出时,Material的相应改变
void Out()
{
m_Render.material = m_Normal;
}
//单击时,Material的相应改变
void Click()
{
m_Render.material = m_Click;
}
//双击时,Material的相应改变
void DoubleClick()
{
m_Render.material = m_DoubleClick;
}
然后把InterItem和VRInteractiveItem脚本添加到Cube上,并做好相应的赋值:

运行当准心移入时Cube改变颜色:

单击时,改变颜色:

双击时,改变颜色:

移出时,恢复原来颜色:

三、注意事项
射线和物体交互中主要用到了SDK中的VRIput,VREyeRaycaster,Reticle,VRInteractiveItem几个脚本,其中使用到了大量的事件订阅功能,下面通过Cube的Over事件和Click事件的触发过程来理解:
- Click事件的触发:
VRIput中声明Click事件:

在VREyeRaycaster对Click事件进行订阅,订阅的方法是执行交互物体中的Click事件,


最后,在每个交互物体上可以定义具体的点击方法并且订阅VRInteractiveItem中的Click事件,如该例子中的Click方法:


- Over事件的触发:
当射线打到了一个VRInteractiveItem物体时,就会调用当前可交互物体的Over方法:

也就是调用了VRInteractiveItem中的Over方法

然后在InterItem脚本中订阅了OnOver事件:

所以,调用的事件为InterItem脚本中的Over方法,Cube改变了颜色:

网友评论