Search code examples
colorsswiftsprite-kitxcode6spectrum

Constantly changing the background color in swift


Hi there im finishing my game but i want to add some detail and one of them is looping trough a color cycle i have tried SKActions, that worked fine but it overlapped everything else.

then i made this in the update function but it doesn't do anything

if BGRed == 1 {RedBoolIs1 = true}
        else {RedBoolIs1 = false}

        if BGGreen == 1 {GreenBoolIs1 = true}
        else {GreenBoolIs1 = false}

        if BGBlue == 1 {BlueBoolIs1 = true}
        else {BlueBoolIs1 = false}


        //red only
        if RedBoolIs1 == true && GreenBoolIs1 == false && BlueBoolIs1 == false {
            BGGreen = BGGreen + 0.01 }
        //red and green
        if RedBoolIs1 == true && GreenBoolIs1 == true && BlueBoolIs1 == false {
            BGRed = BGRed - 0.01  }
        //green only
        if RedBoolIs1 == false && GreenBoolIs1 == true && BlueBoolIs1 == false {
            BGBlue = BGBlue + 0.01  }
        //green and blue
        if RedBoolIs1 == false && GreenBoolIs1 == true && BlueBoolIs1 == true {
            BGGreen = BGGreen - 0.01  }
        //blue only
        if RedBoolIs1 == false && GreenBoolIs1 == false && BlueBoolIs1 == true {
            BGRed = BGRed + 0.01  }
        //blue and red
        if RedBoolIs1 == true && GreenBoolIs1 == false && BlueBoolIs1 == true {
            BGBlue = BGBlue - 0.01  }

        self.backgroundColor = SKColor(red: CGFloat(BGRed), green: CGFloat(BGGreen), blue: CGFloat(BGBlue), alpha: 1)

also is it possible to make labels readable on all colors ? my solution now is placing 2 labels on each other the first one is white and 45 big and the one above that is black and 40 big but it doesn't look always good

thanks


Solution

  • First we initialise the color variables like this:

    var BGRed: Float = 1
    var BGGreen: Float = 0
    var BGBlue: Float = 0
    

    The reason nothing happens is that adding 0.1 10 times does not equal 1.0. This is because of floating point number accuracy. I myself asked the same type of SO question.

    To fix this, remove comparisons like this:

    if BGGreen == 1 
    

    And replace with:

    if round(BGGreen * 100) / 100.0 == 1.0
    

    It will solve this particular problem, but the better approach is to start using decimal floating point

    For the second issue, there is no easy answer but there are multiple answers on SO like this one.