Gun should point at mouse position

I’m using this code but the rotation is all messed up. How can I get my gun to point wherever my mouse is pointing?

using UnityEngine;
using System.Collections;

public class GunRotate : MonoBehaviour
{
    private void Update()
    {
        Vector3 mousePos = Input.mousePosition;
        transform.LookAt(Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, Screen.height - mousePos.y, 10.0f)));
        transform.rotation = new Quaternion(0, 90, transform.rotation.z, transform.rotation.w);
    }
}

What I want is the gun’s z axis to be pointing/facing the mouse position so that it’s looking at wherever the mouse position is on the camera. Here’s what I get currently.

Quaternions confuse me. Why not just use Euler’s Angle?

I don’t have much knowledge about maths, could you please show me how to do it with euler’s angle?

transform.eulerAngles = Vector3(0, 0, degree);

this simply sets the transform’s rotation to degree on the z axis.

I tried it but it still not working. The gun doesn’t now rotate around the camera.

Well,
In your original code you are affecting the transforms rotation twice. That seems odd. Why not just use one, LookAt or Eulers/quarternion?

It would be something like this:

Vector3 mousePos = Input.mousePosition;
Vector3 world_point = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 10.0f));
transform.LookAt(world_point);

I don’t know why you were doing Screen.height - mousePos.y
Also you are already telling it to look at the point, you don’t need to set the rotation again after that.

This may not work 100% because I just typed this into the Quick Reply box. May have to be slightly tweaked to your liking.

About the screen height, I was just playing with some stuff. It doesn’t seem to work either and the result is same as before.

try:

Vector3 mousePos = Input.mousePosition;
Vector3 forward = transform.forward * 10f;
Vector3 world_point = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 0f) + forward);
transform.LookAt(world_point);

I am thinking that its not looking “forward”, so thats why we need to find the forward vector for the transform them increase it (*10) so that it is actually looking at something.

Well still same problem. How can you limit axis and just change the z axis?