- Home /
Character Controller rotate unity
I am using a joystick to make the character move using the CHaracter Controller script like this:
var jumpSpeed : float = 8.0;
var gravity : float = 20.0;
var moveJoystick : Joystick;
var speed: float = 1.0;
var turnSpeed:float = 1.0;
var angle: float = 1.0;
private var moveDirection : Vector3 = Vector3.zero;
function Update() {
var controller : CharacterController = GetComponent(CharacterController);
moveDirection.y -= gravity * Time.deltaTime;
if (moveJoystick.position.y>0) {
controller.Move(Vector3.forward * moveJoystick.position.y * speed);
}
else {
controller.Move(-Vector3.forward * moveJoystick.position.y * speed);
}
controller.Move(moveDirection * Time.deltaTime);
angle = Mathf.Atan2(moveJoystick.position.x, transform.rotation = Quaternion.Euler(new Vector3(0, angle,0));
}
The only problem is that the player does not move towards the direction it is facing. It just keeps going forward all the time.
Answer by robertbu · Oct 11, 2013 at 02:53 PM
On line 15 and line 18 replace 'Vector3.forward' with 'transform.forward'. Vector3.forward is shorthand for Vector(0,0,1) and represents the forward direction in the local coordinates of the object. 'transform.forward' is forward in world coordinates. It is the same as:
transform.TransformDirection(Vector3.forward);
thank you that works. Although just one thing, that the rotation snaps when joystick is released to angles like 90, 180, 270 ,360
I'm guessing about your joystick code. First thought is to create a threshold for the joystick. Your code sets the angle even when the joystick is likely reporting Vector3.zero.
if (moveJoystick.position.magnitude > someSmallValue)
angle = $$anonymous$$athf.Atan2(moveJoystick.position.x, moveJoystick.position.y)
transform.rotation = Quaternion.Euler(new Vector3(0, angle,0));
}
Another strangeness here. Atan2() takes Y,X. That is it is ually called with something like:
angle = $$anonymous$$athf.Atan2(v3.y, v3.x);
thanks man although using: $$anonymous$$athf.Atan2(v3.y, v3.x); got me a weird movement problem. It gets messed up. Also the angle issue got fixed like: if (moveJoystick.position.x!=0){getAngle......}
Your answer
Follow this Question
Related Questions
Character Rotation 2 Answers
A node in a childnode? 1 Answer
Unity List? 1 Answer
rotating at mouse 0 Answers
Character rotation on foot? 1 Answer