Answer the question
In order to leave comments, you need to log in
How to limit the rotation of an object in Unity?
I have a 2d character on which a gun object weighs, the gun is pointing towards the mouse. I need to limit the rotation of the gun.
Code for gun:
void Update ()
{
var mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
var angle = Vector2.Angle(Vector2.right, mousePosition - transform.position);
transform.eulerAngles = new Vector3(0f, 0f, transform.position.y < mousePosition.y ? angle : -angle);
}
Answer the question
In order to leave comments, you need to log in
i solved the problem.
Code:
void Update ()
{
var mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
mousePosition.y = Mathf.Clamp(mousePosition.y, zMiN, zMAX);
var angle = Vector2.Angle(Vector2.right, mousePosition - transform.position);
transform.eulerAngles = new Vector3(0f, 0f, Mathf.Clamp(transform.position.y < mousePosition.y angle : -angle, zMiN, zMAX));
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question