Like in the topic title. I need to get the worldspace (or localspace) positions of green pixels on a texture on a plane, so I could instantiate prefabs there. I loop through the pixels and find them, but how to convert their index positions to worldspace or localspace?
int textureWidth = textureToSpawnOn.width;
int textureHeight = textureToSpawnOn.height;
for (int x = 0; x < textureWidth; x++)
{
for (int y = 0; y < textureHeight; y++)
{
Color pixelColor = textureToSpawnOn.GetPixel(x, y);
// Check if the pixel color is green
if (pixelColor == Color.green)
{
// TODO: Find each pixel in worldspace (or localspace)
Vector3 spawnPosition =
}
}
}
Tried many things, but still not there. Anyone could do this?
Edit: Figured out it’s impossible for anything with variable height, so I guess I need some other solution.
You already got close to the UV. This can show how to get the world pos. You can try to load UV info, or just divide the found pixel by the total size (if it’s pixel 512 of a 1025 pixel, the value would be 0.5).
If it’s on a plane and the green pixel is on 0.5, 0.5, you can use the plane width and height in world space to calculate the position of the pixel. For variable height you can sample the heightmap to add that to the height. You’re basically doing the reverse of rendering
Thank you for the response. Yeah, you’ve confirmed exactly what I’ve since figured out. Have no idea why I forgot that (probably a break I had from graphics). I’ve remembered UVs are basically percentages, so it’s easy. There could be also scale involved and that heightmap sampling. Weird, I was confused it would be harder for some reason.
Maybe because it would be harder if there was no heightmap for some irregular objects. Guess there’d be some hardcore number crunching with triangles involved. Wonder if there’s a function for that - I bet there should be if the texture is painted all over such object…
Don’t have time to reconstruct it on triangles and UVs now though, maybe later.
ps. oh, and it’s not a performant approach, but needed to reconstruct the concept for some spatial understanding - off cpu we go.