Rotate Character with movement

Right, I have a simple movement script. I haven’t picked up unity in a while and for some reason it seems i have forgotten some of the basics. I want my character to face the direction he is moving. Here is the script i have for movement at the moment.

var speed : float = 6.0;

var jumpSpeed : float = 8.0;

var gravity : float = 20.0;

private var moveDirection : Vector3 = Vector3.zero;

function Update() {
    var controller : CharacterController = GetComponent(CharacterController);
    
    if (controller.isGrounded) {
        // We are grounded, so recalculate
        // move direction directly from axes
        moveDirection = Vector3(Input.GetAxis("Horizontal"), 0,
                                Input.GetAxis("Vertical"));
        moveDirection = transform.TransformDirection(moveDirection);
        moveDirection *= speed;
        
        if (Input.GetButton ("Jump")) {
            moveDirection.y = jumpSpeed;
        }
    }

    // Apply gravity
    moveDirection.y -= gravity * Time.deltaTime;
    
    // Move the controller
    controller.Move(moveDirection * Time.deltaTime);
}

3 Answers

3

Like this-

if(moveDirection.magnitude > 0.05f)
{
    transform.LookAt(transform.position + moveDirection);
}

I mean, that’s just one way- you can do it any way really.

Oh yeah- you have to do it before any of the jump stuff gets added.

Thank you!

Turns out it’s just easier to use the third person controller script in the standard assets.

Hi, I am having same kind of trouble, but instead of moving all direction , my character is restricted to move in x-direction only - moveDirection = new Vector3(0,0,Input.GetAxis("Horizontal")); basically what i want is to move my character in 2d platform.