- Home /
limit camera vertical rotation
can you please help me with limiting camera's vertical rotation with my code? heres the code:
using System.Collections; using System.Collections.Generic; using UnityEngine;
[RequireComponent(typeof(PlayerMoto))] public class PlayerController : MonoBehaviour {
public float speed = 5, sensetivity;
private PlayerMoto motor;
public GameObject hands;
public camera cam;
// Start is called before the first frame update
void Start()
{
motor = GetComponent<PlayerMoto>();
cam = GetComponent<camera>();
}
// Update is called once per frame
void Update()
{
//cam.transform.localEulerAngles = new Vector3(cam.transform.localEulerAngles.x, 0, 0);
float _xmove = Input.GetAxis("Horizontal");
float _zmove = Input.GetAxis("Vertical");
Vector3 _moveHorizontal = transform.right * _xmove;
Vector3 _movVertical = transform.forward * _zmove;
Vector3 _velocity = (_moveHorizontal + _movVertical) * speed;
motor.Move(_velocity);
float _yRot = Input.GetAxis("Mouse X");
Vector3 _rotation = new Vector3(0f, _yRot, 0f) * sensetivity;
motor.Rotate(_rotation);
float _xRot = Input.GetAxis("Mouse Y");
Vector3 _cameraRotation = new Vector3(_xRot, 0f, 0f) * sensetivity;
motor.RotateCamera(_cameraRotation);
if (Input.GetKey(KeyCode.LeftShift) && Input.GetKey(KeyCode.W)) {
for (; speed <= 15; speed++)
{
speed = 15;
}
}
else
{
speed = 10;
}
}
}
Answer by JonPQ · Aug 09, 2019 at 11:32 PM
Simple limiting using the camera look forward vector...
float lookUpMax = .6f; //cosine of angle (0.0 to 1.0)
if ( Cam.forward.y > lookUpMax )
{
Cam.forward.y = lookUpMax;
Cam.forward.normalize();
}
//then do same for look down angle, you can have a different threshold, just check against -ve forward.y
Note:- this will work if your angle delta is not too much from frame to frame ( limit your max Y rotation speed) if you want unlimited Y rotation speed, you'll need to convert angles to euler... then limit those, and convert back to quaturnions.
what is those "Cam"? maybe you mean my camera ("public camera cam") so it doesn't take the attribute "forward". if you would help me it would be amazing