Hierarchy:
-Character (GameObject)-> has an idependent controller script so it rotates independently of the camera’s rotation. No problem.
-Camera Rotator (empty Gameobject)-> has a camera rotation script based on the input of the mouse.
-Main Camera
Sorry, I am a beginner in Unity :((joined in 2018 but started learning this month), and programming.
This is the code component of the Empty GameObject called Camera Rotator:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraRotScript : MonoBehaviour
{
float rotX;
float rotspeedY = 100.0f;
float rotspeedX = 100.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
rotX = transform.eulerAngles.x;
//to avoid problems with negative rotation values, I add +360 to a negative value.
if (rotX < 0)
{
rotX += 360;
}
//ROTATE CAMERA ROTATOR AROUND THE Y AXIS!
if (Input.GetMouseButton(1))
{
transform.Rotate(0, Input.GetAxis("Mouse X") * rotspeedY * Time.deltaTime, 0);
}
//ROTATE CAMERA ROTATOR AROUND THE X AXIS!
if (Input.GetMouseButton(1))
{
if (rotX > 310 || rotX < 40)
{
transform.Rotate(Input.GetAxis("Mouse Y") * rotspeedX * Time.deltaTime, 0, 0);
}
}
}
}
(^ I do the same for the rotation around the Y axis but I don’t want to limit it, so it’s out of question.)
This code is to rotate the Camera Rotator so its child, the Main Camera(where I have already inserted a
script to LookAt the rotator), also gets rotated. The problem is, I want to limit its rotation to -60 and 60.
I have tried many different ways to do that. The answers of similar questions the internet are a bit confusing for me, it’s like they are answering people who have been programming for some time on the engine.
My most successful but still not desired result was obtained by adding +360 in case the float transform.eulerAngles.x<0, and using conditions of transform.eulerAngles.x>300 and transform.eulerAngles.x<60 for the camera to be able to be rotated. But the camera just freezes in the boundaries… and another problem: if I shake the mouse too much, its “deltas” will be so big that the X rotation will get to something like 100 or even more, which is undesirable.
Is the problem the hierarchy? Or the way I’m using the input, so the shaking throws a very high value of the Mouse Y input? What about the boundaries freezing forever instead of just limiting? I don’t know if this is common with beginners but at this rate I’m starting to think I’m just throwing random stuff at my code until it somehow works… if I need to rewrite THE WHOLE CODE, I WILL, but, please, help!