Mouse To Camera is Not accurate :(

Hello! I’m trying to get an object to appear where where the mouse clicks in a 3D space. So far, I have a somewhat working solution by attaching the following script to the object I want to move with the mouse:

public class sMainTargeter : MonoBehaviour
{
    public Camera myCamera;
    void Update()
    {
        if (Input.GetMouseButtonDown(1))
        {
            Ray myRay = myCamera.ScreenPointToRay(Input.mousePosition);
            RaycastHit myHit;

            if (Physics.Raycast(myRay, out myHit)) transform.position = myHit.point;
        }
    }
}

However the position the object moves to and the position of the mouse don’t seem to be lined up. You can see the what it looks like on my screen here:

Any ideas what the problem may be?
Thank you very much for your time!

A few things I noticed in the video

  • The file you showed doesn’t line up with which component you actually have on your gameobject, the file is called sMainTargeter but the file you showed is sMoveBoxCon.
  • The file was also not saved
  • The MainCamera object wasn’t the same MainCamera as the one you dragged into the box, as one of them is MainCamera (1).

Oh sorry, honest mistake, I have edited the post code and video to correctly reflect my situation. Can you take a second look at the first post? All those issues should be resolved -

Well, your code looks fine. Though the result looks like the actual camera view is somehow mirrored on the z axis. Do you only have a single camera in your scene and the one referenced is the right one? try adding a Debug.DrawRay to your code

void Update()
    {
        if (Input.GetMouseButtonDown(1))
        {
            Ray myRay = myCamera.ScreenPointToRay(Input.mousePosition);
            Debug.DrawRay(myRay.position, myRay.direction, Color.red, 5f);
            RaycastHit myHit;
            if (Physics.Raycast(myRay, out myHit)) transform.position = myHit.point;
        }
    }

Make sure the gizmos are enabled in the sceneview. You should not see any lines in the gameview (when the gizmos are on there as well) since the ray should pass from the camera origin through the mouse coordinates (which is clearly does not when looking at the hit point). So maybe crank up the duration of the rays (5 seconds at the moment) and explore the situation in the sceneview. Maybe your referenced camera is not the actual main camera in the scene? Just click once on the myCamera field in the inspector and Unity will highlight / ping the object referenced.

Other than that printing out the ray start coordinates and maybe the name of the object the raycast hits could also help to figure out what went wrong.

1 Like

Wow, your first hypothesis was correct, I had multiply cameras, and it was taking data from the wrong camera - My problem has been solved, thank you so much for your time!!

1 Like