Advertisement
Elledan3101

TargetFollowerRotation

Jan 21st, 2021
569
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.87 KB | None | 0 0
  1.     public class TargetFollowerRotation : MonoBehaviour
  2.     {
  3.         [Header("General settings")]
  4.         [SerializeField]
  5.         private string targetTag = "Player";
  6.         [SerializeField]
  7.         private Transform targetToFollow;
  8.         public Transform TargetToFollow
  9.         {
  10.             get => targetToFollow;
  11.             set => targetToFollow = value;
  12.         }
  13.  
  14.         [Header("Rotation settings")]
  15.         [SerializeField]
  16.         private Vector3 rotationOffset;
  17.         public Vector3 RotationOffset
  18.         {
  19.             get => rotationOffset;
  20.             set => rotationOffset = value;
  21.         }
  22.  
  23.         [SerializeField]
  24.         private bool smoothRotation = true;
  25.         [SerializeField]
  26.         private float speedRotation = 1f;
  27.  
  28.         private Vector3 directionToTarget;
  29.         private Quaternion targetRotation;
  30.         private new Rigidbody rigidbody;
  31.  
  32.         private void Awake()
  33.         {
  34.             if (targetToFollow == null)
  35.             {
  36.                 GameObject foundObject = GameObject.FindGameObjectWithTag(targetTag);
  37.  
  38.                 if (foundObject != null)
  39.                     targetToFollow = foundObject.transform;
  40.             }
  41.  
  42.             rigidbody = GetComponent<Rigidbody>();
  43.         }
  44.  
  45.         private void LateUpdate()
  46.         {
  47.             Do();
  48.         }
  49.  
  50.         private void Do()
  51.         {
  52.             if (targetToFollow == null || speedRotation == 0) return;
  53.  
  54.             directionToTarget = (targetToFollow.position - rigidbody.position).normalized;
  55.  
  56.             targetRotation = Quaternion.LookRotation(directionToTarget, Vector3.up) * Quaternion.Euler(rotationOffset);
  57.  
  58.             if (smoothRotation)
  59.                 targetRotation = Quaternion.RotateTowards(rigidbody.rotation, targetRotation, speedRotation);
  60.  
  61.             rigidbody.MoveRotation(targetRotation);
  62.         }
  63.     }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement