AimReticle.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. /// <summary>
  5. /// Reticle control for when the aiming is inaccurate. Inaccuracy is shown by pulling apart the aim reticle.
  6. /// </summary>
  7. public class AimReticle : MonoBehaviour
  8. {
  9. [Tooltip("Maximum radius of the aim reticle, when aiming is inaccurate. ")]
  10. [Range(0, 100f)]
  11. public float MaxRadius;
  12. [Tooltip("The time is takes for the aim reticle to adjust, when inaccurate.")]
  13. [Range(0, 1f)]
  14. public float BlendTime;
  15. [Tooltip("Top piece of the aim reticle.")]
  16. public Image Top;
  17. [Tooltip("Bottom piece of the aim reticle.")]
  18. public Image Bottom;
  19. [Tooltip("Left piece of the aim reticle.")]
  20. public Image Left;
  21. [Tooltip("Right piece of the aim reticle.")]
  22. public Image Right;
  23. [Tooltip("This 2D object will be positioned in the game view over the raycast hit point, if any, "
  24. + "or will remain in the center of the screen if no hit point is detected. "
  25. + "May be null, in which case no on-screen indicator will appear. Same as Cinemachine3rdPersonAim's")]
  26. public RectTransform AimTargetReticle;
  27. void Reset()
  28. {
  29. MaxRadius = 30f;
  30. BlendTime = 0.05f;
  31. }
  32. float m_BlendVelocity;
  33. float m_CurrentRadius;
  34. void Update()
  35. {
  36. var screenCenterPoint = new Vector2(Screen.width * 0.5f, Screen.height * 0.5f);
  37. float distanceFromCenter = 0;
  38. if (AimTargetReticle != null)
  39. {
  40. var hitPoint = (Vector2) AimTargetReticle.position;
  41. distanceFromCenter = (screenCenterPoint - hitPoint).magnitude;
  42. }
  43. m_CurrentRadius = Mathf.SmoothDamp(m_CurrentRadius, distanceFromCenter * 2f, ref m_BlendVelocity, BlendTime);
  44. m_CurrentRadius = Mathf.Min(MaxRadius, m_CurrentRadius);
  45. Left.rectTransform.position = screenCenterPoint + (Vector2.left * m_CurrentRadius);
  46. Right.rectTransform.position = screenCenterPoint + (Vector2.right * m_CurrentRadius);
  47. Top.rectTransform.position = screenCenterPoint + (Vector2.up * m_CurrentRadius);
  48. Bottom.rectTransform.position = screenCenterPoint + (Vector2.down * m_CurrentRadius);
  49. }
  50. }