- Home /
Clamp rotation value.
I have a 3D object that rotates according to mouse position, but I want to clamp it so it doesn't get further or lower than certain values. Here is my code:
void LookAt () {
float distance = transform.position.z - Camera.main.transform.position.z;
Vector3 position = new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance);
position = Camera.main.ScreenToWorldPoint(position);
position.x = Mathf.Clamp(position.x, -70, 70);
position.z = Mathf.Clamp(position.z, -70, 70);
Vector3 target = new Vector3 (position.x, transform.position.y, position.z); // Use current object positin.y
transform.LookAt(target);
}
But unfortunately it doesn't work, it keeps rotating 360.
Edit: I tried this and partially worked, I changed this line :
Vector3 position = new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance);
To this:
Vector3 position = new Vector3(Mathf.Clamp( Input.mousePosition.x, Input.mousePosition.y, distance), 350, 40);
It now locks perfectly on the left side, but not on the right side, tried playing with the values but didn't succeed.
There doesn't seem to be any code that pertains to rotation other than transform.LookAt(), which is the last thing you do so even if there where the only rotation you would see would be the one calculated by transform.LookAt().
I used something simlar a while ago, where i wanted to bank/tilt my spaceship. This might help you out:
public float ztilt = 1.0f;
void Update()
{
rigidbody.rotation = Quaternion.Euler (0.0f, 0.0f, rigidbody.velocity.x * ztilt);
}
you just need to find the right axises. in this case, x and y are not affected.
Edit: the rigidbody.velocity for my ship was calculated like this:
rigidbody.velocity = movement * CameraSpeed;
you want to calculate it on you mouse or whatever. Hope it helps somehow.
Problem is, my object doesn't have a rigidbody and i don't need it. $$anonymous$$y codes runs fine, it's just a matter of where to or which value t oexactly clamp.
Hi, using Debug.Drawline or Drawray usually helps a lot to figure out what happens in those kind of situations.
Your answer
Follow this Question
Related Questions
How to use mathf.clamp? 2 Answers
How to Clamp a Quaternion Camera Rotation? 0 Answers
Bizzare problem with limiting camera veritcal rotation 2 Answers
Clamping Vector3 2 Answers
How to clamp rotation in degrees in relation to another GameObject 1 Answer