- Home /
When i look around in my FPS my controls get inverted and rotate with the camera!!!,
while i was making my fps in unity 2019.4.17f1 i stumbled upon a problem, when i turned around my movement controls got flipped according to the axis i was looking at. Here is the code (i used a brackeys tutorial so there is a look script and a movement script). Movement Script: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerMovement : MonoBehaviour { public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
public float jumpHeight = 3f;
public Transform GroundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(GroundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
Looking Script: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class MouseLook : MonoBehaviour { public float mouseSpeed = 100f; public Transform playerBody; float xRotation = 0f; float yRotation = 0f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSpeed * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSpeed * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
yRotation += mouseX;
transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0f);
}
}
Answer by VoidPhoenix96 · Feb 13, 2021 at 12:12 AM
I think the problem might be in your camera script. You added yRotation += mouseX
I don’t see that in brackeys’ script In the video.
Answer by $$anonymous$$ · Feb 13, 2021 at 01:24 AM
Just with a quick glance, I see you may want/need to base your movement off the camera's rotation. If so, try making a variable for your MouseLook script at the top of your 'PlayerMovement' script and get reference to it via inspector or assigning it at the start:
MouseLook mouseLook;
Start(){
mouseLook = FindObjectOfType<MouseLook>(); //or something like this, so it isn't null
}
then, you can modify that move calculation after the fact and apply the camera's rotation, like so:
...
Vector3 move = transform.right * x + transform.forward * z;
move = mouseLook.transform.rotation * move; // <--- add this
controller.Move(move * speed + Time.deltaTime);
...
I hope this helps / is somewhat what you were looking for.