- Home /
Ray casting in Unity, matching Unity camera parameters
I'm trying to do some ray casting in a pixel shader.
I'm doing this by drawing a screen aligned quad using an orthographic projection, but I would like the ray casting to match the camera parameters of my main Unity camera - a perspective camera with a 60 degree field of view.
I'm having trouble calculating my Ray Direction to match this.
Here is the pixel shader code I'm using.
// fragment.hPos is output from the vertex shader - is the model-view-projection of the
// vertex coordinate
float4 p1 = fragment.hPos / fragment.hPos.w;
float screen_x = (p1.x + 1) * (_ScreenParams.x/2);
float screen_y = (p1.y + 1) * (_ScreenParams.y/2);
// fragcoord is supposed to be the same as openGL's gl_FragCoord
float2 fragcoord = float2(screen_x, screen_y);
float i =fragcoord.x;
float j = fragcoord.y;
float fovx, fovy;
fovx = 1.04719755; //60 degrees horizontal field of view
fovy = _ScreenParams.y / _ScreenParams.x * fovx;
//holds the x and y coords of the viewplane point
x = 0;
y = 0;
x = (((2* i) - _ScreenParams.x) / _ScreenParams.x) * tan(fovx);
y = (((2*j) - _ScreenParams.y) / _ScreenParams.y) * tan(fovy);
// ro = ray origin, at the camera position
ro = cameraPosition;
float3 rd = float3(x,y,1.0) - ro; // rd = ray direction viewPlane is at x, y, 1.0
rd = normalize(rd);
When I go on to use this ray origin (ro) and ray direction (rd) to ray cast the scene, the result doesn't match the scene view from a regular unity camera. Objects aren't in quite the same position and look 'stretched' vertically.
Anyone know how to do this correctly? I would greatly appreciate any guidance. Thank you!
Your answer
Follow this Question
Related Questions
is it possible to have raycasts to cover the whole screen in one Update() time? 0 Answers
How to make camera position relative to a specific target. 1 Answer
Accessing all GameObjects with a certain tag 1 Answer
nullifying targetObject after a Smooth LookAt Transition 2 Answers
How to display a camera on the screen while displaying the Oculus Rift in direct mode ? 1 Answer