- Home /
Help with CharacterController rotation
Hi I think this is an easy fix however I'm having trouble with it. Basically I need my CharacterController to face the same direction hes moving.
var speed : float = 4.0;
var gravity : float = 20.0;
private var velocity : Vector3 = Vector3.zero;
var controller : CharacterController;
function Update ()
{
if (controller.isGrounded)
{
velocity = GetHorizontalMovement();
velocity *= speed;
}
velocity.y -= gravity * Time.deltaTime;
controller.Move (velocity * Time.deltaTime);
}
function GetHorizontalMovement()
{
var direction : Vector3 = Vector3 (Input.GetAxisRaw("Horizontal"), 0, 0);
return transform.TransformDirection (direction);
}
other question :) Is that a sidescroller or a top-down game? It looks like a sidescroller since you only checking the Horizontal axis? in this case you could just check if the Horizontal-Axis value is >0 or <0 and then rotate the character
Im not sure what you mean by what kind of character controller. I only know of the one in the physics component. The game is a sidescroller.
The problem with that is if i go left its <0 and itll turn 180 but if I press left again it's still <0 so it will turn again when it shouldn't
Answer by InfiniBuzz · Jun 12, 2013 at 10:36 PM
you can use (not tested)
function Update ()
{
if (controller.isGrounded)
{
velocity = GetHorizontalMovement();
velocity *= speed;
}
velocity.y -= gravity * Time.deltaTime;
controller.Move (velocity * Time.deltaTime);
if(Input.GetAxis("Horizontal") > 0)
transform.rotation = Quaternion.Euler(0, 0, 0);
else if(Input.GetAxis("Horizontal") < 0)
transform.rotation = Quaternion.Euler(0, 180, 0);
}
You will need to adjust the rotating values sice I don't know how your scene is set up.
E: I see you are a quiet new user, make sure to tick and vote answers that helped you on unity answers (also on your other questions) this helps others to see if an answer is sucessfully answered and the person you tick gets more karma ;)
It worked!!! When I go left he faces left but walks backwards but you fixed the rotation which has been killing me for 3 days thanks a lot brother.
Glad it helped :) if its facing wrong you need to adjust the angles or the axis input (0)
make sure to tick and vote answers if they helped :)