- Home /

# How do I implement ScreenPointToRay in a compute shader?

I've been scratching my head for a while trying to figure this one out. The nearest I can figure is that you take the XY of the screen position, feed it to the projection matrix and the worldToCameraMatrix and then magically you get the right direction of the ray, then you can derive the ray's origin from the camera position. Seems simple right? I cannot get that to work.

Nearest I have is something along the lines of:

```
Matrix4x4 V = Camera.main.worldToCameraMatrix;
Matrix4x4 P = Camera.main.projectionMatrix;
Matrix4x4 InvVP = (P*V).inverse;
```

which then gets fed into the compute shader to a function like this:

```
float3 ComputeWorldPosition(float3 screenPos)
{
// Transform pixel space to clipping space
screenPos.x = 2.0f*screenPos.x - 1.0f;
screenPos.y = 1.0f - 2.0f * screenPos.y;
// Do inverse VP multiplication
float4 worldPos = mul(float4(screenPos, 1), InvVP;
// Calculate final world position
return worldPos.xyz * worldPos.w;
}
```

Screenpos x and y are always between 0 and 1 and z is always 0, this results in nonsensical output, I know I'm doing something wrong but I cannot figure out what.

Why use projection matrices? Aren't you looking for the world coordinates from a ray going through an x,y screen coordinate? All you need is the output of Camera.ScreenPointToRay and use the point field from the RaycastHit data.

@cjdev: As far as I know within compute shaders there's no such thing as Camera.ScreenPointToRay.

In my application I am attempting to generate a LOT of rays, I need the paralelism of compute shaders.

That is exactly what I am looking for and I wish I could do that within Compute Shaders but I need to find a different solution.

**Answer** by anasainea
·
Feb 11 at 09:18 PM

You can check this article, it goes through using the matrices available on the Camera of Unity to create rays for all pixles inside a compute shader

### Your answer

### Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.

### Follow this Question

### Related Questions

Trying to find how the 'y' position of a Raycast with ScreenPointToRay is set 1 Answer

Using ScreenPointToRay with multiple changing cameras. 1 Answer

How to use ScreenPointToRay for orthographic cameras 1 Answer

Change parts of compute shader at runtime 0 Answers

How (Or Why) to use Consume Buffers safely on arbitrary data lengths 0 Answers