Skip to content

Instantly share code, notes, and snippets.

@Velsimir
Created March 14, 2025 16:42
Show Gist options
  • Select an option

  • Save Velsimir/038efdb95caa98f6a038ea003942c825 to your computer and use it in GitHub Desktop.

Select an option

Save Velsimir/038efdb95caa98f6a038ea003942c825 to your computer and use it in GitHub Desktop.
[RequireComponent(typeof(Rigidbody))]
public class Follower : MonoBehaviour
{
[SerializeField] private Player _player;
[SerializeField] private float _speed = 5f;
[SerializeField] private float _distance = 5f;
private Rigidbody _rigidbody;
private void Awake()
{
_rigidbody = GetComponent<Rigidbody>();
_rigidbody.interpolation = RigidbodyInterpolation.Interpolate;
_rigidbody.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
_rigidbody.freezeRotation = true;
}
private void FixedUpdate()
{
if (transform.position.IsEnoughDistance(_player.transform.position, _distance) == false)
{
Follow();
}
else
{
_rigidbody.linearVelocity = Vector3.zero;
RotateTowardsTarget(GetDirection());
}
}
private void Follow()
{
Vector3 direction = GetDirection();
RotateTowardsTarget(direction);
MoveTowardsPlayer(direction);
}
private Vector3 GetDirection()
{
Vector3 direction = _player.transform.position - transform.position;
return direction.normalized;
}
private void RotateTowardsTarget(Vector3 direction)
{
Quaternion targetRotation = Quaternion.LookRotation(direction);
_rigidbody.MoveRotation(targetRotation);
}
private void MoveTowardsPlayer(Vector3 direction)
{
Vector3 velocity = direction * _speed;
_rigidbody.linearVelocity = velocity;
_rigidbody.linearVelocity += Physics.gravity;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment