Lampros Tzanetos Lampros Tzanetos - 1 month ago 21
Swift Question

Restarting Sprite - Kit Game Swift

I have created a simple 2D arcade game using SpriteKit and I am trying to add a scoring system.Basically the game is a square sprite which has to jump over various obstacles. So what I want is when the player contacts the object for the whole game to restart. The game detects the contact (I tested it previously) but when I remove all my children and then run my game's basic main function I notice that old objects keep spawning and cluttering with each other.

func didBegin(_ contact: SKPhysicsContact) {

if (contact.bodyA.categoryBitMask == PhysicsCategory.Player && contact.bodyB.categoryBitMask == PhysicsCategory.Obstacles ) { //case where PLAYER collides with OBSTACLE

print("I detect Contact")

Scorelabel.text = "0"
scoreCounter = 0


self.removeAllActions()
self.removeAllChildren()

self.setupGame()

}


// the didBeging func is then continued for other cases

`

Nik Nik
Answer

If you're trying to restart a scene, you can just present the same scene and it resets back to its defaults:

let scene = GameScene(size: self.size)
let animation = SKTransition.crossFade(withDuration: 0.5) // ...Add transition if you like
self.view?.presentScene(scene, transition: animation)

You might just want to not show an animation (or do a cross fade) if you're trying to make a seamless transition.

Alternatively, you may want to create a game over scene/menu. This could just be another SKNode that becomes visible once the game resets or even another scene.

Comments