How do I make my Game Object face the direction it's going?

Hi Guys. I’m new to Unity 3D. I’ve been following the lessons from www.unity3dstudent.com and I’ve been trying to make my object move using the keyboard. I’m having trouble making it face the direction it’s going. Any help and advice would be greatly appreciated. Thanks in advance to anyone who can help me. :slight_smile:

Here is the script I’ve been using:

var speed = 3.0;
var rotateSpeed = 3.0;

function Update () {
        var horiz : float = Input.GetAxis("Horizontal");
 transform.Translate(Vector3(horiz * rotateSpeed,0,0));
 transform.Rotate(Vector3(0,horiz * rotateSpeed,0));
 {
        var verti : float = Input.GetAxis("Vertical");
 transform.Translate(Vector3(0,0,verti * speed));
 }
 }

Your problem is line 5. You don’t want to use the ‘Horizontal’ axes for both translation and rotation. Line 10 handles the translation.

In addition, this code should scale things by Time.deltaTime so that it runs consistently as the Frames per Second change.

#pragma strict

var speed = 3.0;         // Units per second
var rotateSpeed = 90.0;  // Degrees per second
 
function Update () {
     var horiz : float = Input.GetAxis("Horizontal");
	 transform.Rotate(Vector3(0,horiz * rotateSpeed * Time.deltaTime,0));

    var verti : float = Input.GetAxis("Vertical");
 	transform.Translate(Vector3(0,0,verti * speed * Time.deltaTime));
 }

First, move your var horiz and verti declarations above where your speed and rotateSpeed are. This way you won’t keep instantiating a new variable every time your program updates. Instead set horiz within update, or not at all.

You could get rid of horiz and verti and just have “transform.Translate(Vector3(Input.GetAxis(“Horizontal”) * rotateSpeed…”

As far as rotation goes, what I did (C#) is check if the Input.GetAxis(“Horizontal”) was > 0. If it was, player was moving right. Else, the player was moving left. You’ll want to rotate on the Y-axis via transform.Rotate() within each condition, as that will make your player spin to face another direction.

You need to translate in the forward direction of your characters transform.

transform.Translate(transform.forward * verti * speed);