How do I make a character turn in the direction of the camera once (to attack player), then turn back to the direction at which it was looking? The following attempt failed:
function Update () {
if (calculateDistance(GameObject.Find("Main Camera"), this.gameObject) > 4f) {
if (rotation.y != 10001) {
//this.gameObject.transform.eulerAngles = rotation;
//this.gameObject.transform.LookAt(oldForward, oldUp);
this.gameObject.transform.localRotation = rotation;
addWalkingForce();//MOVE FORWARD AGAIN
rotation.y = 10001;
}
this.animation.Play ("Walks");
}
else {
this.animation.CrossFade ("Attacks");
oldForward = this.gameObject.transform.forward;
oldUp = new Vector3(Vector3.up.x, Vector3.up.y, Vector3.up.z);
rotation = this.gameObject.transform.localRotation;
rigidbody.velocity = Vector3.zero;//KILL FORWARD MOVEMENT
this.transform.LookAt(GameObject.Find("Main Camera").transform, Vector3.up)
}
I'm surprised no one had anything to say about it. But the following worked. I added the time test to prevent it from storing the rotated forward before the animation could be said to be "Walks" (as it was cross fading, I suppose). Other than this little bit, the only thing I can tell was wrong was that transform.forward gives you the worldspace vector but not the actual position (hence the addition). I hope this helps someone.
PS: How frustrating is this system of trying to get code colored and indented here? Come on, guys, come up with ` ` brackets, or something.
private var oldForward : Vector3;
private var lastTimeStoredForward : float;
function calculateDistance(from : GameObject, to : GameObject) : float {
var origin : Vector3 = from.transform.position;
var destination : Vector3 = to.transform.position;
return Mathf.Sqrt((origin.x-destination.x)(origin.x-destination.x) + (origin.y-destination.y)(origin.y-destination.y) + (origin.z-destination.z)*(origin.z-destination.z));
}
function addWalkingForce() {
this.rigidbody.AddForce (this.gameObject.rigidbody.transform.forward*20);
}
function Start() {
addWalkingForce();
oldForward.y = 10001;
lastTimeStoredForward = -99999;
}
function Update () {
if (calculateDistance(GameObject.Find("Main Camera"), this.gameObject) > 4f) {
if (oldForward.y != 10001) {
this.gameObject.transform.LookAt(oldForward, Vector3.up);