天天看點

unity VR 技術之凝視

直接上代碼

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class RayCtro : MonoBehaviour {
	
	float currTime=0f; //目前時間
	float CoutTime=3f;	//計時,3秒後做 完成凝視	
	public UIctro btnCtro; //挂在在UI上的腳本 
	GameObject oldObj;   //記錄 凝視進入的物體
	// Use this for initialization
	void Start () 
	{
	
	}
	
	// Update is called once per frame
	void Update () 
	{
		Ray camRay = new Ray (transform.position, transform.forward);//建立一條射線	
		RaycastHit Hit;
		if (Physics.Raycast (camRay, out Hit, 4000f)) //這裡直接發出射線,進行檢查,當然也可以使用laymask層	
		{
			
			if (Hit.transform.CompareTag ("GazeUI"))  //如果凝視到的是UI
			{
				
				
				if (Hit.transform.gameObject != oldObj) 
				{
					Restart ();
				}
				currTime += Time.deltaTime;
				oldObj = Hit.transform.gameObject;
				oldObj.GetComponent<Image> ().fillAmount = currTime / CoutTime;
				if (currTime - CoutTime > 0) 
				{
					btnCtro.isAllshow= false;
					if (Hit.transform.name == "Image1")	//如果UI下的名字為 就調用物體下的函數
					{		
						oldObj.GetComponent<GazeEvent> ().showIntro1 ();
					}

					if (Hit.transform.name == "Image2")
					{
						oldObj.GetComponent<GazeEvent> ().showIntro2 ();
					}

					if (Hit.transform.name == "Image3")
					{
						oldObj.GetComponent<GazeEvent> ().showIntro3 ();
					}
					
				}


			} 

			else 	//視線移出 初始化
			{
				Restart ();
			}

		} 
		else 		//初始化
		{
			Restart ();
		}
	
	}
	void Restart()
	{
			//初始化函數 判斷物體是否為null 使其歸空
		if (oldObj != null) 
		{
			oldObj.GetComponent<Image> ().fillAmount = 0;
			oldObj = null;
		}

			currTime = 0f;


	}
}