开发引擎:Unity3d
设备:Htc Vive
Htc Vive Sdk(OpenVR),Unity3d 开发,Hello World
Htc Vive Sdk(OpenVR),Unity3d 开发,手柄射线
Htc Vive Sdk(OpenVR),Unity3d 开发,UGUI界面响应
Htc Vive Sdk(OpenVR),Unity3d 开发,UGUI响应代码分析篇
原理:
在VR 3D的虚拟空间里,使用htc vive的手柄指向的射线来操作3D空间的UI,只能使用碰撞。
unity3d提供Physics.Raycast来实现射线碰撞,这个函数需要一个其实位置,一个方向,然后输出碰撞的物
体。
我们根据输出碰撞的物体来作为移入这个物体的响应事件,或者我们检测到了未碰撞了来模拟作为移除的响应事件。
根据以上的操作,需要两个代码文件,raycast.cs和handleray.cs。
raycast.cs:通过射线碰撞获取到碰撞的对象,如 文章 讲到的射线射向Cube或者UGUI的Button;
handleray.cs:处理射线碰撞或者不发生碰撞后的操作;
raycast.cs
public class raycast : MonoBehaviour
{
public Transform startPoint;
public Transform endRefPoint;
public LineRenderer line;
private IHandleRay handle;
private RaycastHit rayhit;
void FixedUpdate()
{
bool bEraseRayCast = true;
Physics.Raycast(startPoint.position, endRefPoint.position - startPoint.position, out rayhit);
if (rayhit.transform)
{
IHandleRay handleCur = (IHandleRay)rayhit.collider.GetComponent<IHandleRay>();
if (handleCur != null)
{
if (handle == null || handle != handleCur)
{
handleCur.MoveEnter(rayhit.point);
handle = handleCur;
}
bEraseRayCast = false;
}
line.SetPosition(1, new Vector3(0, 0, System.Math.Abs((rayhit.point - startPoint.transform.position).z)));
}
if (bEraseRayCast)
{
if (handle != null)
{
handle.MoveLeave();
handle = null;
}
line.SetPosition(1, new Vector3(0, 0, 10.0f));
}
}
}
事件响应接口:
ihandleray.cs
public interface IHandleRay
{
void MoveEnter(Vector3 point);
void MoveLeave();
}
最简单的处理:
handleray .cs
public class handleray : MonoBehaviour, IHandleRay
{
public void MoveEnter(Vector3 point)
{
Debug.Log("move enter cube raycast point:" +
point.x + "-" +
point.y + "-" +
point.z);
}
public void MoveLeave()
{
Debug.Log("move leave cube ");
}
}