I have a sprite that is partly transparent.
My aim is to fill the image with some square prefabs.
I have written this code which works fine.
while (newY < endVertical)
{
while (newX < endHorizontal)
{
Instantiate(filler, new Vector3(newX, newY, 0), Quaternion.identity);
newX = fillerWidth 0.1f;
}
newY = fillerHeight 0.1f;
newX = startHorizontal;
}
The result is
My goal is however to only draw the white prefabs only on the visible part of the image. I want my result to be something like this
To achieve this I have added a little change to check the color at each pixel and only instantiate the prefab if the color is not clear.
var colorSelected = player.GetComponent<SpriteRenderer>().sprite.texture.GetPixel((int) newX, (int) newY);
if (colorSelected != Color.clear)
{
Instantiate(filler, new Vector3(newX, newY, 0), Quaternion.identity);
}
This, however does not work.
CodePudding user response:
You can read pixels of texture via Texture2D.GetPixel and think texture as sets of chunks. Set the chunk as the same size as square and if there are any colored pixel in the chunk, render the square at the position.