- Home /
My AI is flying when I jump
How can I change my script so the Enemy doesn't fly when I'm above it?
var target : Transform; //the enemy's target
var moveSpeed = 3; //move speed
var rotationSpeed = 3; //speed of turning
var myTransform : Transform; //current transform data of this enemy
function Awake()
{
myTransform = transform; //cache transform data for easy access/preformance
}
function Start()
{
target = GameObject.FindWithTag("Player").transform; //target the player
}
function Update () {
//rotate to look at the player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
//move towards the player
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
Answer by Andres-Fernandez · May 29, 2014 at 01:49 PM
Instead of using target.position - myTransform.position to obtain the lookrotation, use another Vector3 that has the same vertical position of the enemy transform. Something like this:
Vector3 newTargetPosition = new Vector3(target.position.x, myTransform.position.y, target.position.z);
Then, use it in the Quaternion.LookRotation as this:
Quaternion.LookRotation(newTargetPosition - myTransform.position)
[EDIT] forgot to mention that my code is in C#...
About where should I use it, I'm tired and trying to read and my code doesn't look so good
var target : Transform; //the enemy's target
var moveSpeed = 3; //move speed
var rotationSpeed = 3; //speed of turning
var myTransform : Transform; //current transform data of this enemy
function Awake()
{
myTransform = transform; //cache transform data for easy access/preformance
}
function Start()
{
target = GameObject.FindWithTag("Player").transform; //target the player
Vector3 newTargetPosition = new Vector3(target.position.x, myTransform.position.y, target.position.z);
//THAT ONE
}
function Update () {
//rotate to look at the player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(newTargetPosition - myTransform.position), rotationSpeed*Time.deltaTime);
//AND THAT
//move towards the player
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
In the update function, make it the first line inside the function. And I believe you need to translate it to JavaScript. It should be something like this:
var newTargetPosition: Vector3 = new Vector3(target.position.x, myTransform.position.y, target.position.z);
Answer by JohnnySunshine · May 29, 2014 at 01:52 PM
Depending on your game, you could remove the y component of the movement vector:
Vector3 movement = myTransform.forward * moveSpeed * Time.deltaTime;
movement = new Vector3(movement.x, 0, movement.z);
myTransform.position += movement;
Or you could add a CharacterController to the AI, but that's a tad bit harder and probably slower, but it would use the level geometry (if you have any).
Where in the code should I paste it? (Tired and confused right now)