Thomas Keegan
Thomas Keegan

Reputation: 11

Continuously changing color property of SKShapeNode during gameplay (Swift)

I have an SKShapeNode var Circle = SKShapeNode(circleOfRadius: radius) in the background of my spritekit game that uses swift. The circle is for aesthetic purposes so nothing interacts with it. I'd like Circle.strokeColor to continuously change at all times. My current code changes the stroke color property of the SKShapeNode but it does not display the color changes because I'm changing the property after it has been added to the background. The color stays the same throughout the game until the the game ends and the circle is removed from the background then recreated. My code changes the color by adding 1 to var colorTime: CGFloat = 0.0 every time the update function runs, and then relating the RGB values of the Circle's color to cosine functions using that colorTime variable. How can I continuously change (and display) the color of the circle?

override func update(currentTime: CFTimeInterval) {


    if last_update_time == 0.0 {
        delta = 0
    } else {
        delta = currentTime - last_update_time
    }
    last_update_time = currentTime

    colorTime += 100
    redColor = (cos(colorTime/100)+1)/2
    greenColor = (cos(colorTime/200 - 2.09)+1)/2
    blueColor = (cos(colorTime/300 - 4.18)+1)/2
    circleColor = UIColor(red: redColor, green: greenColor, blue: blueColor, alpha: 1)
    Circle.strokeColor = circleColor
}

Upvotes: 0

Views: 244

Answers (1)

Thomas Keegan
Thomas Keegan

Reputation: 11

I didn't realize this code actually works. The only issue ended up being that the game would crash after the game restarts because I would add the SKShapeNode to the background again without ever removing it. I added Circle.removeFromParent() to my restartGame function and now I'm good.

Upvotes: 1

Related Questions