1、Unity 的IDragHandler、IPointerDownHandler、IPointerUpHandler
namespace UnityEngine.EventSystems
{
public interface IDragHandler : IEventSystemHandler
{
void OnDrag(PointerEventData eventData);
}
}
namespace UnityEngine.EventSystems
{
public interface IPointerUpHandler : IEventSystemHandler
{
void OnPointerUp(PointerEventData eventData);
}
}
namespace UnityEngine.EventSystems
{
public interface IPointerDownHandler : IEventSystemHandler
{
void OnPointerDown(PointerEventData eventData);
}
}
2、计算点击位置
using UnityEngine;
using UnityEngine.EventSystems;
public class GameBoard : MonoBehaviour/*UIBehaviour*/, IPointerDownHandler, IPointerUpHandler, IDragHandler
{
public RectTransform touchLayerTrans;
public virtual void OnPointerDown(PointerEventData eventData)
{
var touchPosition = GetCurrentHitPosition(eventData);
Debug.Log("Point down " + touchPosition);
}
public virtual void OnPointerUp(PointerEventData eventData)
{
var touchPosition = GetCurrentHitPosition(eventData);
Debug.Log("Point up " + touchPosition);
}
public virtual void OnDrag(PointerEventData eventData)
{
var touchPosition = GetCurrentHitPosition(eventData);
Debug.Log("OnDrag " + touchPosition);
}
public Vector3 GetCurrentHitPosition(PointerEventData eventData)
{
var wordPosition = Camera.main.ScreenToWorldPoint(eventData.position);
var localPosition = touchLayerTrans.InverseTransformPoint(wordPosition);
return localPosition;
}
}
3、添加UI中的EventSystem
4、Canvas、Graphic Raycaster (射线检测),添加Image或者Mesh 确保能点击