How do I turn to face direction of movement?

I’m using Javascript and I can’t figure out how to turn the character model. This is the code for the movement script:
#pragma strict

var speed = 3.0;

function Start () {

}

function Update () {
    var direction = Vector3.zero;
    if(Input.GetKey(KeyCode.A)) {
       direction += Vector3.left;
    }
    if(Input.GetKey(KeyCode.S)) {
       direction += Vector3.back;
    }
    if(Input.GetKey(KeyCode.D)) {
       direction += Vector3.right;  
    }
    if(Input.GetKey(KeyCode.W)) {
       direction += Vector3.forward;  
    }
 
    transform.Translate(direction * speed * Time.deltaTime);
}

1 Answer

1

you’re doing well so far, but as you’ve noticed tranform.Translate moves the object without rotating it. the simplest possible way to turn the character toward that point is

	transform.LookAt(direction);

which works but only in a single frame(no smoothing).

It sounds like this a first project so I might just start with that. the character will sort of ‘snap’ into the right rotation and that might actually look okay in your game. If you want to do something that slowly rotates the character toward the right direction, you’ll want to use something like Quaternion.Slerp.