- Home /
I reworked my code to try to get around this.
Clamping Vector3
I'm trying to clamp a Vector3 in Unity3D C#, and it the code isn't doing anything. Any tips?
Code:
Vector3 rot = new Vector3(-Input.GetAxis("MouseY"), Input.GetAxis("MouseX"), 0);
rot.y = Mathf.Clamp(rot.y, -clampAngle, clampAngle);
transform.Rotate(rot * Time.deltaTime * mouseSensitivity);
Wait you're just trying to clamp the transform's rotation? Right now, you're clamping the rotation the transform will experience, but not how the transform will appear after that rotation.
You want something closer to:
// $$anonymous$$ouse rotation
Vector3 rot = new Vector3 (-Input.GetAxis ("$$anonymous$$ouseY"), Input.GetAxis ("$$anonymous$$ouseX"), 0);
// Assign the rotation
this.transform.Rotate (rot);
// Get whatever its new rotation is
Vector3 resulting = this.transform.rotation.eulerAngles;
// Clamp that y-component
resulting.y = $$anonymous$$athf.Clamp (resulting.y, -clampAngle, clampAngle);
// Then reassign the clamped rotation
this.transform.rotation = Quaternion.Euler (resulting);
Yeah it always helps to be specific about what you are trying to do: limit the end rotation of the object or the rotation speed.
Answer by MattG54321 · Jul 24, 2017 at 07:15 PM
Try putting in Debug.Log and seeing what it says, like this:
Vector3 rot = new Vector3(-Input.GetAxis("MouseY"), Input.GetAxis("MouseX"), 0);
rot.y = Mathf.Clamp(rot.y, -clampAngle, clampAngle);
Debug.Log(rot.y);
transform.Rotate(rot * Time.deltaTime * mouseSensitivity);
It just comes back with a number from about -4 to 4 with a couple outliers getting nearer to -12 and 12.
What is clampAngle set to? Is Input.GetAxis("$$anonymous$$ouseX") working properly?
All of the movement works properly, and clampAngle is set to 80.
Answer by MattG54321 · Jul 25, 2017 at 12:45 PM
My hunch right now is that Input.GetAxis("MouseX") is simply never returning a value greater than 80 or less than -80 because the mouse is never moving fast enough. Try clamping it after you've multiplied it by mouseSensitivity
, like this:
Vector3 rot = new Vector3(-Input.GetAxis("MouseY"), Input.GetAxis("MouseX"), 0);
rot = rot * mouseSensitivity;
rot.y = Mathf.Clamp(rot.y, -clampAngle, clampAngle);
transform.Rotate(rot * Time.deltaTime);
Follow this Question
Related Questions
Clamp gyro rotation 0 Answers
Limit Rotation of physics object in 2D 1 Answer
Camera Clamping Third Person? 0 Answers
Clamping rotation of an object 0 Answers