How to make the players gun point and shoot in the direction of the game object “crosshairs” C# ?

Ok so I have been working on this for a few days now looking up tutorials and unity answers but none have really helped,
So I’m building a 2D sidescroller like Mario it’s all sprite based I created a crosshairs game object and attached it to the mouse curser that works fine the problem is I can’t seem to figure out how to make the gun rotate on the z axis to align up with the crosshairs (the gun is attached to the player so that it move with the player) also if I could somehow restricted the allowed angle on the gun so that it will not clip threw the player something like a 180 degree angle or something I’m very new to coding

I’m writing In C#
please any help would be very much appreciated
thank you

Try using Transform.LookAt in an Update function on your gun and set the target to your crosshairs. From there you can then limit the rotation of the object. If the rotation is within your maximum and minimum rotation, then all transform.LookAt to do it’s thing. If the rotation is above or below the limits, set it to the closest limit and then stop the transform.LookAt.

Here is a bit of code. I assumes that your gun is a sprite and that the sprite is oriented so that the gun forward is on the right side of the sprite. I’m unsure of what restriction you want on the rotation. Vector3.right is zero angle, and the angle ranges from -180 to 180. I’ve restricted the rotation to the right side in this code:

#pragma strict

function Update () {
    var pos = Camera.main.WorldToScreenPoint(transform.position);
    var dir = Input.mousePosition - pos;
    var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
	
	if ((angle >= 0.0 && angle <= 90.0) || (angle <= 0.0 && angle >= -90.0))
    	transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward); 
}