LoseSightWhenTargetsFallsOffThePlatform.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System;
  2. using UnityEngine;
  3. namespace Cinemachine.Examples
  4. {
  5. [RequireComponent(typeof(CinemachineTargetGroup))]
  6. public class LoseSightWhenTargetsFallsOffThePlatform : MonoBehaviour
  7. {
  8. [Tooltip("The platform from which LoseSightAtRange is calculated")]
  9. public Transform LowerPlatform;
  10. [Tooltip("The weight of a transform in the target group is 1 when above the Lower Platform. When a transform is " +
  11. "below the Lower Platform, then its weight decreases based on the distance between the transform and the " +
  12. "Lower Platform and it reaches 0 at LoseSightAtRange. If you set this value to 0, then the transform is removed " +
  13. "instantly when below the Lower Platform.")]
  14. [Range(0, 30)]
  15. public float LoseSightAtRange = 20;
  16. CinemachineTargetGroup m_TargetGroup;
  17. void Awake()
  18. {
  19. m_TargetGroup = GetComponent<CinemachineTargetGroup>();
  20. }
  21. void Update()
  22. {
  23. // iterate through each target in the targetGroup
  24. for (var index = 0; index < m_TargetGroup.m_Targets.Length; index++)
  25. {
  26. // skip null targets
  27. if (m_TargetGroup.m_Targets[index].target != null)
  28. {
  29. // calculate the distance between target and the LowerPlatform along the Y axis
  30. var distanceBelow = LowerPlatform.position.y - m_TargetGroup.m_Targets[index].target.position.y;
  31. // weight goes to 0 if it's farther below than LoseSightAtRange
  32. var weight = Mathf.Clamp(1 - distanceBelow / Mathf.Max(0.001f, LoseSightAtRange), 0, 1);
  33. m_TargetGroup.m_Targets[index].weight = weight;
  34. }
  35. }
  36. }
  37. }
  38. }