Tiptonix Beats Tiptonix Beats - 4 months ago 6x
Swift Question

RGB Values doing strange things when colorizing? - Swift

func colorBall() {

let colorize1 = SKAction.colorizeWithColor(UIColor.redColor(), colorBlendFactor: 1.0, duration: 0.1)
let colorize2 = SKAction.colorizeWithColor(UIColor.greenColor(), colorBlendFactor: 1.0, duration: 0.1)
let colorize3 = SKAction.colorizeWithColor(UIColor.blueColor(), colorBlendFactor: 1.0, duration: 0.1)

let actions = [colorize1, colorize2, colorize3]
let randomIndex = Int(arc4random_uniform(3))

var colorBucket = [UIColor]()

func randomColor() -> UIColor {

if colorBucket.isEmpty {


let randomIndex = Int(arc4random_uniform(UInt32(colorBucket.count)))
let randomColor = colorBucket[randomIndex]
return randomColor

func fillBucket() {
colorBucket = [UIColor.redColor(), UIColor.greenColor(), UIColor.blueColor()]

When I run this code in my game, and print out the color value of my ball, it sometimes prints out numbers like this:

UIDeviceRGBColorSpace 1 2.98023e-08 2.98023e-08 1

Why does it do this? I just want it to say: UIDeviceRGBColorSpace 0 0 1 1 if it's blue, IDeviceRGBColorSpace 1 0 0 1 if it's red, etc.

How can I keep those numbers from going higher than one, or much lower than one? What makes them do that in my code?


2.98023e-08 is 0.0000000298023. If you look up the value 2.98023e-08 on Google or another search engine, you can find several examples of people getting that value because of rounding errors. Rounding errors occur because of how computers treat floating-point numbers.

It's probably a rounding error from the interpolation code that colorizeWithColor uses, and you get it instead of zero. For practical purposes, when talking about color components about to be displayed to an end user, I'd say that anything smaller than 1/256 can be considered to be zero.

You can test if two floating point numbers are "about equal" like this (typed on my phone, not really guaranteed to work):

func areAboutTheSame(a: Double, b: Double) -> Bool {
    let difference = a-b
    return difference < 1/256 && difference > -1/256