Miles Militis
Miles Militis

Reputation: 147

Swift: if statement to check if Node Texture is the same as another Node texture

There are 5 balls with different colors. The choiceBall changes randomly textures(colors) with each tap and indicates which of the other 4 colored balls you have to tap on. I thought of doing an if statement where I check if the ball that I tapped on is the same texture as the choiceBall but I can't seem to find a way that works.

Here I thought if choiceBall turns red and I press the red ball that RED would be printed. But it doesn't seem to happen. Shouldn't I be in touchesBegan since I want RED or BLUE or YELLOW or GREEN to be printed every time I tap on a ball.

Thanks for any help. :)

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

    let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
    choiceBall.texture = array[randomIndex]


    if choiceBall.texture == redBall.texture {
        println("RED")
    }
    else if choiceBall.texture == blueBall.texture
    {
        println("BLUE")
    }
    else if choiceBall.texture == yellowBall.texture {
        println("YELLOW")
    }
    else if choiceBall.texture == greenBall.texture {
        println("GREEN")
    }

}

Upvotes: 2

Views: 339

Answers (1)

Zachary Espiritu
Zachary Espiritu

Reputation: 987

See this answer on another StackOverflow post for the solution you're probably looking for.

In terms of game architecture, I would recommend using an enum of Color (or something similar) on choiceBall, because then you won't be comparing the actual textures, just the type of Color each ball is. It'll make for more cleaner code, and you'll probably be able to squeeze some more functionality out of that as well.

Example:

enum Color {
    case Red, Blue, Yellow, Green
}

[...]

if choiceBall.colorType == .Red {
    println("RED")
}
else if choiceBall.colorType == .Blue {
    println("BLUE")
}
else if choiceBall.colorType == .Yellow {
    println("YELLOW")
}
else if choiceBall.colorType == .Green {
    println("GREEN")
}

Upvotes: 2

Related Questions