Search code examples
xcodesprite-kitskspritenode

How can I have an SKSpriteNode follow the same path back and forth?


My code is compartmentalized over many files, so I hope I can describe this easily. I have a CGMutablePath() that goes from point A to point B I place an SKSpriteNode at point A and execute:

yourline0 = SKShapeNode()
pathToDraw0.move(to: cgPoints[0])
pathToDraw0.addQuadCurve(to: cgPoints[1], control: cgPoints[2])

yourline0.lineWidth = 0
yourline0.path = pathToDraw0
yourline0.strokeColor = .clear

iconPath0 = pathToDraw0

SKAction.follow(iconPath0, asOffset: false, orientToPath: false, duration: 1))

I execute that SKACtion and as I expected, my SKNode goes from point A to point B. Fine.

I'm not sure how to reverse it, I assumed from the dox that calling that same SKAction as is, would make the SKNode go from point B to A.


Solution

  • There is a method called reversed() which you could use.

    Below I have given your action a name of "youraction"

                let youraction = SKAction.follow(iconPath0, asOffset: false, orientToPath: false, duration: 1)
                let reverseaction = SKAction.reversed(youraction)
                yourspritenode.run(reverseaction)
                
    

    Alternatively, you can just use reversed after the action name to run it in reverse:

                yourspritenode.run(youraction.reversed())