- Home /
Look At Target Without Y
How can I make my script have the enemy look at the Player without using the local Y axis so he doesn't rotate into the air? So far he looks at the Player but once the Player gets too close or jumps, he'll start rotating into the air to look at him, any help?
//LOOK AT THE PLAYER ONCE TARGETED//
if(targeted){
var rotation = Quaternion.LookRotation(Player.transform.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
ChasePlayer = gameObject.GetComponent("EnemyControl");
if(distanceToTarget >= 2){
isMoving = true;
}else{
isMoving = false;
}
}else{
isMoving = false;
}
//CHASE THE PLAYER//
if(isMoving){
animation.CrossFade("run",0.2);
var controller2 : CharacterController = GetComponent(CharacterController);
var forward : Vector3 = transform.TransformDirection(Vector3.forward);
controller2.SimpleMove(forward * 3);
}
}
Answer by testure · Jun 26, 2011 at 04:55 PM
The fastest way to do this is to zero out x and z after your call to lookat.
transform.eulerAngles = new Vector3(0,transform.eulerAngles.y,0);
Thanks a lot man! I needed this! I've been looking all night so now i can get some sleep.
Answer by Gillissie · Jun 26, 2011 at 04:38 PM
I may not be 100% clear on what you mean, but you can always manually set any rotation value before applying it to a transform. If you want Y to remain constant, simply set the y property of the rotation to whatever you want before applying it. Something like this, maybe:
var rotation = Quaternion.LookRotation(Player.transform.position - transform.position);
rotation.y = 0;
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
[edit] Now that I think about it, you may want to set the x property, not y.
Answer by Gillissie · Jun 26, 2011 at 04:42 PM
Also see this post http://answers.unity3d.com/questions/36255/lookat-to-only-rotate-on-y-axis-how.html