Hey Everybody, I’m trying to make an angry birds knock off I was wondering if I can get some help?
void Update () {
Vector3 mouseInWorld = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 5f));
Vector3 direction = mouseInWorld - transform.position;
Quaternion rotation = Quaternion.LookRotation(direction);
transform.rotation = new Quaternion(0, 0, rotation.z, rotation.w);
}
This Code makes my cannon rotate by moving my mouse. I want to limit the rotation of my cannon. I don’t want the cannon to fire directly up or directly down.
Yikes! I don’t know what you think you’re doing with that last line, but it’s not valid. You can’t just pick apart a Quaternion like that. (What you’ve created here is a non-unit quaternion, which does not represent a pure rotation… mathematically, it’s sheer madness.)
Right, so what you want to do instead is something like this:
void Update() {
Vector2 meOnScreen = Camera.main.WorldToScreenPoint(transform.position);
float angleToMouse = Vector2.Angle(Vector2.right, (Vector2)Input.mousePosition - meOnScreen);
angleToMouse = Mathf.Clamp(angleToMouse, 5, 85); // limit as desired
transform.rotation = Quaternion.Euler(0, 0, angleToMouse);
}
Let me know if it’s not clear how this works (or if, for some reason, it doesn’t work for you!).
1 Like
Did you try to clamp the rotation of the cannon using the Inspector?