Search code examples
swiftscenekituicolorscnnode

Why does only the built-in UIColors work here?


Having failed miserably at further attempts to solve this question on my own, I'm trying something I thought would work for certain:

func switchColor(data:UInt32){
        switch data {
        case 1..<200:
            backgroundGeometry.firstMaterial?.diffuse.contents =
                UIColor(red: CGFloat(242), green: CGFloat(90), blue: CGFloat(90), alpha: 1.0)
        case 200..<400:
            backgroundGeometry.firstMaterial?.diffuse.contents =
                UIColor(red: CGFloat(252), green: CGFloat(162), blue: CGFloat(115), alpha: 1.0)
        case 400..<600:
            backgroundGeometry.firstMaterial?.diffuse.contents =
                UIColor(red: CGFloat(244), green: CGFloat(235), blue: CGFloat(99), alpha: 1.0)
        case 600..<800:
            backgroundGeometry.firstMaterial?.diffuse.contents =
                UIColor(red: CGFloat(110), green: CGFloat(195), blue: CGFloat(175), alpha: 1.0)
        case 800..<1000:
            backgroundGeometry.firstMaterial?.diffuse.contents =
                UIColor(red: CGFloat(91), green: CGFloat(118), blue: CGFloat(211), alpha: 1.0)
        default:
            backgroundGeometry.firstMaterial?.diffuse.contents = UIColor.green
        }
    }

All the non-default cases turns the node white. The default case does turn it green - and within each case, statements like UIColor.red, UIColor.blue work fine as well.

So why the heck doesn't the above statements work?

Hope you can help, I'm completely at a loss here :(

Edit: Thanks for the swift and not least correct answers! All accepted and upvoted, but I'm too much of a newbie for it to display. Thanks! :)


Solution

  • This should work for you:

    func switchColor(data: UInt32) {
        guard let contents = backgroundGeometry.firstMaterial?.diffuse.contents else {
            fatalError("First material is nil") // If this really can be empty, just replace this with return
        }
    
        switch data {
        case 1..<200:
            contents = UIColor(red: 242/255, green: 90/255, blue: 90/255, alpha: 1)
        case 200..<400:
            contents = UIColor(red: 252/255, green: 162/255, blue: 115/255, alpha: 1)
        case 400..<600:
            contents = UIColor(red: 244/255, green: 235/255, blue: 99/255, alpha: 1)
        case 600..<800:
            contents = UIColor(red: 110/255, green: 195/255, blue: 175/255, alpha: 1)
        case 800..<1000:
            contents = UIColor(red: 91/255, green: 118/255, blue: 211/255, alpha: 1)
        default:
            contents = .green
        }
    }
    

    The maximum value of a color is 1.0, not 255. Therefore you need to divide the values.