One of the useful features we explored when
using sprites is the ability to tint the sprite into a different color.
The same facility is available when rendering objects using vertices,
too.
The effect object has a property named DiffuseColor,
which allows the tint color to be set. This property defaults to white,
which leaves the colors of our objects unchanged, but can be modified
to any color that we desire. The color is applied to our vertex colors
just as it was for sprites: it takes the red, green, and blue values of
each vertex color and represents them as a value between 0 and 1. Each
of them is then multiplied by the corresponding color element within DiffuseColor, and the resulting values used for the final vertex color.
Setting DiffuseColor to black will therefore result in all vertex colors becoming black, too. Setting DiffuseColor to red will remove all green and blue color information from the vertices, resulting in just the red color elements surviving.
Unlike the color properties we have seen so far, however, DiffuseColor is implemented as a Vector3 structure rather than as a Color. Each of the three elements within the Vector3 relates to one of the color elements in a color: the x element stores the amount of red, the y element stores the amount of green, and the z
element stores the amount of blue. All three of these measure color
using a float value in the range of 0 to 1, rather than an integer from
0 to 255.
To make our lives easier, the XNA developers have taken into account the need to translate color values between the Color structure and the Vector3 structure and have provided built-in functions to accomplish this.
To convert a Color into a Vector3, simply call its ToVector3 method. The resulting vector values will match those of the color. A simple example of this can be seen in Listing 1.
Example 1. Converting a Color structure into a Vector3
Vector3 myColorVector; myColorVector = Color.PeachPuff.ToVector3();
|
To convert a Vector3 into a Color, create a new Color and pass the Vector3
as a parameter to its constructor. This will produce a color whose
values match that of the vector. A simple example of this is shown in Listing 2.
Example 2. Converting a Vector3 structure into a Color
Vector3 myColorVector = new Vector3(1.0f, 0.8f, 0.2f); Color myColor; myColor = new Color(myColorVector);
|
Try modifying the NestedSquares example project so that the effect's DiffuseColor is set prior to rendering the squares in the Draw method and see the effect that it has on the generated graphics.
Being a Vector3, however, this
gives no opportunity to set an alpha value. When we tinted sprites,
alpha values were also available and allowed us to fade the
transparency of the sprites that were being rendered. In the
vertex-rendering approach, it is still possible to change the alpha of
rendered objects, but this is controlled using a separate property.