ScreenCameraRay.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.EventSystems;
  5. public class ScreenCameraRay : MonoBehaviour
  6. {
  7. // Start is called before the first frame update
  8. void Start()
  9. {
  10. }
  11. /// <summary>
  12. /// 输入设备上一次检测到的目标物体
  13. /// </summary>
  14. protected GameObject target;
  15. // Update is called once per frame
  16. void Update()
  17. {
  18. if (Input.GetMouseButtonDown(0))
  19. {
  20. //Debug.Log("点击屏幕");
  21. CheckRay(Input.mousePosition, TouchPhase.Began);
  22. }
  23. else if(Input.GetMouseButtonUp(0))
  24. {
  25. CheckRay(Input.mousePosition, TouchPhase.Ended);
  26. }
  27. else if (Input.touchCount == 1)
  28. {
  29. if (Input.GetTouch(0).phase == TouchPhase.Began)
  30. {
  31. CheckRay(Input.GetTouch(0).position, TouchPhase.Began);
  32. }
  33. else if (Input.GetTouch(0).phase == TouchPhase.Ended)
  34. {
  35. CheckRay(Input.GetTouch(0).position, TouchPhase.Ended);
  36. }
  37. }
  38. else
  39. {
  40. CheckRay(Input.mousePosition, TouchPhase.Canceled);
  41. }
  42. }
  43. private void CheckRay(Vector3 point, TouchPhase mode)
  44. {
  45. RaycastHit hit;
  46. Ray ray = Camera.main.ScreenPointToRay(point);
  47. if (Physics.Raycast(ray, out hit))
  48. {
  49. if(!hit.transform.gameObject.Equals(target))
  50. {
  51. ExecuteEvents.Execute<IPointerExitHandler>(target, null, (x, y) => x.OnPointerExit(null));
  52. }
  53. target = hit.transform.gameObject;
  54. //CDebug.Log(hit.transform.name);
  55. //Debug.Log(hit.transform.tag);
  56. if(mode == TouchPhase.Began)
  57. {
  58. ExecuteEvents.Execute<IPointerDownHandler>(hit.transform.gameObject, null, (x, y) => x.OnPointerDown(null));
  59. ExecuteEvents.Execute<IPointerClickHandler>(hit.transform.gameObject, null, (x, y) => x.OnPointerClick(null));
  60. }
  61. else if (mode == TouchPhase.Ended)
  62. {
  63. ExecuteEvents.Execute<IPointerUpHandler>(hit.transform.gameObject, null, (x, y) => x.OnPointerUp(null));
  64. }
  65. }
  66. }
  67. }