I am looking for a way to lock the camera position in game while still being able to move the mouse.
So the idea here is the player will be able to move around the world using the movement keys, and look around using the mouse. I want to press a key (lets say the ‘Z’ key) and hold it down, so that it will keep the camera locked and framed in position. The mouse will still be able to move around in view, but will not rotate the player. Once the player releases the ‘Z’ key, the player is able to freely move once again. Making it so that the player will be able to interact with a puzzle, but not have the camera shift side to side as you move the mouse around the puzzle area.
Using a first person controller from the unity store, as I am still a beginner to code.
Here is the code I am working with:
public class HeroController : MonoBehaviour
{
public float MoveSpeed = 30f, JumpForce = 200f, Sensitivity = 70f;
CharacterController character;
Rigidbody rb;
Vector3 moveVector;
Transform Cam;
float yRotation;
Camera camera;
void Start()
{
character = GetComponent<CharacterController>();
rb = GetComponent<Rigidbody>();
Cam = Camera.main.GetComponent<Transform>();
Cursor.lockState = CursorLockMode.Locked; // freeze cursor on screen centre
Cursor.visible = false; // invisible cursor
}
void Update()
{
// camera rotation
float xmouse = Input.GetAxis("Mouse X") * Time.deltaTime * Sensitivity;
float ymouse = Input.GetAxis("Mouse Y") * Time.deltaTime * Sensitivity;
transform.Rotate(Vector3.up * xmouse);
yRotation -= ymouse;
yRotation = Mathf.Clamp(yRotation, -85f, 60f);
Cam.localRotation = Quaternion.Euler(yRotation, 0, 0);
}
void FixedUpdate()
{
// body moving
moveVector = transform.forward * MoveSpeed * Input.GetAxis("Vertical") +
transform.right * MoveSpeed * Input.GetAxis("Horizontal") +
transform.up * rb.velocity.y;
rb.velocity = moveVector;
}