Single SKAction Animation on several nodes using a loop with completion handler - ios

Objective: Apply a single SKAction Animation on several nodes using a loop, while waiting for completion handler.
func animateShuffle(cards: [Card], completionHandler:(success: Bool) -> Void) {
var rotationInRadians:CGFloat = CGFloat(M_PI)
var rotateFirstDeck = SKAction.rotateByAngle(rotationInRadians, duration: 1.0)
var moveFirstDeck = SKAction.moveToX(-150, duration: 1.0)
var returnToOrigPosition = SKAction.moveToX(-125, duration: 1.0)
var firstDeckSequence = SKAction.sequence([moveFirstDeck, rotateFirstDeck, returnToOrigPosition])
var rotateSecondDeck = SKAction.rotateByAngle(-rotationInRadians, duration: 1.0)
var moveSecondDeck = SKAction.moveToX(-100, duration: 1.0)
var secondDeckSequence = SKAction.sequence([moveSecondDeck, rotateSecondDeck, returnToOrigPosition])
for (index, Card) in enumerate(cards){
if index % 2 == 0{
Card.image.runAction(firstDeckSequence)
}
else{
Card.image.runAction(secondDeckSequence)
}
}
//hack
cards[0].image.runAction(firstDeckSequence, completion: { () -> Void in
completionHandler(success: true)
})
}
Here I call the function which kicks off another Animation:
animateShuffle(newDeck.deck, completionHandler: { (success) -> Void in
print("entered")
var drawnCards = [Card]()
if let areThereCards = newDeck.drawCards(4){
drawnCards = areThereCards
}
self.dealCards(drawnCards)
})
I used a hack to get to 99% of where I want to be but my gut tells me there is better way to do this. How can I tell when the last node has finished animating?

Both sequences run for 3 seconds so when the first completion block runs you can safely assume they are all done. To be 100% certain set a bool ivar in the completion handler and then run your post-sequence code in the didEvaluateActions method of the scene.
Alternatively count how many sequences you run, then increase a counter in completion block, and run your code when both counters match.

Related

iOS (Swift): Changing UILabel text with a for loop

I have a for loop as follows:
#objc private func resetValue() {
for i in stride(from: value, to: origValue, by: (value > origValue) ? -1 : 1) {
value = i
}
value = origValue
}
And when value is set it updates a label:
private var value = 1 {
didSet {
updateLabelText()
}
}
private func updateLabelText() {
guard let text = label.text else { return }
if let oldValue = Int(text) { // is of type int?
let options: UIViewAnimationOptions = (value > oldValue) ? .transitionFlipFromTop : .transitionFlipFromBottom
UIView.transition(with: label, duration: 0.5, options: options, animations: { self.label.text = "\(value)" }, completion: nil)
} else {
label.text = "\(value)"
}
}
I was hoping that if value=5 and origValue=2, then the label would flip through the numbers 5,4,3,2. However, this is not happening - any suggestions why, please?
I've tried using a delay function:
func delay(_ delay:Double, closure: #escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
and then placing the following within the stride code:
delay(2.0) { self.value = i }
However, this doesn't seem to work either.
Thanks for any help offered.
UIKit won't be able to update the label until your code is finished with the main thread, after the loop completes. Even if UIKit could update the label after each iteration of the loop, the loop is going to complete in a fraction of a second.
The result is that you only see the final value.
When you attempted to introduce the delay, you dispatched the update to the label asynchronously after 0.5 second; Because it is asynchronous, the loop doesn't wait for the 0.5 second before it continues with the next iteration. This means that all of the delayed updates will execute after 0.5 seconds but immediately one after the other, not 0.5 seconds apart. Again, the result is you only see the final value as the other values are set too briefly to be visible.
You can achieve what you want using a Timer:
func count(fromValue: Int, toValue: Int) {
let stride = fromValue > toValue ? -1 : 1
self.value = fromValue
let timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats:true) { [weak self] (timer) in
guard let strongSelf = self else {
return
}
strongSelf.value += stride
if strongSelf.value == toValue {
timer.invalidate()
}
}
}
I would also update the didSet to send the oldValue to your updateLabelText rather than having to try and parse the current text.
private var value = 1 {
didSet {
updateLabelText(oldValue: oldValue, value: value)
}
}
private func updateLabelText(oldValue: Int, value: Int) {
guard oldValue != value else {
self.label.text = "\(value)"
return
}
let options: UIViewAnimationOptions = (value > oldValue) ? .transitionFlipFromTop : .transitionFlipFromBottom
UIView.transition(with: label, duration: 0.5, options: options, animations: { self.label.text = "\(value)" }, completion: nil)
}

How to create a closure inside a closure? [duplicate]

This question already has answers here:
Calling Swift Closure Inside Closure
(4 answers)
Closed 4 years ago.
I am trying to create a function in Swift so I can make a repeating animation (I know you can use .repeat, but I do not want to use that). In my completion closure, I am getting an error. Here is my code so far:
import UIKit
var withDurationVar:TimeInterval = 0
var optionsVar:UIViewAnimationOptions?
var iterateVar = 0
var animationsVar:(() -> ()?)?
var completionVar:(() -> ()?)?
var numberOfIterations = 0
func repeatingAnimation(withDuration:TimeInterval, options:UIViewAnimationOptions, iterate:Int, animations:#escaping () -> (), completion:#escaping () -> ()) {
withDurationVar = withDuration
optionsVar = options
iterateVar = iterate
animationsVar = animations
completionVar = completion
}
func animationRepeat() {
UIView.animate(withDuration: withDurationVar, delay: 0, options: optionsVar!, animations: animationsVar as! () -> Void, completion: { (Finished) in
// Increase number of iterations
numberOfIterations += 1
// If it has not yet done every iteration needed
if numberOfIterations != iterateVar {
// Repeat animation
animationRepeat()
}
else {
completionVar // Where I get an error. 'Expression resolves to an unused I-value'
}
})
}
I can do this however:
func animationRepeat() {
UIView.animate(withDuration: withDurationVar, delay: 0, options: optionsVar!, animations: animationsVar as! () -> Void, completion: completionVar)
}
So how can I have the completion from my repeatingAnimation function into the completion of animationRepeat with the rest of the code as well? Thanks!
I have updated my code if anyone want to use it as a repeating animation function :)
import UIKit
// Make some variables to be accessed across the file
var withDurationVar:TimeInterval = 0
var optionsVar:UIViewAnimationOptions?
var iterateVar = 0
var animationsVar:(() -> ()?)?
var completionVar:(() -> ()?)?
var numberOfIterations = 0
// The function to call
func repeatingAnimation(withDuration:TimeInterval, options:UIViewAnimationOptions, iterate:Int, animations:#escaping () -> (), completion:#escaping () -> ()) {
// Set the global variables from the parameters
withDurationVar = withDuration
optionsVar = options
iterateVar = iterate
animationsVar = animations
completionVar = completion
// Has not started repeating yet
numberOfIterations = 0
// Start repeat
animationRepeatForFunction()
}
// The function which is ONLY called by the repeatingAnimation or itself, not the user
func animationRepeatForFunction() {
UIView.animate(withDuration: withDurationVar, delay: 0, options: optionsVar!, animations: {animationsVar?()}, completion: { (Finished) in
// Increase number of iterations
numberOfIterations += 1
// If it has not yet done every iteration needed
if numberOfIterations < iterateVar {
// Repeat animation
animationRepeatForFunction()
}
else {
// Perform what the user wanted to do after the repeating animation
completionVar?()
}
})
}
Call the function using repeatingAnimation(...)
The .repeat function can only really be used for infinite loops, which do not need to be stopped. In my case, I wanted to repeat a finite amount of times (terminates), so I made this custom function which can have its own .swift file.

Break a loop inside an animation block

I'm trying to break a for-loop after a completed UIView animation. Here is the following snippet:
public func greedyColoring() {
let colors = [UIColor.blue, UIColor.green, UIColor.yellow, UIColor.red, UIColor.cyan, UIColor.orange, UIColor.magenta, UIColor.purple]
for vertexIndex in 0 ..< self.graph.vertexCount {
let neighbours = self.graph.neighborsForIndex(vertexIndex)
let originVertex = vertices[vertexIndex]
print("Checking now Following neighbours for vertex \(vertexIndex): \(neighbours)")
var doesNotMatch = false
while doesNotMatch == false {
inner: for color in colors{
UIView.animate(withDuration: 1, delay: 2, options: .curveEaseIn, animations: {
originVertex.layer.backgroundColor = color.cgColor
}, completion: { (complet) in
if complet {
let matches = neighbours.filter {
let vertIdx = Int($0)!
print("Neighbour to check: \(vertIdx)")
let vertex = self.vertices[vertIdx-1]
if vertex.backgroundColor == color{
return true
}else{
return false
}
}
//print("there were \(matches.count) matches")
if matches.count == 0 {
// do some things
originVertex.backgroundColor = color
doesNotMatch = true
break inner
} else {
doesNotMatch = false
}
}
})
}
}
}
}
Basically this method iterate over a Graph and checks every vertex and its neighbours and give the vertex a color that none of its neighbours has. Thats why it has to break the iteration at the first color that hasn't been used. I tried to use Unlabeled loops but it still doesn't compile (break is only allowed inside a loop). The problem is that I would like to visualise which colors have been tested. Thats why I'm using the UIView.animate()
Is there anyway to solve my problem?
You need to understand, that the completion block that you pass to the animate function is called after the animation has finished, which is a long time (in computer time) after your for loop has iterated through the colors array. You set the duration to be 1 second, which means that the completion is called 1 second later. Since the for loop isn't waiting for your animation to finish, they will all start animating at the same time (off by some milliseconds perhaps). The for loop has completed way before the animation has completed, which is why it doesn't make sense to break the for loop, since it is no longer running!
If you want to see this add a print("Fire") call right before the UIView.animate function is called and print("Finished") in the completion block. In the console you should see all the fire before all the finished.
You should instead queue the animations, so that they start and finish one after the other.
As Frederik mentioned, the animations the order in execution of the next in your for loop is not synchronous with the order of your completions. This means that the for loop will keep cycling no matter of your blocks implementations.
An easy fix would be to create the animations by using CABasicAnimation and CAAnimationGroup. So that the product of your for loop would be a chain of animations stacked in an animation group.
This tutorial will give you an idea on how to use CABasicAnimation and CAAnimationGroup: https://www.raywenderlich.com/102590/how-to-create-a-complex-loading-animation-in-swift
You can use this approach, because the condition to break your for loop is given by parameters that are not dependent by the animation itself. The animations will be executed anyway once they will be attached to the view you are trying to animate.
Hope this helps.
Just modifying your code a little bit. Its a old school recursion but should work. Assuming all the instance variables are available here is a new version.
public func greedyColoring(vertex:Int,colorIndex:Int){
if vertexIndex > self.graph.vertexCount { return }
if colorIndex > color.count {return}
let neighbours = self.graph.neighborsForIndex(vertexIndex)
let originVertex = vertices[vertexIndex]
let color = self.colors[colorIndex]
UIView.animate(withDuration: 1, delay: 2, options: .curveEaseIn, animations: {
originVertex.layer.backgroundColor = color.cgColor
}, completion: { (complet) in
if complet {
let matches = neighbours.filter {
let vertIdx = Int($0)!
print("Neighbour to check: \(vertIdx)")
let vertex = self.vertices[vertIdx-1]
//No idea what you are trying to do here. So leaving as it is.
if vertex.backgroundColor == color{
return true
}else{
return false
}
}
//print("there were \(matches.count) matches")
if matches.count == 0 {
// do some things
originVertex.backgroundColor = color
greedyColoring(vertex: vertex++,colorIndex:0)
} else {
greedyColoring(vertex: vertex,colorIndex: colorIndex++)
}
}
})
}
Now we can call this function simply
greedyColor(vertex:0,colorIndex:0)
As mentioned before, the completion blocks are all called asynchronously, and thus do not exist within the for loop. Your best bet is to call a common method from within the completion blocks which will ignore everything after the first call.
var firstMatch: UIColor?
func foundMatch (_ colour: UIColor)
{
if firstMatch == nil
{
firstMatch = colour
print (firstMatch?.description ?? "Something went Wrong")
}
}
let colours: [UIColor] = [.red, .green, .blue]
for colour in colours
{
UIView.animate(withDuration: 1.0, animations: {}, completion:
{ (success) in
if success { foundMatch (colour) }
})
}

Add a delay to a function in SpriteKit

I would like to be able to only allow the player to shoot a missile every 0.7 seconds. How do I do this? Here is my code. I have tried other methods I found on this site but they do not work.
func fireTorpedo() {
if !self.player.isPaused
{
if isSoundEffect == true {
self.run(SKAction.playSoundFileNamed("Rocket", waitForCompletion: false))
}
let torpedoNode = SKSpriteNode(imageNamed: "Rocket")
torpedoNode.position = player.position
torpedoNode.position.y += 5
torpedoNode.physicsBody = SKPhysicsBody(circleOfRadius: torpedoNode.size.width / 2)
torpedoNode.physicsBody?.isDynamic = true
torpedoNode.physicsBody?.categoryBitMask = photonTorpedoCategory
torpedoNode.physicsBody?.contactTestBitMask = alienCategory
torpedoNode.physicsBody?.collisionBitMask = 0
torpedoNode.physicsBody?.usesPreciseCollisionDetection = true
self.addChild(torpedoNode)
let animationDuration:TimeInterval = 0.5
var actionArray = [SKAction]()
actionArray.append(SKAction.move(to: CGPoint(x: player.position.x, y: self.frame.size.height + 10), duration: animationDuration))
actionArray.append(SKAction.removeFromParent())
torpedoNode.run(SKAction.sequence(actionArray))
}
}
I like to do that like this:
class GameScene:SKScene {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if action(forKey: "shooting") == nil {
let wait = SKAction.wait(forDuration: 0.7)
run(wait, withKey: "shooting")
print("shot fired")
}
}
}
While there is a key "shooting" found on a scene, you can't shoot anymore. In real game, this would be likely the part of a node (an action should be run on a node).
First, add a flag at class-level that indicates whether the player can fire a torpedo.
var canFireTorpedo = true
Then, at the end of the fireTorpedo method, set canFireTorpedo to false, then set it to true again after 0.7 seconds:
canFireTorpedo = false
player.run(SKAction.sequence([
SKAction.wait(forDuration: 0.7),
SKAction.run { [weak self] in self?.canFireTorpedo = true }]))
After that, check canFireTorpedo at the start of the method:
func fireTorpedo() {
if canFireTorpedo {
// put everything in the method here, including the parts I added
}
}
Hopefully this code is self-explanatory.
To launch every 0.7 seconds you can do:
let actionKey = "repeatLaunchMethod"
let launchMethod = SKAction.afterDelay(0.7, runBlock: {
[weak self] in
guard let strongSelf = self else { return }
strongSelf.fireTorpedo()
})
// do this if you want to repeat this action forever
self.player.run(SKAction.repeatForever(launchMethod), withKey: actionKey)
// do this if you want to repeat this action only n times
// self.player.run(SKAction.repeat(launchMethod, count: 5), withKey: actionKey)
To stop this action you can do:
if self.player.action(forKey: actionKey) != nil {
self.player.removeAction(forKey: actionKey)
}
Extension used to render the code more readable:
extension SKAction {
/**
* Performs an action after the specified delay.
*/
class func afterDelay(_ delay: TimeInterval, performAction action: SKAction) -> SKAction {
return SKAction.sequence([SKAction.wait(forDuration: delay), action])
}
/**
* Performs a block after the specified delay.
*/
class func afterDelay(_ delay: TimeInterval, runBlock block: #escaping () -> Void) -> SKAction {
return SKAction.afterDelay(delay, performAction: SKAction.run(block))
}
}

For loop in swift seems to randomly choose increment

I have a for loop that executes animations and then removes them on completion, and I am trying to call another method upon completion. Here is my code:
func animateMatch(completion: () -> ()) {
var movingShape = level.shapeAtColumn(pointsContainingShapeArray[0].Column, row: pointsContainingShapeArray[0].Row)
let destinationShape = level.shapeAtColumn(pointsContainingShapeArray[0].Column, row: pointsContainingShapeArray[0].Row)
for everyShape in 1..<pointsContainingShapeArray.count {
movingShape = level.shapeAtColumn(pointsContainingShapeArray[everyShape].Column, row: pointsContainingShapeArray[everyShape].Row)
let Duration: NSTimeInterval = 1
let moveShapes = SKAction.moveTo((destinationShape?.sprite!.position)!,duration: Duration)
moveShapes.timingMode = .EaseOut
movingShape?.sprite?.runAction(moveShapes, completion: {
movingShape?.sprite?.removeFromParent()
print("Removed shape \(everyShape)")
if everyShape == pointsContainingShapeArray.count {
completion()
}
})
}
}
Basically the idea is that every shape in the array after the first position moves to the position of the first one and then removes it from the scene. This works fine, but my completion was getting called at random times every time. So finally I added the print statement in there. Here was the output:
Removed shape 3
Removed shape 1
Removed shape 4
Removed shape 2
At this point I got so frustrated I decided it was time for stack overflow. I can't possibly figure out what's going on here. Thanks for any help!
Here is the code that calls this method:
func handleSwipe(move: Move) {
view.userInteractionEnabled = false
level.performMove(move)
scene.animateMove(move) {
self.view.userInteractionEnabled = true
if hasMatch {
self.view.userInteractionEnabled = false
self.scene.animateMatch() {
self.scene.addNewSpritesForShapes(pointsContainingShapeArray)
hasMatch = false
self.view!.userInteractionEnabled = true
}
}
}
}
The issue isn't the for loop, it's the asynchronous nature of the run action.
When you call moveShapes action, it runs asynchronously before calling the completion back on the original thread. This can happen in any order. You can see this yourself by calling your print synchronously:
for everyShape in 1..<pointsContainingShapeArray.count {
print("Synchronous loop: \(everyShape)")
}
I think you'd be better off using a dispatch_group_t for your final completion:
func animateMatch(completion: () -> ()) {
var movingShape = level.shapeAtColumn(pointsContainingShapeArray[0].Column, row: pointsContainingShapeArray[0].Row)
let destinationShape = level.shapeAtColumn(pointsContainingShapeArray[0].Column, row: pointsContainingShapeArray[0].Row)
// HERE
let group = dispatch_group_create()
dispatch_group_notify(group, dispatch_get_main_queue(), completion)
//
for everyShape in 1..<pointsContainingShapeArray.count {
// HERE
dispatch_group_enter(group)
//
movingShape = level.shapeAtColumn(pointsContainingShapeArray[everyShape].Column, row: pointsContainingShapeArray[everyShape].Row)
let Duration: NSTimeInterval = 1
let moveShapes = SKAction.moveTo((destinationShape?.sprite!.position)!,duration: Duration)
moveShapes.timingMode = .EaseOut
movingShape?.sprite?.runAction(moveShapes, completion: {
movingShape?.sprite?.removeFromParent()
print("Removed shape \(everyShape)")
// HERE
dispatch_group_leave(group)
//
})
}
}

Resources