I’m having an issue with raycasting while using Unity’s Lens Distortion image effect.
Raycasts lose accuracy because they use the camera’s projection matrix without accounting for the distortion of the image effect. I tried to find the matrix or algorithm used for the distortion but I haven’t found anything.
Does any know what algorithm is used and how to modify the raycasting logic to account for the distortion?
The answer by @anaswattar got me close to what I needed, but I did some more digging and found that the formula is changed a little between PostProcessing V2 and the version I was using (Universal Render Pipeline 12.1.6)
The location of the code changed too:
The C# code can be found at com.unity.render-pipelines.universal@12.1.6\Runtime\Passes\PostProcessPass.cs
The shader code can be found at com.unity.render-pipelines.universal@12.1.6\Shaders\PostProcessing\UberPost.shader
I also converted the code a little differently than the other answer:
Ultimately this helped me do the kind of raycasting I needed to do. In my case I don’t need to worry about the distortion changing, so you could hook up those variables to read information from the post process settings. Hope that my digging saves someone else some time.
I ended up translating the shader code to C# so I could perform the same distortions on my mouse position. Here is my code:
public Ray RaycastWithDistortion(Vector2 screenPosition)
{
if (settings.active)
{
return cam.ViewportPointToRay(DistortAndNormalizeScreenPosition(screenPosition));
}
return cam.ScreenPointToRay(screenPosition);
}