How to turn and face the direction I'm moving using CharacterController?

Hi all,

I'm new to Unity, and although I've got programming experience with JS these libraries sure do take a while to learn! :)

I'm working on a game with a top down view that has the camera targeted at the player character below. The camera never rotates, it keeps the same perspective.

The character needs to walk in the direction of the arrow key pressed. So there is no "forward" as such.

I had it all working nicely until my character walked through a wall and I read that I need to use Move or SimpleMove rather than Transform.position to stop this from happening.

I'm now using a slightly modified version of the script example for 'Move' in the docs.

I can move around in all directions but I can't get the player to face the direction he's walking in. Hopefully, someone can help me out :)

My script is:

var speed = 6.0;
var gravity = 20.0;
var bulletPrefab:Transform;

private var moveDirection = Vector3.zero;

function FixedUpdate() {
    var controller : CharacterController = GetComponent(CharacterController);
    if (controller.isGrounded) {

        moveDirection = Vector3(Input.GetAxis("Horizontal"), 0,
        Input.GetAxis("Vertical"));

    /* Here's the part I'm having trouble with... 
       If I don't add the following if block, the character moves correctly but doesn't
       face the correct direction.
       If I do add this if block, the character faces the correct direction but
       both the up and down arrow keys make the character move up the screen
       and the left and right arrows make him move down the screen. So it's like 
       I'm only accessing the vertical axis.
    */
        if (moveDirection != Vector3.zero) {
            var rotation = transform.rotation; 
            rotation.SetLookRotation(moveDirection); 
            transform.rotation = rotation;
        }

        moveDirection = transform.TransformDirection(moveDirection);
        moveDirection *= speed;

        if(Input.GetButtonDown("Jump")) {
            var bullet = Instantiate(bulletPrefab, 
                                        GameObject.Find("spawnFireBall").transform.position, 
                                        Quaternion.identity);
            bullet.rigidbody.AddForce(transform.forward * 1200);
        }
    }

    // Apply gravity
    moveDirection.y -= gravity * Time.deltaTime;

    // Move the controller
    controller.Move(moveDirection * Time.deltaTime);
}

Fixed.

After fiddling around with it for some time I found the answer.

I just needed to remove the following line:

moveDirection = transform.TransformDirection(moveDirection);

I was using both setLookRotation and TransformDirection and they didn't seem to like each other. TransformDirection wasn't even needed in the end :)

Hooray!

You can Use "MouseLook" script in standard assets. just import standard assets from Assets>>Import packages menu.