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

Question How to use Camera.ScreenToWorldPoint in AR Foundation

Discussion in 'AR' started by J1wan, Jul 28, 2020.

Thread Status:
Not open for further replies.
  1. J1wan

    J1wan

    Joined:
    Jun 4, 2020
    Posts:
    15
    I am trying to use a non-centered crosshair in an AR app as shown here:
    upload_2020-7-28_11-51-58.png

    I am using

    Vector3 cameraPoint = camera.ScreenToWorldPoint(new Vector3(cursorPos.x, cursorPos.y, 0.2f));
    , where
    cursorPos
    is the screen position of the cursor. However, when I make a Raycast to detect collisions using cameraPoint as the ray origin, the origin position does not seem to be at
    cursorPos
    . Instead, the Raycast origin seems to be very close to the center of the camera. The code for the Raycast is

    Physics.Raycast(cameraPoint, camera.transform.forward, out RaycastHit hit, Mathf.Infinity, layerMask)
     
    makaka-org likes this.
  2. KyryloKuzyk

    KyryloKuzyk

    Joined:
    Nov 4, 2013
    Posts:
    1,070
    In my experience it's always simpler to use Rayast version that accepts Ray:
    Code (CSharp):
    1. var ray = camera.ScreenPointToRay(cursorPos);
    2. Physics.Raycast(ray, out var hit, Mathf.Infinity, layerMask);
     
  3. re-cheid

    re-cheid

    Joined:
    Apr 10, 2017
    Posts:
    34
    I also prefer KirillKuzyk's version, that should handle everything.

    Just to clarify where your problem was:
    Your ray always shoots in perfect camera.forward direction. Unless you have an orthographic camera this is only correct for the camera center. On perspective cameras the ray direction points more outward the further you are from the center.
     
  4. b9n

    b9n

    Joined:
    Feb 6, 2020
    Posts:
    14
  5. sidbhise

    sidbhise

    Joined:
    May 13, 2020
    Posts:
    7
    I was trying to solve a similar problem, but never found ARCamera.ScreenToWorldPoint in ARFoundation 3.1.3? Is this available in the latest ARFoundation by any chance?
     
  6. KyryloKuzyk

    KyryloKuzyk

    Joined:
    Nov 4, 2013
    Posts:
    1,070
    You can get the reference to AR camera from ARSessionOrigin:
    var arCamera = FindObjectOfType<ARSessionOrigin>().camera;
     
    makaka-org likes this.
Thread Status:
Not open for further replies.