Clamp camera rotation
Hi, I am new to c# coding. I have a script that I am trying to learn and add to. Basically, I want to create an additional on clamp to this script for the side to side rotation. The camera should be limited to 20 degree side to side and 20 up and down. I have tried a number of methods to no avail. I think if I can see what I need to do to this script, I can understand a bit more of the basics. I figured out how to change this script to clamp side to side, but then I lose the vertical clamp. Or I just get some strange motions.
I have 3 Gameobjects in my scene that each contains the camera. I am applying this "MouseLook" script to each of the camera that then transform the gameobject playerBody via public transform. This is the script I am using as a base; "credit to Brackeys"
Thanks for any help! Happy to trade 20 years of 3d modeling data in exchange.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseLook : MonoBehaviour
{
public float mouseSensitivity = 100f;
public Transform playerBody;
float xRotation = 0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -20f, 20f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
}
Your answer
Follow this Question
Related Questions
Camera clamps to the world scale, not local :c 1 Answer
Rotate Camera around fixed point in specified increments (Bonus: How could I lerp this?) 0 Answers
Unity 5 Player Control Movement, camera (3rd prs following) jump + gravity 0 Answers
Making a Smooth camera zoom with transform.Translate 1 Answer
I cannot move my camera in the Game mode 3 Answers