- Home /
How to make an object follow the player?
Hello I need help making the object follow the player.
Please be more descriptive. Is the object following at a fixed distance, or is it AI driven and has to chase the player?
Answer by MT369MT · Jun 07, 2018 at 07:13 PM
Hi, you can use something like this:
public GameObject Player;
public float Speed;
void Start()
{
Player = GameObject.Find(“Player”);
Speed = 10;
}
void Update()
{
Transform.Translate((Player.transform.position - transform.position).normalized * Speed * Time.deltaTime);
}
Transform.translate has an error message for some reason.
Your syntax is pretty off, should be:
void Update()
{
this.transform.Translate((Player.transform.position - transform.position) * Speed * Time.deltaTime);
}
Sorry, didn't notice that the vector wasn't being normalized:
void Update()
{
Vector3 direction = (Player.transform.position - transform.position).normalized;
this.transform.Translate(direction * Speed * Time.deltaTime);
}
It's working fine on my end:
Can you paste your script? $$anonymous$$aybe something wasn't entered correctly.
Answer by GameDevH2O · Jun 07, 2018 at 08:05 PM
This code works! But the only issue is it follows a bit too fast & I tried to adjust the speed & it slows down when it gets close to the player is there a way the speed can move the same speed throughout the whole follow? @TreyH
public class FollowObject1 : $$anonymous$$onoBehaviour {
public GameObject Player;
public float Speed;
// Use this for initialization
void Start () {
Player = GameObject.Find("Player");
Speed = 10;
}
// Update is called once per frame
void Update () {
Vector3 direction = (Player.transform.position - transform.position).normalized;
this.transform.Translate((Player.transform.position - transform.position) * Speed * Time.deltaTime);
}
}
@TreyH like this?
You need to use the direction
value in your Translate
call.
this.transform.Translate(direction * Speed * Time.deltaTime);
Your answer
Follow this Question
Related Questions
Color area below line renderer? 0 Answers
Choppy Character Movement Unity 2D 0 Answers
What can I do to further optimize mobile game? (2D) 0 Answers
Multiple Cars not working 1 Answer
UIText not updating on Android build 0 Answers