Game Development Reference
In-Depth Information
for ( int i = 0; i < density; i++)
{
positions.Add( this .CreateRandomPosition());
scales.Add(0f);
}
18.4.3 Accessing Pixel Color Data
Suppose that we want to add glitters to a jewel. If you take a look at the sprite
containing the jewels, there are two issues:
there is no sprite that represents a single jewel;
there is a lot of transparent space around the jewels.
The first issue means that if we pass along the 'spr_jewels.png' sprite as the target,
we need a way to indicate which part of the sprite we should use as a target. This is
done using the xoffset variable. Although this is not an ideal design, for this particular
game this is sufficient. The second issue is that the jewels sprite contains a lot of
transparent space, and we do not want to draw glitters on that part of the sprite, only
on the part that represents the jewel. So, we need a way to find out what color the
target sprite is at a certain (pixel) position. That way, we can only select random
positions that fall on the actual sprite, and not on the transparent background.
Retrieving the color of a pixel in a sprite is done with the GetData method from
the Texture2D sprite. This method can retrieve color data from a sprite for a rectangle
that indicates for which part of the sprite we want to retrieve color data. So the first
step is to create a rectangle located at a certain position in the sprite. We define this
rectangle with a width and height of 1 since we only need a single pixel:
Rectangle sourceRectangle = new Rectangle(randomx + xoffset, randomy, 1, 1);
Later on, we will see how to generate the randomx and randomy values. We add the
xoffset to the x value so that we select the desired part of the sprite. Then, we create
an array of Color objects in which we will store the retrieved colors:
Color[] retrievedColor = new Color[1];
Finally, we call the GetData method, which fills the array of Color objects with the
2D sprite data:
target.GetData<Color>(0, sourceRectangle, retrievedColor, 0, 1);
The first parameter (which we do not use in our game) defines on which level of
detail we want to retrieve the data. Sometimes, a sprite can consist of multiple im-
Search WWH ::




Custom Search