N
N
ne_Sci_fi2019-05-18 13:15:12
C++ / C#
ne_Sci_fi, 2019-05-18 13:15:12

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

2 answer(s)
S
Sergey Ivanov, 2019-05-18
@keksmr

mousePosition.y = Mathf.Clamp(mousePosition.y, min, max);

N
ne_Sci_fi, 2019-05-18
@ne_Sci_fi

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 question

Ask a Question

731 491 924 answers to any question