Check your clock, because remarkably we’re just two methods away from finishing this game! Predictably, the two methods are critically important: one to move the player around the screen, and one to handle collisions between the player and the space debris.
Handling player movement is as simple as implementing the touchesMoved()
method. We will, like always, need to use the location(in:)
method to figure out where on the screen the user touched. But this time we're going to clamp the player's Y position, which in plain English means that we're going to stop them going above or below a certain point, keeping them firmly in the game area.
I'll be clamping the player's position so they can't overlap the score label, and I'll apply the same restriction on top so that the player has a symmetrical channel to fly through. This is a cinch to do, so here's the touchesMoved()
method:
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
var location = touch.location(in: self)
if location.y < 100 {
location.y = 100
} else if location.y > 668 {
location.y = 668
}
player.position = location
}
Our last task is to end the game when the player hits any piece of space debris. This is all code you know already: we're going to create a particle emitter, position it where the player is (or was!), and add the explosion to the scene while removing the player. In this game we're also going to set isGameOver
to be true so that the update()
method stops adding to their score. Here's all the code:
func didBegin(_ contact: SKPhysicsContact) {
let explosion = SKEmitterNode(fileNamed: "explosion")!
explosion.position = player.position
addChild(explosion)
player.removeFromParent()
isGameOver = true
}
SPONSORED Ready to dive into the world of Swift? try! Swift Tokyo is the premier iOS developer conference will be happened in April 9th-11th, where you can learn from industry experts, connect with fellow developers, and explore the latest in Swift and iOS development. Don’t miss out on this opportunity to level up your skills and be part of the Swift community!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.