I am trying to rotate a 2D cannon to clicked mouse position and having accuracy issue. It's working but the angle seems to be losing more and more accuracy when I move the mouse to further up or down position.

Here's my code,

void Update()
        if (Input.GetMouseButtonDown(0)) 
                // display a test cannon ball on mouse location
                Vector2 BallPos = MainCam.ScreenToWorldPoint(Input.mousePosition);
                TestBall.transform.position = BallPos;

                var p2 = MainCam.ScreenToViewportPoint(Input.mousePosition);
                var p1 = MainCam.WorldToViewportPoint(Cannon.transform.position);
                var p3 = p2 - p1;

                var angle = Mathf.Atan2(p3.y, p3.x) * Mathf.Rad2Deg;
                RotAngle = Quaternion.AngleAxis(angle, Vector3.forward);
                Cannon.transform.rotation = RotAngle;

And attached screenshot below, enter image description here

enter image description here

enter image description here


From what I understand the fact to compute your angle on Viewport space messes everything up due to origins. If you do your computation on Screen space everything will work just fine.

Update your code with this:

            var p2 = Input.mousePosition + Vector3.forward * transform.position.z;
            var p1 = Camera.main.WorldToScreenPoint(transform.position);
  • \$\begingroup\$ You are right. Thank you! \$\endgroup\$ – Eddi Oct 14 '19 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.