Reputation: 323
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
`
Upvotes: 2
Views: 1042
Reputation: 1664
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) // Whichever scene you want to restart (and are in)
let animation = SKTransition.crossFade(withDuration: 0.5) // ...Add transition if you like
self.view?.presentScene(scene, transition: animation)
Put this code in whichever scene you are in and wish to restart. It should be called when you want to restart the scene.
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.
Upvotes: 5
Reputation: 2591
First of All, you should check both cases, If player is Contact A or if Player is Contact B. Secondly, you should assign the object you want to remove, lets says the obstacle, to a variable, for example lets says that Object B es the Obstacle, Then: contact.bodyB.node.removeFromParent() and you will successfully remove the object.
Upvotes: 2