- Home /
how to move player forward relative to camera forward with "mouse-y" input
hi! First of all im new to scripting. I have done intense searching in the unity answers, the forum and the script reference but i can't get a solution.. I use mouse-x and mouse-y input to move a 3rdperson player. (the x & y movement of the mouse should be translated to moving the character forward, backwards, left and right) Mouse-x also give a slight rotation so you can steer the player. But rotating doesn't influence the direction of the x and z axis. So when i rotate 180 degrees and I Make a forward input, the player just moves backwards along the original and unchanged z-axis
heres my script:
function Update () {
transform.position.x -= (Input.GetAxis("Mouse X") * 0.04);
transform.position.z += (Input.GetAxis("Mouse Y") * 0.04);
transform.rotation.y -= (Input.GetAxis("Mouse X") * 0.01);
}
I know it has something to do with transform.direction but from all the examples I stumbled upon, they all work with key input * speed as input, while i have raw numbers from the x and y movement of the mouse. My scripting knowledge is to narrow to make these things compatible. Can anyone push me in the right direction? Thanks in advance, any advice will be greatly appreciated! Laurens.
Answer by tnetennba · Jun 08, 2011 at 02:41 PM
You can get the Camera's forwrad direction by using:
Camera.mainCamera.transform.forward
Am I correct in assuming that you want to move the player along the camera's direction. So you would want to do something like this:
player.transform.position += Camera.mainCamera.transform.forward * mouseYDelta;
player.transform.position += Camera.mainCamera.transform.right * mouseXDelta;
This exact code will not work but it should give you an idea of what to do.
Yup, thank you for pointing it out! Script works like a charm now. I also fixed the rotation part. transform.rotation.y -= (Input.GetAxis("$$anonymous$$ouse X") * 0.01); wouldn't let me steer more then 180° So ins$$anonymous$$d I used eulerAngles which allowed me to go over 180° without running into issues.
Heres my working script:
function Update () {
transform.position -= Camera.mainCamera.transform.right *(Input.GetAxis("$$anonymous$$ouse X")*0.03);
transform.position += Camera.mainCamera.transform.forward *(Input.GetAxis("$$anonymous$$ouse Y")*0.03);
transform.eulerAngles.y -= (Input.GetAxis("$$anonymous$$ouse X"));
}
Thanks again!
Your answer
Follow this Question
Related Questions
Relative Rotation 1 Answer
Rigid Body relative speed 1 Answer
3rd person camera 1 Answer
Third Person Camera on a speherical world 2 Answers
Switching between cameras 4 Answers