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.
  2. Dismiss Notice

Camera.main.ScreenToWorldPoint() Not Working

Discussion in 'Scripting' started by Froggles01, May 22, 2021.

  1. Froggles01

    Froggles01

    Joined:
    Apr 2, 2021
    Posts:
    8
    I have a 3D game and I am trying to make it so that it spawns a gameobject where I click with cam.ScreenToWorldPoint(mousePosition), but whenever I click it just inserts the game object at the position of the camera? Why is this and how can I fix it?

    Code (CSharp):
    1. void Update()
    2.     {
    3.         if (Input.GetKeyDown("mouse 0"))
    4.         {
    5.             Vector3 point = new Vector3();
    6.  
    7.  
    8.             Vector3 mousePos = Input.mousePosition;
    9.  
    10.             point = Camera.main.ScreenToWorldPoint(mousePos);
    11.  
    12.             Instantiate(g, point, Quaternion.identity);
    13.         }
    14.     }
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    It's counter-intuitive, but you need to set the Z position as the distance from the camera.

    Code (csharp):
    1.  
    2. Camera cam = Camera.main;
    3.  
    4. Vector3 mousePos = Input.mousePosition;
    5. mousePos.z = cam.nearClipPlane;
    6.  
    7. point = cam.ScreenToWorldPoint(mousePos);
    8.  
    For a full 3D game with a rotatable camera, you'll probably want to use a Raycast eventually anyways.
     
  3. Lurking-Ninja

    Lurking-Ninja

    Joined:
    Jan 20, 2015
    Posts:
    9,913
    Didn't you want something like this?
    Code (CSharp):
    1. private void Update()
    2. {
    3.    if(!Input.GetMouseButtonDown(0)) return;
    4.    var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    5.    if (Physics.Raycast(ray, out var hit)) {
    6.       Instantiate(g, hit.transform.position, Quaternion.identity);
    7.    }
    8. }
     
  4. Froggles01

    Froggles01

    Joined:
    Apr 2, 2021
    Posts:
    8
    Thank you, this helped a lot.