Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class TargetFollowerRotation : MonoBehaviour
- {
- [Header("General settings")]
- [SerializeField]
- private string targetTag = "Player";
- [SerializeField]
- private Transform targetToFollow;
- public Transform TargetToFollow
- {
- get => targetToFollow;
- set => targetToFollow = value;
- }
- [Header("Rotation settings")]
- [SerializeField]
- private Vector3 rotationOffset;
- public Vector3 RotationOffset
- {
- get => rotationOffset;
- set => rotationOffset = value;
- }
- [SerializeField]
- private bool smoothRotation = true;
- [SerializeField]
- private float speedRotation = 1f;
- private Vector3 directionToTarget;
- private Quaternion targetRotation;
- private new Rigidbody rigidbody;
- private void Awake()
- {
- if (targetToFollow == null)
- {
- GameObject foundObject = GameObject.FindGameObjectWithTag(targetTag);
- if (foundObject != null)
- targetToFollow = foundObject.transform;
- }
- rigidbody = GetComponent<Rigidbody>();
- }
- private void LateUpdate()
- {
- Do();
- }
- private void Do()
- {
- if (targetToFollow == null || speedRotation == 0) return;
- directionToTarget = (targetToFollow.position - rigidbody.position).normalized;
- targetRotation = Quaternion.LookRotation(directionToTarget, Vector3.up) * Quaternion.Euler(rotationOffset);
- if (smoothRotation)
- targetRotation = Quaternion.RotateTowards(rigidbody.rotation, targetRotation, speedRotation);
- rigidbody.MoveRotation(targetRotation);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement