- Home /
The question is answered, right answer was accepted
Problem with trigger
I am new to using unity and I have run into what seems like is a simple problem that I cannot figure out. I want to use a cube as a trigger to make objects follow the first person controller. It seems like it should be pretty straight forward, I have yet to see much documentation about this though. Anyone that can help?
What do you mean by 'follow'? should they be attached to the first person controller (like collecting a weapon), or chase after (like a creature). What have you tried so far, and where is it failing?
Answer by Phoskryfes · Oct 30, 2012 at 01:36 AM
I think if you touch the cube, the cube will chase you. That's what I think your question is. Put this to the cube but it will chase you even without triggering. Make the cube into an enemy tag and your player into player tag first before inserting this.
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
public Transform target;
public int moveSpeed;
public int rotationSpeed;
public int maxDistance;
private Transform myTransform;
void Awake() {
myTransform = transform;
target = null;
}
// Use this for initialization
IEnumerator Start () {
yield return new WaitForSeconds(10);
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
maxDistance = 1;
}
// Update is called once per frame
void Update () {
if(target == null) {
return;
}
Debug.DrawLine(target.position, myTransform.position, Color.yellow);
//Look at target
myTransform.rotation = Quaternion.Slerp (myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
if(Vector3.Distance(target.position, myTransform.position) > maxDistance) {
//Move towards target
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
}
Could you accept my answer by pressing the check button at the left side of my answer?