Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

How Camera.ScreenPointToRay is calculated?

Discussion in 'Scripting' started by mnarimani, Aug 14, 2019 at 4:31 PM.

  1. mnarimani

    mnarimani

    Joined:
    Mar 27, 2017
    Posts:
    174
    You can use ScreenPointToRay function to convert a point on screen to a ray that can be used for raycast. But how the function works internally?
     
  2. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,022
    Camera has a 4 corner pyramid frustrum. Computer screen is a plane perpendicular to that frustrum. You provide ScreenPointToRay with coordinates on that plane and it returns ray coming from camera through that point on screen plane.
     
  3. Boz0r

    Boz0r

    Joined:
    Feb 27, 2014
    Posts:
    333
    You take your mouse cord and normalize it so the values are between -1 and 1. You have the camera fov, position and forward vector. Add half the camera fov multiplied by the values to your camera's forward vector and you're golden.
     
    mnarimani likes this.
  4. mnarimani

    mnarimani

    Joined:
    Mar 27, 2017
    Posts:
    174
    Thanks!
     
  5. iSinner

    iSinner

    Joined:
    Dec 5, 2013
    Posts:
    123
    Did it work? because that isn't correct.
    It doesn't take into account the perspective, and the aspect ratio, so i'm curious if it worked, because if it did, them i'm missing something.
     
  6. mnarimani

    mnarimani

    Joined:
    Mar 27, 2017
    Posts:
    174
    I didn't get the time to try it. I wanted a general hint to know how it's implemented.