Twinkle Twinkle Some XNA Stars
7/28/2010
Hypership, XNA
(0)
My game Hypership Out of Control is full of all kinds of stars. In order to make these stars seem a bit more real (or as real as a 5x5 pixel star can be), I decided I wanted to add a twinkle effect.
Searching online I found several examples of doing this with shaders or looping through items and setting specific pixels to be darker or black. I didn't particularly like any of the examples I found. For performance reasons, I didn't want any solution that involved looping through more items or even adding any extra if/else conditions when updating or drawing all the stars (100 in total). I didn't like all the extra shader logic I would need to add either, I like simple things because most often they're easy and they work.
First off, I have star objects in my game. What those look like isn't important. Just know they have their own position (vector2), draw and update methods, and a DrawRectangle method that returns a rectangle we use to draw the star.
Second I have a stars object. This object contains a list of all the stars and a few other variables specific to the collection of stars.
The first thing I did was create some new variables in the stars class.
private float TWINKLE_TIME = .05f;
private Texture2D black;
private int twinkleStar1; // First star to twinkle
private int twinkleStar2; // Second star to twinkle
private int twinkleStar3; // Etc.
private int twinkleStar4;
private int twinkleStar5;
private float twinkleTimer;
private Color twinkleColor;
In the constructor for my stars class, I set a couple of these variables. Note that I also pass a ContentManager object (content) to the constructor so I can load textures and fonts.
this.black = content.Load<Texture2D>("Debug\\Black");
this.twinkleTimer = TWINKLE_TIME;
this.twinkleColor = new Color(1f, 1f, 1f, .5f);
The magic happens in the Draw() method of the stars object. In this method I setup which stars will twinkle and then do the drawing to make that happen. In the Draw() method, I do have some logic that sets values. Normally I don't set anything in Draw() methods, but I made an exception for the stars. I don't want to run the full Update() method since this would cause my stars to move, but I do want them to always twinkle. I display the same stars on menus and the title screen so I want them to always look and twinkle the same. For your game, you could easily move the non-drawing stuff into your Update() method (and probably should) and it would work the same.
this.twinkleTimer -= Program.ElapsedTime;
if (this.twinkleTimer < 0)
{
// Different stars now will dim
this.twinkleTimer = TWINKLE_TIME;
this.twinkleStar1 = this.random.Next(1, 99); // 1 – 99 value based on how many stars total.
This article has been view 2478 times.
|