|
well I have created this script and when the enemies target me they gather infront of me. I want them to keep distance here is my code I think my problem is however I do not know how to fix it. please help = )
(comments are locked)
|
|
The easiest way is to add a CharacterController to the enemy and use Move to move it (or SimpleMove, if you want to include gravity): the CharacterController detects collisions with any collider, thus will not occupy the same place as the others.
public Transform target;
public int moveSpeed;
public int rotationSpeed;
public int maxDistance;
private Transform myTransform;
void Awake() {
myTransform = transform;
}
CharacterController character;
void Start () {
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
character = GetComponent<CharacterController>();
maxDistance = 2;
}
void Update () {
Debug.DrawLine(target.position, myTransform.position, Color.yellow);
Vector3 dir = target.position - myTransform.position;
dir.y = 0; // kill height differences to avoid enemy tilting
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(dir), rotationSpeed * Time.deltaTime);
if (dir.magnitude > maxDistance) {
character.Move(myTransform.forward * moveSpeed * Time.deltaTime);
}
}
If you want to include gravity, replace character.Move with: when I add character.SimpleMove(Vector3.forward * moveSpeed); he starts moving to the side
Jan 20 '12 at 10:20 PM
Babilinski
Do you have other colliders childed to the character? The CharacterController has a bug that makes it move to weird directions when any childed collider is in touch with the character capsule collider. To solve this, mark Is Trigger in any childed object's collider (or just delete the child's collider).
Jan 20 '12 at 10:47 PM
aldonaletto
Forget about the previous comment about the bug: I forgot to convert the direction to world space. Actually, it's easier to use transform.forward instead. I edited my answer to use world direction.
Jan 20 '12 at 10:54 PM
aldonaletto
(comments are locked)
|
|
Tried your script. The problem in not in the statement you think. In the start function you are keeping the value of maxDistance to 2 always when the script runs. Remove the statement I Hope this helps
(comments are locked)
|
