Changing scenes with sprite kit after a certain ti

2019-06-13 19:13发布

I would like to change from scene to scene after a certain amount of time on one scene in Swift. I am trying to create a survival type game that the player has to survive a level for so long before they can advance to the next level.

I know that after I get to func being called I will be using this to go to the next scene.

self.view?.presentScene(GameScene2())

I am sure that something along the lines of NSTimer is going to be used, but anything that can be given to point me in the right direction would be of great help. Thank you in advance.

2条回答
祖国的老花朵
2楼-- · 2019-06-13 19:35

When your view is instantiated, you want to begin an NSTimer. See this page for help creating this: How can I use NSTimer in Swift?. This page may help as well: Using an NSTimer in Swift.

override func viewDidLoad() {
super.viewDidLoad()

var timer = NSTimer.scheduledTimerWithTimeInterval(30.0, target: self, selector: "update", userInfo: nil, repeats: true)

Then, you can just put the

self.view?.presentScene(GameScene2())

in a func update like so:

func update() {

self.view?.presentScene(GameScene2())

Hope this helps. If so, please check off my answer. If not, comment and I will try and help again.

查看更多
别忘想泡老子
3楼-- · 2019-06-13 19:47

An NSTimer is one option. Depending on what sort of accuracy you need and how long your duration will be you may or may not want to use an NSTimer. Example of an NSTimer ...

var myTimer = NSTimer()

func startMyTimer() {
myTimer = NSTimer.scheduledTimerWithTimeInterval(1.5, target: self, selector: "myFunction", userInfo: nil, repeats: true)
//1.5 is the time interval that you want to call the timer, in this case every 1.5 seconds
//the selector calls myFunction which is the function that you want to call every time the timer reaches its time interval
//if you want the timer to repeat and call myFunction() every 1.5 seconds then repeat should be true. if you only want it to be called once then repeat should be false
}

func myFunction(){
    //do whatever i am supposed to do when the timer reaches my specified interval
}

Now this may not be solution you are looking for. Another way is to use GCD's (grand Central Dispatch) dispatch_after . A very nice and extremely easy to use function can be found here, dispatch_after - GCD in swift? , in the second answer down, compliments of stackoverflow's @matt

查看更多
登录 后发表回答