- Home /
Still Having Trouble With AI Please HELP!
Hey, i have modelled a figure from 3Ds Max and have imported it into Unity and set a number a codes as my game is FPS and the code i am having trouble with is the code which allows the AI to move towards the player to attack.
The problem being is that the enemy AI moves through the terrain and then continues to go downwards, here is the code i have assigned to the enemy:
using UnityEngine; using System.Collections;
public class EnemyAI : MonoBehaviour { public Transform target; public int moveSpeed; public int rotationSpeed; public int maxDistance;
privateTransform myTransform;
void Awake(){ myTransform = transform; }
// Use this for initialization void Start() { GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
maxDistance = 2;
} // Update is called once per frame void Update(){ Debug.DrawLine(target.position, >myTransform.position);
//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; } } }
All help would be much appreciated!
Answer by Sriram · Dec 07, 2010 at 10:22 AM
There is a very good FPS tutorial( google unity3d fps tutorial) which follows a similar AI pattern as you mentioned.Take a look at it and you should understand where your going wrong! also i think most of that code is in java so you should take a look at
Answer by zander · Jan 13, 2011 at 08:03 PM
using UnityEngine; using System.Collections;
public class EnemyAI : MonoBehaviour { public Transform target; public int moveSpeed; public int rotationSpeed;
private Transform myTransform;
void Awake() { myTransform = transform; }
// Use this for initialization void Start () { GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
}
// Update is called once per frame void Update () { Debug.DrawLine(target.position, myTransform.position);
//Look at target
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
//Move towards target
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
I think that should do it