- Home /
Clamp Vertical Aiming
So I'm making a first person controller, and this code is my camera aiming code: But I can still aim 360 degrees around verticaly... How would I clamp the vertical rotation of the camera?
public float mouseSensitivity = 5;
public float rotVertical = 0;
public float viewRange = 60;
Transform cameraTransform;
void Start () {
cameraTransform = Camera.main.transform;
}
void Update () {
//Camera
float rotHorizontal = Input.GetAxisRaw ("Mouse X") * mouseSensitivity;
transform.Rotate (0, rotHorizontal, 0, Space.World);
rotVertical = Input.GetAxisRaw ("Mouse Y") * mouseSensitivity;
cameraTransform.localRotation *= Quaternion.Euler (-rotVertical, 0, 0);
}
Answer by baboca · Dec 17, 2017 at 07:43 PM
You have to clamp the value of rotVertical between the angles that you want your player to rotate to. This will set the minimal and the maximal value that it can reach.
void Update () {
//Camera
float rotHorizontal = Input.GetAxisRaw ("Mouse X") * mouseSensitivity;
transform.Rotate (0, rotHorizontal, 0, Space.World);
rotVertical = Input.GetAxisRaw ("Mouse Y") * mouseSensitivity;
rotVertical = Mathf.Clamp(rotVertical, minimalRotation, maximalRotation);
cameraTransform.localRotation *= Quaternion.Euler (-rotVertical, 0, 0);
}
The variable rotVertical is the amount the camera should change every frame. For example, if I'm not moving my mouse, it's 0. Clamping that would just set a $$anonymous$$ and max turning speed. So how would I clamp the final rotation?
Then you need to clamp the rotation of the object with $$anonymous$$athf.Clamp(), not the force rotating it.
transform.rotation.y = $$anonymous$$athf.Clamp (transform.rotation.y, float $$anonymous$$Angle, float maxAngle);
That is if you are rotating around y, otherwise just change it.
If that dosent work try using Quaternions ins$$anonymous$$d of floats, and transform.rotation without specifying the direction of the rotation, that way you can do:
transform.rotation = $$anonymous$$athf.Clamp(transform.rotation, Quaternion $$anonymous$$, Quaternion max);
You can use Vector3 to specify the angle ins$$anonymous$$d of quaternions, but then you have to convert it using Quaternion.Euler
You can't set a single axis rotation by using "transform.rotate.y =". Otherwise I would have done that already.
Your answer
Follow this Question
Related Questions
How do I make a gun aim down sights? 2 Answers
How to delete prefabs without warning popping up? 0 Answers
Aiming Down Sights Problem 2 Answers
Aiming down a gun 1 Answer
Aiming Gun at Cursor 2 Answers