Thursday 6 January 2011

Seeing through the problem

Well this colour issue was a bit of an anti climax. I was expecting it to take the entire evening but it seems I've actually done a good job in making the program thus far and as such I only needed to create a new method and then change 2 lines of existing code! Awesome!

Seeing as that took such a short time you'll be pleased to know that I've also restarted the particle engine. With new idea's rushing at me as usual it may become the case that I'll need a "Particle System" tool to create some funky new particle effects for use on the map and in battle scenes. Shiny shiny stuff.



For some lost folk who may end up here through google here's how to work with transparency in XNA 4.0:

Before in XNA 3.1 and below we could simply do the following to get a semi transparent white:

Color C = new Color(Color.White, 0.5f);

Nice and simple right? Create the colour "white" and set it's alpha channel to 0.5
Well it seemed that some people were getting a bit confused with Color's other constructors and the constructor

public Color(byte R, byte G, byte B, byte A)

had to be changed to accept int's instead of byte's. Why this affected the constructor that accepts a colour and a float is beyond me, but the constructor no longer exists. Visit our old friend Shawn Hargreave's for a bit more info on what confused people:
Shawn Hargreave's Blog

Worse still, you gotta jump through hoops to get the same effect. a sensible person would assume that creating a semi transparent white colour with the new constructors would be as simple as

Color C = new Color(255, 255, 255, 127);

Full Red, Full Green, Full Blue, Half Alpha
Errrrrmmmmm.....no.

The actual code you would need is

Color C = new Color(127, 127, 127, 127);

Why? Well wrap your head around this:
In XNA 4.0 we now need to apply the alpha to the individual colour components. In the case above the alpha is set to half. 255 being 100% and 127 being 50% so we needed to half the colour components as well. It seems a bit cack handed to me and I don't know why the old constructor was removed, but I decided to remake it in the form of a static method so that I can create semi transparent colours nice and easy

public static Color ColorCreator(Color colour, float Opacity)
        {
            int Alpha = (int)(255 * Opacity);
            int Red = (int)(colour.R * Opacity);
            int Green = (int)(colour.G * Opacity);
            int Blue = (int)(colour.B * Opacity);
            return new Color(Red, Green, Blue, Alpha);
        }

Notice how the opacity is taken as a float so that I can easily depict the opacity as a fraction between 0-1

This fraction then gets applied to the colour components of the colour that was passed through and a new set of int's are created to construct a colour using the new 4.0 constructor

No comments:

Post a Comment