GameCrossHair.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using ZIM;
  5. public class GameCrossHair : MonoBehaviour
  6. {
  7. GameController gameController;
  8. [SerializeField] ScreenLocate screenLocate;
  9. RectTransform myRTF;
  10. Vector2 targetPos;
  11. [SerializeField] int infraredSpotsIndex;
  12. Vector3? _lastPosition;
  13. void Start()
  14. {
  15. gameController = GetComponentInParent<GameController>();
  16. myRTF = transform as RectTransform;
  17. screenLocate = FindAnyObjectByType<ScreenLocate>();
  18. }
  19. void Update()
  20. {
  21. _lastPosition = myRTF.position;
  22. if (screenLocate)
  23. {
  24. Vector2? locateResult = null;
  25. InfraredSpot[] InfraredSpots = screenLocate.InfraredSpots;
  26. if (InfraredSpots != null && infraredSpotsIndex < InfraredSpots.Length && InfraredSpots[infraredSpotsIndex].ScreenUV != null)
  27. {
  28. Vector2 v2 = InfraredSpots[infraredSpotsIndex].ScreenUV.Value;
  29. if (v2.x > 0 && v2.y > 0 && v2.x < 1 && v2.y < 1)
  30. {
  31. locateResult = v2;
  32. }
  33. }
  34. gameObject.GetComponent<UnityEngine.UI.Image>().enabled
  35. = locateResult != null && gameController.crossHairIsOn;
  36. if (locateResult == null)
  37. {
  38. _lastPosition = null;
  39. return;
  40. }
  41. Vector2 np = ((Vector2)locateResult).pixelToLocalPosition_AnchorCenter(Vector2.one, (transform.parent as RectTransform).rect);
  42. if (Vector2.Distance(np, targetPos) >= 3)
  43. {
  44. targetPos = np;
  45. //插值移动
  46. //myRTF.anchoredPosition = Vector2.Lerp(myRTF.anchoredPosition, targetPos, Time.deltaTime * 15);
  47. myRTF.anchoredPosition = targetPos;
  48. }
  49. }
  50. else
  51. {
  52. gameObject.GetComponent<UnityEngine.UI.Image>().enabled = gameController.crossHairIsOn;
  53. if (Input.GetMouseButtonDown(infraredSpotsIndex))
  54. {
  55. transform.position = Input.mousePosition;
  56. }
  57. }
  58. if (gameController.gameNode.activeSelf == false) return;
  59. Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, (transform as RectTransform).rect.width / 2);
  60. foreach (var item in colliders) item.GetComponent<Box>()?.Bomb();
  61. if (_lastPosition != null)
  62. {
  63. Vector3 lp = (Vector3)_lastPosition;
  64. float displace = Vector3.Distance(lp, myRTF.position);
  65. if (displace > 0.1)
  66. {
  67. Vector3 pointer = myRTF.position - lp;
  68. RaycastHit2D[] raycastHit2Ds = Physics2D.CircleCastAll(lp, (transform as RectTransform).rect.width / 2, pointer, displace);
  69. foreach (var item in raycastHit2Ds) item.transform.GetComponent<Box>()?.Bomb();
  70. }
  71. }
  72. }
  73. }