Handling Touches in a SpriteKit Game
Table of Contents
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.
Use the location
property to determine where the touch occurred. Call the atPoint
function to determine what SpriteKit node was touched.
for t in touches {
let location = t.location(in: self)
let touchedNode = atPoint(location)
}
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.
I have a SpriteKit playground that lets you drag a sprite around the screen.