AimReticle.cs 2.4 KB

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