# Unity 2D Rotating Cannon to Mouse Position Inaccuracy Issue

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,

## 1 Answer

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);

• You are right. Thank you! – Eddi Oct 14 at 13:26