How can I stop my FPS camera from rotating 360 degrees?
Hello everyone, I am pretty new to coding in general and even more so in Unity. I am making an fps game and I would to limit the rotation up and down. how can I accomplish this?
here is my FPSCamera Script:
private float xRotate, yRotate;
private Quaternion cameraQuaternion;
void FixedUpdate()
{
cameraQuaternion = Quaternion.Euler (0, xRotate, 0);
GameObject.Find ("Player").transform.rotation = cameraQuaternion;
xRotate += Input.GetAxis ("Mouse X");
yRotate += Input.GetAxis ("Mouse Y");
transform.rotation = Quaternion.Euler (yRotate,xRotate,0);
}
Answer by ScaniX · Dec 29, 2016 at 03:34 PM
You could simply use Min/Max:
private GameObject player;
private float xRotate, yRotate;
void Start() {
player = GameObject.Find("Player");
}
void Update()
{
xRotate = Mathf.Min(50, Mathf.Max(-50, xRotate + Input.GetAxis ("Mouse X")));
yRotate += Input.GetAxis ("Mouse Y");
player.transform.localRotation = Quaternion.Euler(0, xRotate, 0);
transform.localRotation = Quaternion.Euler(yRotate, 0, 0);
}
Some notes:
Using localRotation is probably looking better, assuming your camera is a child of the player.
You should get the player once in the Start() method or assign it through the editor instead of calling Find() each frame.
Inputs should be processed in the Update(), not the FixedUpdate() as they are cleared per frame.
Thank you very much for responding. It worked excepted I had to change the xRotate line to the yRotate line and vice versa. $$anonymous$$any thanks though, very appreciated. private GameObject player; private float xRotate, yRotate;
void Start()
{
player = GameObject.Find("Player");
}
void Update()
{
xRotate += Input.GetAxis("$$anonymous$$ouse X");
yRotate = $$anonymous$$athf.$$anonymous$$in(50, $$anonymous$$athf.$$anonymous$$ax(-50, yRotate + Input.GetAxis("$$anonymous$$ouse Y")));
player.transform.localRotation = Quaternion.Euler(0, xRotate, 0);
transform.localRotation = Quaternion.Euler(yRotate, 0, 0);
}
You're welcome!
I see my mistake. You are using xRotate for the Y-rotation and yRotate for the X-rotation, that must have confused me. ;)
On an unrelated topic, is there any website/forums where I can post my scripts and have people give me pointers on how I can improve the script.
Did you check out the unity forums?
Answers is a place to ask for solutions to specific problems, so this is not really the right place. Unfortunately I don't know of any other place for this (as I'm pretty shy when it comes to showing my code around ^^).
Your answer
Follow this Question
Related Questions
How to rotate camera in FPS with joystick 4 Answers
How to bring UI element infront of other objects? 0 Answers
Transform.Rotate x and y rotate z, where z is 0 0 Answers
Cut viewport Rect of the camera in half 0 Answers
Rotate camera upward. 0 Answers