- Home /
character turning where he looks
Hello world! so I'm working on a character controller that lets my character face the direction he's turning. This works fine when I'm going straight, left, right, or diagonally in any of the mentioned directions. However, whenever I try and go back he does so but does not turn. If I change the Vector3 value for "back" to 180 he will facing right but walk left and if I input the value as -180 he will look left but move right. Diagonal directions moving back do not work at all no matter the value. I'd like my character to turn facing back and walk in that direction (diagonal back directions as well).
Here's my "Example" script. Any help would be immensely appreciated!
using UnityEngine; using System.Collections;
public class Example : MonoBehaviour {
public float lookSpeed;
private Vector3 current;
private Vector3 front;
private Vector3 left;
private Vector3 right;
private Vector3 back;
private Rigidbody rb;
public float movementSpeed = 5.0f;
void Start () {
rb = GetComponent<Rigidbody>();
}
void Update () {
front = new Vector3 (0, 0, 0);
left = new Vector3 (-90, 0, 0);
right = new Vector3 (90, 0, 0);
back = new Vector3 (0, 0, 0);
print (current);
if (Input.GetKey (KeyCode.W)) {
rb.AddForce (transform.forward * movementSpeed);
transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation (front), Time.fixedDeltaTime * lookSpeed);
}
if (Input.GetKey (KeyCode.A)) {
rb.AddForce (transform.forward * movementSpeed);
transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation (left), Time.fixedDeltaTime * lookSpeed);
}
if (Input.GetKey (KeyCode.D)) {
rb.AddForce (transform.forward * movementSpeed);
transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation (right), Time.fixedDeltaTime * lookSpeed);
}
if (Input.GetKey (KeyCode.S)) {
rb.AddForce (transform.forward * -movementSpeed);
transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation (back), Time.fixedDeltaTime * lookSpeed);
}
}
}