Answer the question
In order to leave comments, you need to log in
How to make an object dynamically move after another in 2D (Unity)?
Hello. I have already spent a lot of time trying to solve the following problem: there are two objects, A and B, object A is in position Y = 0, and object B is in position Y = -100. Object A is the leader and is in constant motion, for example: transform.position += transform.up * speed;
Object B must move behind it so that if the distance between them, for example, is above 300, then object B adds speed to the base and gradually catches up with object A, and if the distance is lower, then object B, on the contrary, lags behind object A, reducing the base speed. At the start, the base speed of object B is the same as that of object A. The distance can be calculated as follows:
var distance = (a.transform.position - b.transform.position).magnitude;
Answer the question
In order to leave comments, you need to log in
Due to little experience, I did not know about the interesting Lerp method in Vector3:
Vector3.Lerp
You can first try a couple of ready-made scripts like Smooth Camera Follow.
For example:
answers.unity3d.com/questions/29183/2d-camera-smoo...
Easy to use. The script is hung on what should follow the other thing, and a link to what should be followed is placed in the target field in the Inspector.
It's best not to move an object that already has a Rigidbody in this way. Then there will be vibration.
To keep the distance, you can insert a simple if statement into the code from the example
Vector3 delta = target.position - camera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, point.z));
if (delta. magnitude > someValue)
{
Vector3 destination = transform.position + delta;
transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, dampTime);
}
Vector3 delta = target.position - camera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, point.z));
if (delta. magnitude < someValue)
{
Vector3 destination = transform.position + delta;
transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, dampTime);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question