Colour from Angle

The other day I converted a formula I found on Wikipedia into XNA C# code, basically I wanted to turn the 360 degree direction of a controller stick into a pure colour hue.

It’s a bit of a weird formula but it works a treat.

public static Color ColourFromAngle(float angle)
{
    float a = angle / 60.0f;
    int h1 = (int)a;
    int h = h1 % 6;
    float f = a - (float)h1;
    float p = 0;
    float q = 1.0f - f;
    float t = 1 - (1 - f);

    switch (h1)
    {
        case 0: return new Color(new Vector3(1, t, p));
        case 1: return new Color(new Vector3(q, 1, p));
        case 2: return new Color(new Vector3(p, 1, t));
        case 3: return new Color(new Vector3(p, q, 1));
        case 4: return new Color(new Vector3(t, p, 1));
        case 5: return new Color(new Vector3(1, p, q));
    }
    return Color.Red;
}

2 thoughts on “Colour from Angle

  1. Matt Hamilton Reply

    Is “h” used after being assigned to? I can’t find it further down in the code. (Although it’s possible I can’t see for looking!)

    I’d be interested in seeing a screenshot, Pete – maybe superimpose the angle of the controller over the colour?

  2. Pete Reply

    You’re right, I think I’m supposed to be doing the switch on “h” not “h1” if the angle goes larger than 360 it’d cause problems.

Leave a Reply to Matt Hamilton Cancel reply

Your email address will not be published.