Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

[RESOLVED] Camera.main.ScreenToWorldPoint always returns the position of the camera

Discussion in 'Scripting' started by m4ker, Dec 12, 2019.

  1. m4ker

    m4ker

    Joined:
    Nov 26, 2019
    Posts:
    3
    Ok so I have a following script attached to my object:

    Code (csharp):
    1.  
    2. private void OnMouseDown()
    3.     {
    4.         Vector3 mousePos;
    5.         mousePos = Input.mousePosition;
    6.         Debug.Log("C1: " + mousePos.ToString());
    7.         mousePos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 0.0f));
    8.         Debug.Log("C2: " + mousePos.ToString());
    9.     }
    10.  
    When I click the object, the first debug returns sensible numbers, and seems to work. However, the second always returns the position of the main camera, and nothing else. Anyone knows what am I doing wrong? Thanks!
     
    mikeiavelli likes this.
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,749
    That's because your third parameter is 0. The third parameter means "distance from the camera", so naturally if the distance from the camera is 0 it must be the position of the camera.
     
  3. m4ker

    m4ker

    Joined:
    Nov 26, 2019
    Posts:
    3
    This gives the same result:
    Code (csharp):
    1.  
    2.     private void OnMouseDown()
    3.     {
    4.         Vector3 mousePos;
    5.         mousePos = Input.mousePosition;
    6.         Debug.Log("C1: " + mousePos.ToString());
    7.         mousePos = Camera.main.ScreenToWorldPoint(mousePos);
    8.         Debug.Log("C2: " + mousePos.ToString());
    9.         isHeld = true;
    10.     }
    11.  
    This gives following output:
    C1: (471.3, 330.0, 0.0)
    C2: (1.0, 0.0, -8.0)


    C1 changes when I click at different points of the object, but C2 is always the same.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    37,243
    Between line 5 and line 6, do this:

    Code (csharp):
    1. mousePos.z = 10;
    that's what Manta meant about the third coordinate. That means "tell me the world point at this distance into the screen," in the example I suggest above, distance = 10; Your mileage may vary.
     
  5. m4ker

    m4ker

    Joined:
    Nov 26, 2019
    Posts:
    3
    Oh, I see what you mean. I thought the method would simply translate the provided Vector3 into a world coordinate, not do some kind of a raycast. Thanks a lot both!
     
    Kurt-Dekker likes this.
  6. reallybasicgames

    reallybasicgames

    Joined:
    Jun 26, 2020
    Posts:
    3
    Thank you for your answer! I never would have figured this out!
     
    zfried and Kurt-Dekker like this.