Search code examples
swiftsprite-kitskshapenode

How to animate the opacity of a SKShapeNode?


I am working on the instructions screen of my game and want to show to the user that they should tap a certain area of the screen.

So I want to show an animation where

1) A finger is scaling in and out of the screen, followed by -- working fine--

2) A rectangle changing opacity (to show to tap there) and then -- need help--

3) A text flashing saying, "Tap here" -- need help--

For 1), I have this (working fine):

    finger = SKSpriteNode(texture: fingerTxt)
    finger.position = CGPoint(x: 330, y: 450)
    finger.zPosition = 10
    InstHolderNode.addChild(finger)

    let fingerTapScaleDown = SKAction.scale(by: 0.6, duration: 0.7)
    let fingerTapScaleUp = SKAction.scale(by: 1.6, duration: 0.7)
    let fingerScalingSequence = SKAction.sequence([fingerTapScaleDown,fingerTapScaleUp])

    let fingerTapScaleForever = SKAction.repeatForever(fingerScalingSequence)
    finger.run(fingerTapScaleForever)

For 2), I have :

    var rect = SKShapeNode(rectOf: CGSize(width: 150.0, height: frame.height * 2))
    rect.position = CGPoint(x: 300, y: 100)
    rect.fillColor = SKColor.brown
    rect.alpha = 0.5
    InstHolderNode.addChild(rect)

Question :

How do I sync 1) and 2) such that after 1) is completed (the finger tapping animation is done), rect.alpha value to change to 0.1 and then changed back to 0.5 and then 1) happens and then rect.alpha is changed to change to 0.1 (in a loop) continuously.

Many thanks!!


Solution

  • Try this:

        var fadeOut = SKAction.fadeAlpha(to: 0.1, duration: 0.5)
        var fadeIn = SKAction.fadeAlpha(to: 0.5, duration: 0.5)
    
        rect.run(SKAction.repeatForever(SKAction.sequence([fingerScalingSequence, fadeOut, fadeIn])))
    

    Adjust the durations as per your liking