close
using UnityEngine;
using System.Collections;
public class EventMgr : MonoBehaviour {
RaycastHit2D hit2D;
Ray2D ray2D;
bool press = false; //是否按著
void Update () {
// 判斷是否為 android 裝置
#if UNITY_ANDROID
if (Input.touchCount > 0 && Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position), Vector2.zero))
{
hit2D = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position), Vector2.zero);
#else
if (Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero))
{
hit2D = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
#endif
if(hit2D.collider.gameObject.GetComponent<EventListener>())
{
GameObject tempObj = hit2D.collider.gameObject;
EventListener tempListener = tempObj.GetComponent<EventListener>(); // 取得EventListener <- 委派須自己實作Script
if(tempListener.onHover != null)
tempObj.SendMessage("OnHover", true);
#if UNITY_ANDROID
if(Input.GetTouch(0).phase == TouchPhase.Began)
#else
if(Input.GetMouseButtonDown(0))
#endif
{
press = true;
if(tempListener.onPress != null)
tempObj.SendMessage("OnPress", press);
}
#if UNITY_ANDROID
if(Input.GetTouch(0).phase == TouchPhase.Ended)
#else
if(Input.GetMouseButtonUp(0))
#endif
{
if(press)
{
press = false;
if(tempListener.onClick != null)
tempObj.SendMessage("OnClick");
if(tempListener.onPress != null)
tempObj.SendMessage("OnPress", press);
}
}
}
}
}
}
這篇是參考網路上一些3D範例製作
這次小編提供Unity2D元件下的偵測碰撞範例且增加行動裝置的判斷
至於如何動態增加某 GameObject 的事件委派註冊可以參考其他網路上的做法(如果示範例覺得差異性不太,就不再OP了,自行Google)
我目前在網路上找不太到最佳參數傳遞方式,畢竟自己想傳遞的參數不一定個數和型態
如果有研究出還不錯的方法我會再OP一篇新文章
歡迎光臨 ~ Eg 程式筆記的天堂
當你看完此篇文章,如果你覺得文章不錯
可以留下鼓勵的留言~
將是我的撰寫更多相關文章的動力
文章標籤
全站熱搜
留言列表