Restarting Sprite - Kit Game Swift

不羁岁月 提交于 2020-01-02 14:12:14

问题


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

`


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/40051887/restarting-sprite-kit-game-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!