Handling Touches in a SpriteKit Game

One thing most iOS games must do is handle touch input from the player. If you use SpriteKit, handling touch input isn’t too difficult.

When you create a SpriteKit project or playground, the GameScene.swift file includes the following functions to handle touch input:

  • touchesBegan
  • touchesMoved
  • touchesEnded
  • touchesCancelled

The two functions you’ll use the most are touchesBegan and touchesMoved. You use touchesBegan to handle taps and use touchesMoved to move a sprite with your finger.

Determining What Was Touched

Use the location property to determine where the touch occurred. Call the atPoint function to determine what SpriteKit node was touched.

Once you know what SpriteKit node the player touched, you can do whatever you need to do with the node, such as move it, hide it, or highlight it.

Example Playground

I have a SpriteKit playground that lets you drag a sprite around the screen.

Leave a Reply

Your email address will not be published. Required fields are marked *