Htc Vive Sdk(OpenVR),Unity3d 開發,UGUI響應代碼分析篇

開發引擎: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 ");
}

}

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