1. 程式人生 > >NGUI 滑鼠停留UI上時緩慢顯示子Item,當無停留超過一定時間後回到原地

NGUI 滑鼠停留UI上時緩慢顯示子Item,當無停留超過一定時間後回到原地

長話短說,程式碼很短(百行),開始效果如圖:

    當滑鼠停留在藍色的按鈕上時,上面NGUI的幾個Item緩慢出現,當滑鼠離開一段時間後且沒有繼續停留在按鈕和Item上的時候,自動緩慢回到原位。如下圖:

UI的擺放如下圖:

下面是 程式碼類1,OnHoverTween.cs 掛在藍色按鈕上,主要控制 Item 返回原位和計時。

using UnityEngine;
using System.Collections;

public class OnHoverTween : MonoBehaviour
{
	public GameObject target;
	// 初始位置和顯示位置和前面的類一致
	public Vector3 posStart;
	public Vector3 posDisplay;
	// Use this for initialization
	void Start () {}
	
	// Update is called once per frame
	void Update()
	{
		if(!Globe.IsHovered)
		{
			if(Globe.isRun)
			{
				Globe.RunTime -= Time.deltaTime;
				if(Globe.RunTime <= 0)
				{
					GoBack();
				}
			}
		}
		else
		{
			Globe.RunTime = 3.0f;
		}
	}

	void GoBack()
	{
		// 停止計時
		Globe.isRun = false;
		if(Globe.playForm)
		{
			Globe.playTo = true;
			Globe.playForm = false;
			TweenPosition position = TweenPosition.Begin(target, 0.75f, posStart);
		}
	}
}
//程式碼類3, 全域性變數。
using System.Collections.Generic;
using UnityEngine;
public class Globe
{   
	// Used in OnHoverDisplay Class
	public static float RunTime = 3.0f;
	public static bool IsHovered = false;
	public static bool isRun = false;
	public static bool playTo = true;
	public static bool playForm = false;
}


程式碼類2,主要判斷是否停留在按鈕盒 Item 上,掛在藍色按鈕和 所有 Item 上。每個按鈕盒 Item 的 State 用來區別不同的 Item 。


//Target 的物件為 Item 的父節點。開始位置和結束位置,手動設定

using UnityEngine;
using System.Collections;

public enum OnhoverButtonState
{
	PlayAnimation,
	Ce,
	Le,
	Se,
	Ie,
	Re
}
public class OnHoverDisplay : MonoBehaviour {
	public OnhoverButtonState state;
	public GameObject target;
	// 初始位置和顯示位置
	public Vector3 posStart;
	public Vector3 posDisplay;
	// Use this for initialization
	void Start(){}	
	// Update is called once per frame
	void Update(){}

	void OnClick()
	{
		if(enabled)
		{
			// 根據不同的按鈕,選擇不同的點選事件
			if(state == OnhoverButtonState.Se)
			{
				// 這裡寫上你要點選按鈕後想要做的事情
				//DoSomeThing();
			}
		}
	}

	void OnHover(bool isOver)
	{
		if(enabled)
		{
			if(isOver)
			{
				// 告訴 Update 函式,觸發了停留事件
				Globe.IsHovered = true;
				GoDisplay();
			}
			else
			{
				Globe.IsHovered = false;
				// 通知可以開始計時
				Globe.isRun = true;
			}
		}
	}
	// 控制按鈕面板出現
	void GoDisplay()
	{
		if(Globe.playTo)
		{
			Globe.playTo = false;
			Globe.playForm = true;			
			TweenPosition position = TweenPosition.Begin(target, 0.75f, posDisplay);
		}
	}
}