Hello, I am very new to programming in Unity and programming in general, so please forgive me if I don’t describe my question very well or if I ask extremely nooby questions.
I’ve set up an FPS player controller that moves using WASD, and can also look around using a mouse look script. I used a transformdirection so that, for example, if I look to the left and press W, I will move forward in that direction. The problem is that it does this on all three axis x y and z. I only want this to occur when looking left, right, or forwad. (X and Z I think, but correct me if I’m wrong.) What I don’t want is to move upwards if I’m looking up or downwards if I’m looking down (Y axis)
So using the script I have, how can I make it so I move forwards where I’m looking that isn’t up or down relative to the world?
Also since I’m very new to coding, if I have any problems with my script or if it’s using some bad practices that I’m unaware of please let me know.
Here’s my code:
// Use this for initialization
void Start ()
{
controller = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update ()
{
//WASD movement
if(controller.isGrounded)
{
movement = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
movement = transform.TransformDirection(movement);
movement *= speed;
}
controller.Move(movement * Time.deltaTime);
movement.y -= gravity * Time.deltaTime;
//Mouse Look
if (axes == RotationAxes.MouseXAndY)
{
float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX * Time.deltaTime;
rotationY += Input.GetAxis("Mouse Y") * sensitivityY * Time.deltaTime;
rotationY = Mathf.Clamp(rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
}
else if (axes == RotationAxes.MouseX)
{
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX * Time.deltaTime, 0);
}
else
{
rotationY += Input.GetAxis("Mouse Y") * sensitivityY * Time.deltaTime;
rotationY = Mathf.Clamp(rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0);
}
if (lockCursor)
{
Cursor.lockState = CursorLockMode.Locked;
}
//transform.Rotate(Input.GetAxis("Mouse Y") * new Vector3(sensitivityY, 0, 0) * Time.deltaTime);
if (lockCursor)
{
Cursor.lockState = CursorLockMode.Locked;
}
}
}
`