- Home /
How to limit object rotation?
I'm rotating my object with Mouse Drag, and limited its rotation at certain angle, I can rotate it on counter clockwise
but i cant rotate it the oppisite direction (clockwise) somthing like this
How can I be able to rotate it on both direction but with limiting at certain angle like both images???
the following code is attached with object...`
public class MouseDrag : MonoBehaviour
{
private float baseAngle = 0.0f;
private float maxRotaion = 60f;
void Start()
{
}
void OnMouseDown ()
{
var dir = Camera.main.WorldToScreenPoint (transform.position);
dir = Input.mousePosition - dir;
baseAngle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
baseAngle -= Mathf.Atan2(transform.right.y, transform.right.x) * Mathf.Rad2Deg;
}
void OnMouseDrag ()
{
// Limit platform rotation
if (transform.rotation.eulerAngles.z <= maxRotaion ) {
var dir = Camera.main.WorldToScreenPoint (transform.position);
dir = Input.mousePosition - dir;
var angle = Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg - baseAngle;
transform.rotation = Quaternion.AngleAxis (angle, Vector3.forward);
}
}
on the rigidebody component there is constraints I don't know if it works the same in 2d as 3d, but with a limitation of position and rotation it can be done without code right there.
thanks for the reply ..my platform has no rigidbody attached .. @Radivarig answer works fine.. :)
Answer by Radivarig · Jul 10, 2014 at 03:36 AM
// Limit rotation
void OnMouseDrag (){
var dir = Camera.main.WorldToScreenPoint (transform.position);
dir = Input.mousePosition - dir;
var angle = Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg - baseAngle;
if (angle >= -maxRotaion && angle <= maxRotaion)
transform.rotation = Quaternion.AngleAxis (angle, Vector3.forward);
}
Cheers, Radivarig
Your answer
![](https://koobas.hobune.stream/wayback/20220613153643im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Rotating the game object with direction of mouse move 0 Answers
Rotating sprite with mouse 0 Answers
2D Mouse Drag and Rotate Object Problem 1 Answer