- Home /
Getting pixel color on ray hit
What I need is to get the texture's pixel color where the ray hit. I need it so I can check if color = blabla, then do something. Seeing as rays hit colliders and not meshes, I don't know to get pixel color from a mesh texture. I know there is Texture2D.GetPixel, but I don't know how to get it from 3d into 2d and to the right pixel.
Thanks
Answer by Eric5h5 · May 29, 2011 at 03:44 PM
Use RaycastHit.textureCoord. Note that it only works with mesh colliders.
But I need it to work on meshes that don't use mesh colliders.
Well, it doesn't. ;) There's some way to do it by writing your own routines no doubt, but I have no idea what the math would be.
Although, what might work is to convert the RaycastHit.point to screen space using WorldToScreenPoint, and then use ReadPixels on that point. It wouldn't work if the hit.point is behind some object, but depending on what you're doing, it might be O$$anonymous$$.
Answer by Statement · May 29, 2011 at 11:30 AM
Manually reverted to 1st revision:
I am unaware of any such built in functionality, though I wouldn't be surprised if anyone made and shared a similar tool already. I'd check google if you haven't. But basically you'd need to perform a test vs every triangle to get the barycentric coordinates of intersection between the triangle and the ray. Then, you can interpolate the triangle UVs using the barycentric coordinates to get the final UV coordinate for your hit test.
When you have the UVs, you can rescale the UVs to texture pixel space. That is, the UVs are usually in the 0 to 1 range where textures are like 0 to 255 (256 pixels). Note that some models may repeat the texture so it's possible to get an UV outside of the range 0 to 1, like -1 or 2.34 or -502.2.
That said, I wouldn't be surprised if there is any built in, premade or easier solution. This is just what came to my mind.
This requires the collider to be a $$anonymous$$eshCollider. For another explanation about getting the UV from an arbitrary mesh, see my revision history as I first explained the "long way" around and then realized you can probably just do with the RaycastHit.
You should see "Edited xx $$anonymous$$utes ago". Press that and you should see the other revisions.
$$anonymous$$e neither. This new Unity Answers is still very buggy.