Learn iOS SpriteKit with Examples, Code Snippets and Video Tutorials

Sprite Kit SKActions Example

Sprite Kit SKActions Example

How to write a simple SKAction with Swift 3 and Sprite Kit. All of the following examples, assume your game has an SKSpriteNode named thePlayer in the scene. Below, is a single SKAction being created on the first line, to move something on the x axis by 50 and 30 on the y axis over 1 second.  The “thing” to be moved is established on the second line, which is thePlayer.

Note once the SKAction move is created, it could be run on multiple nodes. For example…

Sprite Kit has dozens of SKActions available, all of which can be seen in Xcode by simply beginning to type SKAction. and you’ll find plenty, like so…

SKActions example with Swift and Sprite Kit

Common SKActions

If you’re an aspiring game developer, useful SKActions to familiarize yourself with would be…

  • SKAction.move
  • SKAction.animate
  • SKAction.scale
  • SKAction.resize
  • SKAction.rotate
  • SKAction.fade
  • SKAction.fadeOut
  • SKAction.fadeIn
  • SKAction.hide
  • SKAction.unhide
  • SKAction.playSoundFileNamed
  • SKAction.applyForce
  • SKAction.applyImpulse
  • SKAction.run  (runs a block of code)

How to Run SKActions in Sequence

Below we’ll run one action, then another…

SKAction.sequence uses an array of SKActions, each comma separated. You can add as many SKActions as needed.

How to Loop / Repeat SKActions

We could loop the previous example by adding one more SKAction to repeat the sequence. For example…

You can also repeat a set number of times by using this instead of repeatForever…

That would repeat the SKAction 20 times.

How to Run a Block of Code After an SKAction

One of the most important things you can do with actions is follow them up with code. For example, after a player completes a jump, you might want to switch a bool variable to let the game know the player is no longer in the air, so to speak.  For example…

So in that example, the inTheAir variable would be true for 2 seconds. 1 second while the jumpUp action runs, 1 second while fallDown runs, and then when both actions are completed the run block of code is executed to switch it back to false.

Easing SKActions (Smoothing Out the Motion)

Many SKActions support the .timingMode property to ease them in or out. For example…


Check out our premium Swift and Sprite Kit Tutorial content!

Visit CartoonSmart.com