using System.Collections.Generic;
using TouchScript;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class PlayerHit : MonoBehaviour
{
// 用于射线检测的的摄像头
public Camera RayCamera;
List list;
private void OnEnable()
{
if (TouchManager.Instance != null)
TouchManager.Instance.PointersUpdated += pointersUpdatedHandler;
list = new List();
}
private void OnDisable()
{
if (TouchManager.Instance != null)
TouchManager.Instance.PointersUpdated -= pointersUpdatedHandler;
}
void Start()
{
// 获取用于射线检测的的摄像头
if (RayCamera == null)
RayCamera = GameObject.FindGameObjectWithTag("RayCamera").GetComponent();
}
// 3D射线检测
void RayHit3DFunction(Vector2 pos)
{
UnityEngine.Ray ray = RayCamera.ScreenPointToRay(pos);
RaycastHit[] hits = Physics.RaycastAll(ray);
if (hits.Length > 0)
{
foreach (var item in hits)
{
GameObject colObj = item.collider.gameObject;
print(item.collider.gameObject.name);
//if (colObj.CompareTag("3D") && colObj.activeSelf)
//{
//}
}
}
}
//2D UGUI 射线检测
void RayHit2DFunction(Vector2 pos)
{
list = GraphicRaycaster(pos);
foreach (var item in list)
{
GameObject colObj = item.gameObject;
print(item.gameObject.name);
//if (colObj.CompareTag("2D") && colObj.activeSelf)
//{
//}
}
}
public EventSystem _mEventSystem;
public GraphicRaycaster gra;
private List GraphicRaycaster(Vector2 pos)
{
var mPointerEventData = new PointerEventData(_mEventSystem);
mPointerEventData.position = pos;
List results = new List();
gra.Raycast(mPointerEventData, results);
return results;
}
///
/// 鼠标点击事件
///
///
///
private void pointersUpdatedHandler(object sender, PointerEventArgs e)
{
foreach (var pointer in e.Pointers)
{
//Debug.Log(pointer.Id + " touched down at " + pointer.Position);
//RayHit3DFunction(pointer.Position);
RayHit2DFunction(pointer.Position);
}
}
}