What happens if I execute an SKAction run sequence on a node that is already executing another sequence? - sprite-kit

I have an SKSpriteNode with an SKAction being run on it:
theGem!.run(premAction, completion: {theGem!.run(repeatAction)})
Can't seem to find out the proper steps to run another action, such as:
theGem.run(endsequence, completion: {theGem.removeAllActions(); theGem.run(stopAction)})
Should I stop the previous action first?
Is there a way to turn the repeat part off so that the first SKAction ends smoothly?

Typically SKActions are combined when 2 or more are run at once.
To run a sequence of SKActions you would usually use something like this, where premAction is run first, followed by repeatAction
let sequence1 = SKAction.sequence([premAction, repeatAction])
To run the sequence use:
theGem.run(sequence1)
If the plan is to run another SKAction sequence at some point, you can use:
theGem.removeAllActions()
theGem.run(sequence2)
Alternatively, if you prefer more closely monitored action management, whenever you run an action assign it a key like this:
theGem.run(sequence1, withKey "seq1key")
Then, when you want to stop that particular action, use:
theGem.removeAction(forKey: "seq1key")

Related

Swift UIAnimation blocked by for loop

I have a UIAnimation that pulls out a message log, but I need to populate the message log using a for loop as well. I have the animation taking place before the for loop begins, however, the animation doesn't actually begin until after the for loop finishes executing (even though the loop is located after the UIAnimation).
I've tried putting the contents of the for loop within an autoreleasepool (did not work)
I've tried running the for loop on a background thread, however, most of the code within the loop needs to be executed on the main thread, and I haven't had success with that approach.
The for loop is very large, and most of the code is irrelevant to the question, so you can set this up using any UIAnimation, and any relatively time consuming for loop...
for example:
let someView = UIView(frame:CGRect(x:self.view.frame.size.width,y:0,width:self.view.frame.size.width,height:self.view.frame.size.height))
someView.backgroundColor = .red
UIView.animate(withDuration:0.3,animations:{
self.someView.frame.origin.x = 0
})
//You can wrap this with something like:
//DispatchQueue.global(qos: .background).async(execute: {
//But this^ doesn't work on the majority of the code within the loop
for i in 0...1000{
print("hopefully this loop takes a few seconds to finish executing")
print("mainthread tasks being executed")
print("populating UITable in my particular case, and rendering Images/Video/text")
}
The closest that I can get to making it better is to add a "completion" to my UIAnimation, (which will allow the UIView to pull out completely/immediately) but then there is still a second of wait time before the first messages appear...
Also, I am populating a UITableView within the for loop. Not sure if that has any extra relevance to the primary issue I'm having or not...
I'm pretty familiar with DispatchQueue and the differences between async/sync. If you have any potential solutions, or ideas, please let me know.
The animation does not happen immediately, when you call UIView.animate. In stead all the animations are collected and run at some appropriate time. This is why the animation only starts after your for loop is done.
So the way to fix it is to get the animation to run before your for loop runs. Now, accepting what you say, that the for must run on the main thread, you have a number of options. You could put the for loop inside a DispatchQueue.main.async{} or somehow throttle it down so that the animation gets going first. Your idea of using the completion is a good one but you mention some practical issues you picked up with it. So either solve those practical issues, try to run the for inside a DispatchQueue.main.async{} or even, based on practical considerations, start the for loop on the main thread but somewhere else, say in something like didLayoutSubviews (fixed) or as now together with the animation but after a few millis delay to allow the animation to get going.
It's an interesting question. This made me think!
Yes, you mentioned that you understand differences between async/sync but didn't mention if you tried animating in the main thread.
Did you try putting the
UIView.animate(...) in DispatchQueue.main.async{}?

Dynamically append SKAction with unknown number - dependant on previous actions

I'm building a turn based game with SpriteKit. It's a human player versus 1+ CPU opponents.
During the CPUs' turns I'm using an SKAction.sequence in order to show what the CPU is doing. This usually consists of a wait action followed by a custom SKAction.run block.
Now part of the problem I have is that the CPU could perform multiple attack actions per turn, but after each attack task I recalculate if there should be anymore attacks done, as conquering a country might open up new avenues of attack. The trouble I've got here is that I then have no way of knowing how many attacks should take place upfront, and as the initial attack itself is in a block, it doesn't know if it will generate more attacks. Thus I don't know how to add additional attack steps to my sequence.
Does anyone have any ideas how I could go about this? One thought was that I actually perform all the attacks upfront without displaying them and subsequently then just replay them for the benefit of the player. But I'm worried it will seem like the game is hanging in this instance.
Is there anyway I could append more SKActions midway through a running sequence?
let sequence:[SKAction] = []
let attackTasks = actions.getAttackTasks()
if attackTasks.count > 0 {
sequence.append(SKAction.wait(forDuration:0.5))
sequence.append(SKAction.run {
//PerformAttackTask Here calls another recursive function which calculates and generates more attacks
self.performAttackTask(attackTask: attackTasks.first!)
self.combatFinished = false
})
}
let sequenceAction = SKAction.sequence(sequence)
node.run(sequenceAction)
For those that are interested I ended up changing my approach for this moving the animations down a level to the performAttackTask method and recursively calling itself.
I then make use of a callback that only fires when all combat is complete to exit this loop.
This also makes use of SKAction.run with a completion handler to then move onto the next set of actions

Using a timer vs update to run game SpriteKit

I am curious what to use for my game. A timer:
let goodFPS = SKAction.wait(forDuration: 0.01666)
let mainGameRunner = SKAction.run {
//my code is here
}
let toRepeat = SKAction.repeatForever(SKAction.sequence([goodFPS,mainGameRunner]))
inGameHighScore.run(toRepeat,withKey:"mainGame")
or the update function:
override func update(_ currentTime: TimeInterval){
//my code is here
}
Which provides faster more consistent updates?
note: my frame rate is in the range of 45 to 58
First I think you are taking the FPS problem the wrong way around. You cannot "force" a faster frame rate than the device can give you. If you are basing the movements in your game on the assumption that every frame will be consistent, you are doing it wrong. It's actually how they did in the early days because CPUs were so slow and the difference from one generation to the new one wasn't too bad at first. But running an old DOS game on younger hardware will be tricky because the framerate is so high that the whole game mechanic becomes unstable or simply too fast to be playable.
The concept here is to think "over time" and to scale down any action in relation with the time elapsed between two frames.
The update() method gives you that opportunity by providing the current system clock state every frame. By keeping track of the time on the last frame, you can calculate the time difference with the current frame and use that difference to scale down what you are doing.
Using a timer to get the update on a consistent frame rate is not recommended nor practical. You may be calling the update closure at a given time interval, but the code inside that closure is taking time to execute on its own, and depending on your game logic, it might even have different execution times. So maybe the pause timing is consistent, but the code running before and after that pause might not be consistent. Then what happens if you run your game on a slower CPU? The code speed will change even more, making your timing inaccurate.
Another point against using an SKAction for your game loop is simply what they are. An action is an object in memory, meany to be reused by multiple objects. If you are making a "jump" action, for example, it is recommended to store that action somewhere and to reuse the same object every time you need something that "jumps", no matter what node it is. Your game loop is meant to be executed every frame, but not by different objects. Actions are also disposable. Meaning that you can kill an action even while it's running. If you put your game loop in an action, it will probably be run by the SKScene. If you use another action on your scene it becomes a puzzle right away because there are only two ways of removing an action besides letting it come to term: removing all actions or creating the action with an identifier key and use that key to remove any action with that key. If you don't see it already, it then forces you to put identifiers on every action that will be run by the scene and remove them one by one. And them again it leave a door open for a mistake that will get rid of your game loop because, keep it in mind, actions are DISPOSABLE! Then there is also no guarantee that your action will get executed first every single frame.
Why use the update() method? Simply because it is built IN your scene. No matter what, every frame, update() gets called first. THEN, the actions get executed. You cannot flush the update() method accidentally like you can with an action. You don't have to be careful about strong/weak relationships causing memory leaks because you are referring to objects from inside a closure like you do with an action.
Suggested reads:
SKAction API reference
SKScene API reference : read about the frame processing in SpriteKit. It will help you understand how they put everything together at every frame.
I hope it makes things clearer.
I'm pretty sure that SKAction's timing facilities are based on the same game loop that is calling update.
The advantage of SKAction is that it's fire and forget for you, while using update would get awkward with setting and checking a bunch of timer variables.
I don't have a ton of experience with SpriteKit but I do have some experience making games and animations in iOS.
There is a class called CADisplayLink that fires a call to a delegate every time the screen is refreshed, this is a great way to update the screen, either in a game or in an animation, because you can know it will be called every frame and no more.
I'm not sure if SpriteKit uses that class to fire the update method, but I'm sure it uses something similar. This is usually called the run loop.
SKActions run on top of this run loop.
By creating your own run loop using a wait action, not only you're not gaining any benefits, you could be introducing inconsistencies in the way your logic is run.
Imagine that you have your wait action set to 0.01 seconds (I rounded it down for simplicity). If the screen is refreshing faster than you expect, and the action is updated every 0.009 seconds, the first time it's checked, it won't fire because there's a remaining 0.001 second on the wait command, so another 0.009 seconds will pass, and your code will be executed after 0.018 seconds, instead of your desired 0.01. Not only that, but two frames will have passed between the execution.
If you use the update function, you can know that your logic will be executed once every screen refresh, and no more.

How do I loop something and wait for something before re-looping? [swift]

Im basically trying to make a segment of code run over and over once they tap once, and run only if the previous run was completed.
How would I do this exactly, Im completely new to Swift.
At the end of your first loop, put a variable that sets to true and then under the IBAction where they tap once, check if that variable is true or not and if it is true, do your re-loop.
Another way you could do it is loop in the viewDidLoad, which is called before any visuals appear. This way, there's no way they could tap the button or whatever you're monitoring until the view has appeared, which is a separate function.
But I doubt you need to wait for a loop to finish, because the execution time of a loop is so fast it will have happened before they can tap (unless it's a very long loop).
1) IBAction ( code would start to run)
2) You could use a if statement to check to see if what you want done is done.
3) You could use a for to determine how long the code is ran.

runBlock not working in sequence?

I am trying to create a basic spawn sequence- the block must be created, moveDownLeft, and then removeLeft. moveDownLeft and removeLeft work fine on their own when the block is added using self.addChild(block1) previously, however I need to have self.addchild within the sequence.
The only way that I can see to do this is use runBlock, and I looked at this question when I got an error using that: Swift: SKAction.runBlock -> Missing argument for parameter 'completion' in call BUT WHY?
So now I am left with this:
block1.runAction(SKAction.sequence([SKAction.runBlock({ self.addChild(self.block1) }), moveDownLeft, removeLeft]))
And nothing in the sequence works because the block is not created in the first place. Why is this happening?
Your code fragment is too short but it looks like a typical chicken and egg problem.
node can only run actions once it has been added as child and thus becomes part of the scene graph
your node is supposed to run an action that will eventually add itself to the scene graph but it's not in the scene graph yet so it won't run that action
Add the node as child first, then run the action. If you need the node to be inactive for some time, simply set it's visible property to NO for the duration. You kay also ned to change other properties, ie postpone creation of the physics body.