Prevent camera from rotating above specific angles (3D)

Updated on July 25, 2018 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
1 on July 20, 2018

Hi everyone,

I’m developing a 3D player controller, but I cannot figure out how to solve the following issue. I want my camera to stop at +/- 90 deg of rotation with respect to its local x-axis (horizontal with respect to ground), to prevent the player from rotating all the way backwards. The problem is that none of the transform.rotation, transform.eulerAngles, transform.localEulerAngles etc. actually give the same value as given in the inspector, so it gets extremely annoying to figure out how I can get the inspector rotation values. After some research, it seems I cannot unless I make my own conversion, but to do that I first have to understand what the “transform” commands return in terms of values, which is still unclear to me. I understand that quaternions return specific values unrelated to degrees, while euler angles return degrees, but measured with respect to which locations in the reference frame of interest?

If there is an easier way to implement what I’m interested in, I am open to it. I also want to point out that my camera is a child of my player and the following script controls the camera rotation and player rotation (camera rotates left/right together with player, but only the camera is able to rotate up and down) and it is attached to the player:


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerVisual : MonoBehaviour {
public Transform cameraTransform;
public int horizontalMultiplier = 1; //speed control
public int verticalMultiplier = 1;
void Start () {
Cursor.visible = false;
//get the camera gameobject. We will need it to change its vertical rotation only
void Update () {
//cameraTransform = gameObject.GetComponentInChildren(typeof(Transform)) as Transform;
float mouseInputX = Input.GetAxis("Mouse X");
float mouseInputY = Input.GetAxis("Mouse Y");
//rotate player horizontally and camera vertically
transform.Rotate(new Vector3(0, horizontalMultiplier*mouseInputX, 0));
cameraTransform.Rotate(new Vector3(-mouseInputY*verticalMultiplier, 0,0));
Vector3 dontLookUp = cameraTransform.eulerAngles;
if (dontLookUp.x > 90) //prevent camera from rotating too much. Not working.
//dontLookUp.x = 45;


The if statement doesn’t work properly since none of the transform commands is returning the wanted inspector rotation values.


Thank you all!

  • Liked by
0 on July 25, 2018


  • Liked by