- Home /
 
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, mousePos.y, 10.0f)));
         transform.rotation = new Quaternion(0, 90, transform.rotation.z, transform.rotation.w);
     }
 }
 
              Answer by phxvyper · Dec 25, 2012 at 12:29 AM
The issue is most likely because Mouse Position is recorded differently than screen position. This is very simple to fix.
When you call Screen to World, just subtract the y position from the height of the screen like so:
 transform.LookAt(Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, Screen.height - mousePos.y, 10.0f)));
 
              Answer by topaz7 · Dec 25, 2012 at 05:17 PM
Thank you for your response. I will keep that in mind but actually I think I didn't elaborate my problem well. What I want is the gun rotation z to be pointing at the cursor y. In other words, the gun to be aiming at the mouse. The solution you gave me still makes the gun rotation messed up. Here's a picture for your reference. Another thing I could add is that my gun is already rotated on y axis in 90 degrees. Thanks again.

Answer by topaz7 · Dec 25, 2012 at 05:16 PM
I already response it but seems like the moderators removed it for some reason. Thank you for your response and let me elaborate it better. 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.
 
Your answer