Hi people.
I’m trying to make a simple script to make an object follow another object smoothly. I’ve seen some examples here in other answers, but in all of them I’m having the same problem (including my solution which is below). My problem is, the object do follow the target object though when it reaches the minimum distance it starts to move very very slowly to a random direction or in a circle trajectory around the target object. Can anyone tell me what am I doing wrong?
using UnityEngine;
using System.Collections;
public class AllyFollow : MonoBehaviour {
public Transform target;
public float smoothTime = 0.3f;
public float distance = 2.5f;
public float correction = 0.1f;
private Vector2 velocity;
private Vector3 thisPosition;
private Transform thisTransform;
void Start ()
{
thisTransform = transform;
}
void Update ()
{
// Look at target
Vector3 targetRelativeDirection = target.position - thisTransform.position;
targetRelativeDirection.y = 0;
thisTransform.forward = targetRelativeDirection;
// Seems to work fine up to here...
Debug.Log("value 1 - " + targetRelativeDirection.magnitude);
Debug.Log("value 2 - " + (distance + correction));
// Follow target if distance between me and target is
if (targetRelativeDirection.magnitude > distance + correction)
{
Debug.Log("FOLLOWING");
thisPosition = thisTransform.position;
thisPosition.x = Mathf.SmoothDamp(thisTransform.position.x, (target.position.x - (distance * targetRelativeDirection.normalized.x)), ref velocity.x, smoothTime);
thisPosition.z = Mathf.SmoothDamp(thisTransform.position.z, (target.position.z - (distance * targetRelativeDirection.normalized.z)), ref velocity.y, smoothTime);
thisTransform.position = thisPosition;
}
else
{
Debug.Log("NOT FOLLOWING");
}
}
}