- Home /
Help with rotation!
Hello. I have a problem. My character has a character controller applied on him. I have a script to make the character move and rotate. It rotates when i slide the mouse left and right. But i want to make that the character moves when you have the mouse cursor in front of him, that it turns to the direction the cursor is pointing. Help me out please! The script:
pragma strict
var rotationSpeed : float = 10; var walkSpeed : float = 7; var gravity : float = -50; private var yRot : float; var body : Transform;
function Start () {
}
function Update () { var Controller : CharacterController = GetComponent(CharacterController); var vertical : Vector3 = transform.TransformDirection(Vector3.forward); var horizontal : Vector3 = transform.TransformDirection(Vector3.right); var height : Vector3 = transform.TransformDirection(Vector3.up);
if(Input.GetKeyDown("space")){
animation.CrossFade("Jump", 0.1);
Jump();
}else{
animation.CrossFade("Idle", 0.1);
}
if(Input.GetAxis("Vertical") || Input.GetAxis("Horizontal")){
animation.CrossFade("Walk", 0.1);
Controller.Move((vertical * (walkSpeed * Input.GetAxis("Vertical"))) * Time.deltaTime);
Controller.Move((horizontal * (walkSpeed * Input.GetAxis("Horizontal"))) * Time.deltaTime);
}else{
animation.CrossFade("Idle", 0.1);
}
if(Input.GetAxis("Mouse X")){
yRot += 10 * Input.GetAxis("Mouse X");
}
transform.rotation = Quaternion.Euler(0, yRot, 0);
Controller.Move(height * gravity * Time.deltaTime);
}
function Jump(){
gravity = 10;
yield WaitForSeconds(0.2);
gravity = -20;
yield WaitForSeconds(0.3);
gravity = -30;
yield WaitForSeconds(0.3);
gravity = -40;
yield WaitForSeconds(0.3);
gravity = -50;
yield WaitForSeconds(0.3);
gravity = -60;
}
I think you should use the pythagorean theorem to get the angle between transform.position.x and $$anonymous$$ouse.x(?) and rotate accordingly.
Not entirely sure what you want to do... You want the player to rotate towards the mouse and when it has rotated you want it to start moving towards the mouse? But if so, why do you have "if(Input.GetAxis("Vertical") || Input.GetAxis("Horizontal"))"?
EDIT: With pythagorean theorem I ofcourse mean trigonometry. First of all you would have to set up 4 different "If"-statements to deter$$anonymous$$e which quadrant the position of the mouse is in relative to the player. After that you would have to use e.g. arctan to get the angle between the player and the mouse and after that rotate accordingly.
For Vector3, consider these functions:
http://docs.unity3d.com/ScriptReference/Vector3.RotateTowards.html
http://docs.unity3d.com/ScriptReference/Vector3.$$anonymous$$oveTowards.html
Your answer
Follow this Question
Related Questions
Third Person Character Controller Movement 1 Answer
Screen.lockCursor messes my rotation 1 Answer
Smoothly Rotate Character Y to Camera Y 2 Answers
Look On Cursor Problem 1 Answer
Create sprite in place of cursor that has 'lag' on it? 0 Answers