public void Follow()
{
if (target.name.ToString()==(“Player”)) {
Debug.Log (“lksfn”);
Vector3 dir = target.position - transform.position;
// z value is er gewoon omda het 2d is wete wel
dir.z = 0.0f;
if (dir != Vector3.zero)
transform.rotation = Quaternion.Slerp (transform.rotation,
Quaternion.FromToRotation (Vector3.right, dir),
rotationSpeed * Time.deltaTime);
transform.position += (target.position - transform.position).normalized
* moveSpeed * Time.deltaTime;
}
}
Here is a solution that works if you don’t go by way of NavMeshAgent. Put it on any gameObject to test. You’ll see that it has no regard for any obstacles that may get between him and the player - which is fine if it is a ghost and can go through walls. I also added a line at the end so the object stops when it gets too close otherwise it just circles around the player. One last thing is that - at least with my player - the pivot is on the ground , not in his center of mass, so the gameobject is coming at me looking at the ground. But he is moving and chasing and stops. NavMesh is a much better way
using UnityEngine;
using System.Collections;
public class chasePlayer : MonoBehaviour {
float moveSpeed = 3.0f;
public GameObject player;//note the small case "p"
private Transform Player;//note the upper case "P". You don't need this to make the object follow the player but I put it in in a hurry to do the last bit of code to get him to stop.
public int stopDist = 2;
void Start(){
Player = player.transform;
}
void Update(){
//code for looking to player
transform.rotation = Quaternion.Slerp(transform.rotation,
Quaternion.LookRotation(player.transform.position - transform.position), moveSpeed * Time.deltaTime);
//code for following the player
transform.position += transform.forward * moveSpeed * Time.deltaTime;
// the next part below is what I through in to get the object to stop if too close then resume if player moves away again
if (Vector3.Distance (transform.position, Player.position) <= stopDist)
moveSpeed = 0f;
if (Vector3.Distance (transform.position, Player.position) > stopDist)
moveSpeed = 3f;
}
}