- Home /
How to use mathf.clamp?
My look script works fine, but you can look upside down.
float v = Sens * Input.GetAxis("Mouse Y");
v = Mathf.Clamp(v, -80, 80);
CamQuar.Rotate(-v, 0, 0);
float h = Sens * Input.GetAxis("Mouse X");
CamQuar.RotateAround(PlayerQuar.position, Vector3.up, h);
it doesn't return any errors and runs fine in unity, but you can still turn all the way around. I have no idea why it wont do anything.
Answer by Spip5 · Nov 16, 2020 at 09:04 PM
The Mathf does work in your example, but you are missing the logic of what you have written here :). What you did here is to clamp the amount by which you rotate, not lock the rotation.
Transform.Rotate() is different than Transform.rotation or Transform.eulerAngles. Rotate() will rotate by the amount you give (even if Clamped, it keeks on rotating by the clamped values you gave it. Try to put it in the Update loop to see the result). In the other hand rotation and eulerAngles define the actual rotation of your object.
You need something that will look like this :
float v = Sens * Input.GetAxis("Mouse Y");
Transform.eulerAngles = new Vector3(mathf.Clamp(v,-80,80),0,0);
I havn't ried it out, but I am pretty convinced this should work you want you intend it to !
This, unfortunately does not work for me. It turns correctly for 1 frame before snapping back to 0, 0, 0 rotation.
That's because I have no clue what you are looking for. If it is FPS-like, then it should look like this. Edit : missed a +=
float v;
Update()
{
if(Input.GetAxis("$$anonymous$$ouse Y") != 0) {
{
v += Sens * Input.GetAxis("$$anonymous$$ouse Y")
}
Transform.eulerAngles = new Vector3(mathf.Clamp(v,-80,80),0,0);
}
Yes it is in first person, and with the new script im having the same problem, but instead of snapping to 0 rotation, it smoothly transitions to it.
Answer by myzzie · Nov 16, 2020 at 08:54 PM
You're applying rotation rather than setting it. Had you debugged the v value you'd seen that it's only ever what value Sens have multiplied by -1 or 1. So every frame you're applying a rotation of a fixed x value;
edit:
public float sensitivity;
private float x;
private float y;
x += sensitivity * Input.GetAxis("Mouse X");
y += sensitivity * Input.GetAxis("Mouse Y");
y = Mathf.Clamp(y, -80, 80);
camera.transform.rotation = Quaternion.Euler(-y, x, 0);
I included the y axis but I'm guessing you rotate the body around y and only the camera around x axis.
Your answer
Follow this Question
Related Questions
How to clamp character rotation on Y and X axis? 1 Answer
3D top down rotation 1 Answer
How to Clamp a Quaternion Camera Rotation? 0 Answers
How to clamp rotation of an object? 2 Answers
Clamped rotation of turret problem 0 Answers