Changing scenes with sprite kit after a certain time in Swift?

 ̄綄美尐妖づ 提交于 2019-12-08 13:48:11

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/35122809/changing-scenes-with-sprite-kit-after-a-certain-time-in-swift

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