- Home /
Unity 2D Object Smooth Follow Problem C#
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);
}
}
Answer by RudyTheDev · Sep 25, 2015 at 09:21 PM
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);
}
That worked perfectly. Thanks a bunch.
I didn't think about that. The logic seems backwards from what I usually have. I like it. I'm going to start reading into magnitude and normalized as well. I have to figure out how you did that. ^_^ Thanks again.
Answer by Dinosaurs · Sep 25, 2015 at 09:33 PM
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.