# Simple following AI

Discussion in 'Scripting' started by Jsim, Jun 19, 2014.

1. ### Jsim

Joined:
May 12, 2014
Posts:
33
Not sure if this even constitutes being called an AI... But... Basically I'm making this top down completely 2D game and I am trying to get this enemy to look at the player and chase the player. i thought this would be ridiculously simple, but alas I am stumped.

Heres what I have:

Code (JavaScript):
1. #pragma strict
2.
3. var target : GameObject;
4. var walkspeed : int = 1;
5. private var dir : Vector3;
6.
7. function FixedUpdate(){
8.
9.     var customPosition : Vector3 = target.transform.position;
10.
11.     dir = customPosition - transform.position;
12.     dir = dir.normalized;
13.
14.     transform.Translate(dir, Space.World);
15.
16.     var rot : Quaternion = Quaternion.LookRotation(transform.position - customPosition, Vector3.forward );
17.     transform.rotation = rot;
18.     transform.eulerAngles = new Vector3(0, 0, transform.eulerAngles.z);
19. }
20.
21. function Update () {
22.
23. }
Currently what it does is freak out and teleport all around the player. I'm not sure if It is turning to face the player as it is intended to or not, all I know is that it teleports like crazy around the player.

2. ### Falin

Joined:
Sep 29, 2009
Posts:
242
It teleports to the target because of:
Code (csharp):
1.    transform.Translate(dir, Space.World);
To make the object move with the walk speed you need to change it to something like this:
Code (csharp):
1. transform.Translate(dir * walkspeed * Time.deltaTime, Space.World);
also to let the follower face the target instead of the rotation bit you could use this:
Code (csharp):
1.  transform.LookAt(target.transform);
Here is also an other thread on this subject:

3. ### Jsim

Joined:
May 12, 2014
Posts:
33

Thanks! Can you explain to me mathematically why the Time.deltaTime would affect that? I thought deltaTime always increased as the game went on and wouldn't that just speed up the enemy over time?

Joined:
May 19, 2012
Posts:
667
5. ### Jsim

Joined:
May 12, 2014
Posts:
33
Wow! That is actually quite incredibly useful! Thank you so much for your help

unityunity