Saturday, 22 March 2014

Enemy following player

public class EnemyFollow : MonoBehaviour {
public Transform target; //will show in inspecter but dont need to fill in
public int moveSpeed;
public int rotationSpeed;
public int maxdistance; //if player within this distance in inspector it will follow is not it will not follow
private Transform myTransform;
public AudioClip approachHeartBeat; //this is sound effect dont need


void Start(){
myTransform = transform;
target = GameObject.FindGameObjectWithTag ("Player").transform;//will find object tagged Player
}

void Update () {
if (Vector3.Distance(target.position, myTransform.position) < maxdistance)
{

//Debug.Log ("I AM FUCKING MOVING");
audio.PlayOneShot(approachHeartBeat, 1.0f); //this is sound effect dont need
// Get a direction vector from us to the target
Vector3 dir = target.position - myTransform.position;

// Normalize it so that it's a unit direction vector
dir.Normalize();

// Move ourselves in that direction
transform.position += dir * moveSpeed * Time.deltaTime;
}

if (Vector3.Distance (target.position, myTransform.position) > maxdistance)
{
Destroy(gameObject);
}

}
}


No comments:

Post a Comment