Game Development Reference
In-Depth Information
ages, each at different resolutions so that when the image is further away, we can
draw the simpler version to save computation time. Since we do not use that here,
we set that parameter to 0. The second parameter indicates from which part of the
image we want to retrieve color data. The third parameter is the array of colors that
we want to fill with that data. Then, we can indicate at which pixel index we start
collecting the data. Since we want the first (and only) pixel, we set this value to 0.
The final parameter indicates from how many pixels we want to get the data, in our
case: 1.
Now that we have called this method, we can access the Color object of the single
pixel by calling retrievedColor[0] . We can then use that object to check if the pixel is
fully transparent. We do that by accessing the alpha channel value which indicates
transparency. In the Color type, this is done using the A property. The alpha channel
value ranges from 0 (fully transparent) to 255 (fully opaque). See the following
example:
if (retrievedColor[0].A == 255)
// the pixel is fully opaque
Now we can start writing the code for the CreateRandomPosition method using this
knowledge. Creating a random position within the rectangle is easy:
Vector2 randomPos = new Vector2(JewelJam.Random.Next(width),
JewelJam.Random.Next(height));
We can then check if this position falls on a part of the sprite that is opaque, as
follows:
Rectangle sourceRectangle = new Rectangle(( int )randomPos.X + xoffset,
( int )randomPos.Y, 1, 1);
Color[] retrievedColor = new Color[1];
target.GetData<Color>(0, sourceRectangle, retrievedColor, 0, 1);
if (retrievedColor[0].A == 255)
// we're done!
If the position is not fully opaque, we generate a new random position and check
that, and so on, and so on, until we find a valid position. Although this is not entirely
safe, we use a while -instruction to keep generating random positions until we find
one that is on a fully opaque pixel:
Vector2 randomPos = Vector2.Zero;
while ( true )
{
randomPos = new Vector2(JewelJam.Random.Next(width),
JewelJam.Random.Next(height));
Search WWH ::




Custom Search