Okay, I want objectA to follow ObjectB but not until ObjectB is a certain distance away.
The code I have works*… But its really jumpy sometimes as it only works when ObjectB is further away than 3 units, so it kicks off and on a lot. What is a way to fix this to smooth it out?
void FixedUpdate ()
{
distance = Vector3.Distance(transform.position, box.transform.position);
if (distance >= 3)
{
gameObject.transform.position = Vector2.MoveTowards(gameObject.transform.position, box.gameObject.transform.position, 15 * Time.deltaTime);
}
}
Yes, don’t move towards the ObjectA, rather to a point 3 units away from ObjectA. That way your MoveTowards cannot overshoot. Something like:
Vector3 distance = box.transform.position - transform.position;
if (distance.magnitude >= 3)
{
Vector3 targetPoint = box.transform.position - distance.normalized * 3;
gameObject.transform.position =
Vector3.MoveTowards(gameObject.transform.position, targetPoint, 15 * Time.deltaTime);
}
FixedUpdate() should only be used for physics related code; if you’re going to move an object using it’s transform, it should move smoother if you do it in Update(). This is because Update() is called on every camera frame update, while FixedUpdate() is called at a fixed timestep independent of rendered frames, causing the camera and your movement system to be out of sync.