I am making a 3d side scroller. need to rotate gun on z axis to face mouse on x,y plane. This is What I have so far. Tried lookat and angle. They sort of worked but would not point correctly. only half of the screen. I just think I am missing something.
void FixedUpdate()
{
screenPosition = Input.mousePosition;
screenPosition.z = 1; //mainCamera.nearClipPlane 1;
worldPosition = mainCamera.ScreenToWorldPoint(screenPosition);
worldPosition.z = 0;
//Angle?????
transform.rotation = Quaternion.Slerp(rb.transform.rotation,
Quaternion.Euler(0,0,angle), 0.7f);
}
CodePudding user response:
In order to get the angle there is no need to convert to world space.
Indeed actually it is way easier to go the other way round and convert your objects position into screen space.
Then you can simply use the Mathf.Atan2
on the pixel space delta
var mousePosition = Input.mousePosition;
var objectScreenPosition = mainCamera.WorldToScreenPoint(rb.position);
var direction = mousePosition - objectScreenPosition; // No need to normalize btw
var angle = Mathf.Atan2(direction.x, direction.y) * Mathf.Rad2Deg;
// since this seems to be a rigidbody I would rather use this
rb.MoveRotation(Quaternion.Slerp(rb.rotation, Quaternion.Euler(0, 0, angle), 0.7f);
// NOTE: Or in case your rb is actually Rigidbody2D then rather simply
rb.MoveRotation(Mathf.Lerp(rb.rotation, angle, 0.7f));