Turret rotation to look in the direction of the mouse

Hello everyone,

So I am attempting to rotate my turret to face the mouse cursor point in front of the ship calculated this way:

Vector3 mousePos = Input.mousePosition;
mousePos.z = transform.position.z + 200f;
Vector3 point = Camera.main.ScreenToWorldPoint(mousePos);

The Debug.DrawLine() shows the point being in front of the ship correctly.

In order to rotate my turret to face that point I use first heading rotation for the stand of the turret and then pitch rotation for the gun part I have learned from here.

This is the code:

public void AimAt(Vector3 target) { 
//Move stand(heading) 
Vector3 lookDir = target - transform.position; 
float standDeg = Mathf.Rad2Deg * Mathf.Atan2(lookDir.x, lookDir.z); 
transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x, standDeg, transform.rotation.eulerAngles.z); 
//Move the gun(pitch) 
float deg = Mathf.Rad2Deg * Mathf.Asin(-lookDir.y / lookDir.magnitude); 
if (deg > 0) return; 
Gun.transform.rotation = Quaternion.Euler(deg, Gun.transform.rotation.eulerAngles.y,Gun.transform.rotation.eulerAngles.z); 
}

The problem is that it looks like the turret is aiming to opposite directions(or aiming at literal mouse cursor) behind the ship instead of in front of it.

Does anyone know what am I doing wrong here?

RotationIssue

Fixed the issue… I have put Vector2 inside of function argument instead of Vector3…

Watch your naming people!

1 Like