- Home /
How to make a gameObject follow another one with delay and variable speed?
Hello everyone. I want to make it so that when a gameObject ("Player") controlled by the player moves, a second one ("Secondary"), after a brief delay, starts moving from a set distance, following it, such that the distance between the two remains the same after the second gameObject stops. The idea is that Secondary will always go to a point y = ([current Player position] - 1.9) even after Player stops moving.
These are the two C# scripts I used, however, the second one only makes the second gameObject appear at the set distance after the delay, without displaying movement. How could I fix this, so that Secondary is shown moving? Thank you in advance.
First script:
public class PlayerMovement : MonoBehaviour { public float speed = 1f;
void Start () {
}
void Update () {
if (Input.GetKey (KeyCode.D))
transform.position += new Vector3 (speed * Time.deltaTime, 0.0f, 0.0f);
if (Input.GetKey (KeyCode.A))
transform.position -= new Vector3 (speed * Time.deltaTime, 0.0f, 0.0f);
if (Input.GetKey (KeyCode.W))
transform.position += new Vector3 (0.0f, speed * Time.deltaTime, 0.0f);
if (Input.GetKey (KeyCode.S))
transform.position -= new Vector3 (0.0f, speed * Time.deltaTime, 0.0f);
}
}
Second script:
public class SecondaryMovement : MonoBehaviour { Transform pos; public float timer = 0; public float delay = 1f;
void Start () {
pos = GameObject.Find("Player").transform;
}
void Update () {
timer -= Time.deltaTime;
if (timer <= 0) {
transform.position = new Vector3 (pos.position.x, pos.position.y - 1.9f, transform.position.z);
timer = delay;
}
}
}
I would have used a system of triggers ins$$anonymous$$d. When your "follower" is outside your player's trigger, he follows him, when the follower enters the player's trigger, he stops. T
Tuto about triggers in Unity (with 3D objects, but works the same way)
Answer by Duugu · Jun 05, 2015 at 05:02 PM
transform.position = new Vector3 (pos.position.x, pos.position.y - 1.9f, transform.position.z);
This line moves your secondary object instantly to the position of you primary object.
Have a look at Vector3.Lerp to move your object slowly.
Your answer
![](https://koobas.hobune.stream/wayback/20220613200638im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
smooth follow 2d camera runner ios 0 Answers
Ground dash is like a teleport 0 Answers
2D Linked Portals 0 Answers
2D character movement is jittery (top-down) 1 Answer
How do I flip the character when an object is infront/behind it? 1 Answer