Geeks With Blogs
Code.Blog Code Talk for the Game Developer

A cool trick to add to your game is to randomize a color and slowly fade to that color during gameplay.  This can be used as the draw color for sprites, the screen background, or anything else that takes a Color.  The code is pretty easy and only takes a few minutes to implement.

First, lets create a two variables; one to hold the new randomized color and one to hold the current color that is fading:

    Color futureColor = Color.CornflowerBlue;
    Color currentColor = Color.CornflowerBlue;

We'll set it to a default of the traditional CornflowerBlue.  Next, we need to create a random variable and randomize the Red, Green, and Blue components of our color:

    Random rand = new Random();
    if (futureColor != currentColor)
        futureColor = new Color(rand.Next(255), rand.Next(255), rand.Next(255));

We also check before changing the future color since we only want to fade if they are the same color.  Finally, you'll want to change the current color a little each time you update:

    if (currentColor.R != futureColor.R)
        if (futureColor.R > currentColor.R)
            currentColor.R += 1;
            currentColor.R -= 1;

This is the code for the Red component.  To update the entire color, you'll need two more sections similar to this for the green (Color.G) and blue (Color.B) components.  Experiment with the amount you increment and with how you randomize the numbers for more interesting effects.

Posted on Wednesday, January 6, 2010 10:13 AM Tutorials | Back to top

Comments on this post: Game Trick: Randomizing Colors

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Matthew Christian | Powered by: