Tap to Move in SpriteKit
Many iOS games use tap to move. Tap on the screen, and the player character will move to where you tapped.
Use the SpriteKit action moveTo
to add tap to move. Supply the destination location and the time interval (in seconds). When you run the action, the sprite will smoothly move to the destination over the time interval.
func touchDown(atPoint pos : CGPoint) {
let action = SKAction.move(to: pos, duration: 1.0)
// playerSprite is a SpriteKit sprite node.
playerSprite.run(action)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches {
touchDown(atPoint: t.location(in: self))
}
}
The speed the sprite moves depends on the distance between the sprite and the tap. The longer the distance, the faster the sprite moves.