Making enemy follow player
So I have been trying to make my object(a sphere with sphere collider and sphere collider trigger) follow my player,but the script is giving out errors and i have no idea what do they mean,and how to fix them,here is the piece of code I wrote:
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (playerdestructor == true)
Debug.Log ("touchy");
rigid.AddForce (Vector2.MoveTowards (self, player, 10f));
if (playerdestructor == false)
Debug.Log ("lonely :(");
}
void OnTriggerEnter2D (Collider2D col){
if (col.tag == "Player")
playerdestructor = true;
}
void OnTriggerExit2D (Collider2D coly){
if (coly.tag == "Player")
playerdestructor = false;
}
}
my object jumps directly to my player even if i set a speed it teleports to my play and won't follow.I have tweaked it to work on my project,this is what i have got so far
void Update () {
transform.position = new Vector3 (xaxis, 0);
if (playerdestructor == true) {
Debug.Log ("touchy");
rigid.transform.position = Vector3.$$anonymous$$oveTowards (self.position, player.position, 5) * speed;
}
The max$$anonymous$$oveDeltas are quite high, move the speed variable and try a smaller value like 0.1
rigid.transform.position = Vector3.$$anonymous$$oveTowards (self.position, player.position, speed);
well thanks for the advice,it doesn't follow my player but it doesn't teleport to it instantly either,Any fix?
Answer by Winterblood · Apr 27, 2016 at 01:59 PM
You're moving "self" towards "player" with a distance cap of "speed". This will happen instantly. If you want to spread the movement over several frames, multiply speed by Time.deltaTime:
rigid.transform.position = Vector3.MoveTowards (self.position, player.position, speed * Time.deltaTime);
The delta time is the time between frames, ie. how much time has passed since the last Update.
This will also make the movement framerate-independent (a slow machine will have a larger deltaTime, so the object will move in larger steps but take the same time to arrive as it would on a fast machine).
Your answer
![](https://koobas.hobune.stream/wayback/20220612075605im_/https://answers.unity.com/themes/thub/images/avi.jpg)