Reputation: 71
In my game I use SKActions in a sequence to move a node (paddle in this case) to a certain location and back, this part is working fine. The paddle moves whenever the user touches it on the screen. My code for this is as follows:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first!
let touchLocation = touch.location(in: self)
let nodeTouched:SKPhysicsBody? = self.physicsWorld.body(at: touchLocation)
let ballNode = self.childNode(withName: ballName)
if nodeTouched?.node?.name == RpaddleName {
if !paddleRTouched {
paddleRTouched = true
let Rpaddle = self.childNode(withName: RpaddleName) as! SKSpriteNode
let startPosition = CGPoint(x: 301.7, y: 87)
let newPosition = CGPoint(x: 226.7, y: 87)
let moveToNew = SKAction.move(to: newPosition, duration: 0.5)
let moveToOld = SKAction.move(to: startPosition, duration: 0.5)
let delay = SKAction.wait(forDuration: 0.5)
let sequence = SKAction.sequence([moveToNew,delay,moveToOld])
Rpaddle.run(sequence)
paddleRTouched = false
However I need to create a 5 second delay during which the paddle cannot be moved if it toucher (e.g disabling for a period of time) . How could I do this?
Upvotes: 2
Views: 281
Reputation: 35392
I would give an alternative to the good T. Benjamin Larsen answer's that could be useful in frequently situations similar to your, you can use the SKTUtils library with the SKAction
extensions:
public extension SKAction {
/**
* Performs an action after the specified delay.
*/
public class func afterDelay(_ delay: TimeInterval, performAction action: SKAction) -> SKAction {
return SKAction.sequence([SKAction.wait(forDuration: delay), action])
}
/**
* Performs a block after the specified delay.
*/
public class func afterDelay(_ delay: TimeInterval, runBlock block: @escaping () -> Void) -> SKAction {
return SKAction.afterDelay(delay, performAction: SKAction.run(block))
}
}
So , when you need to perform an action after a certain delay you can do directly:
run(SKAction.afterDelay(5, runBlock: {
self.paddleRTouched = false
}))
Upvotes: 1
Reputation: 6383
Remove he last line of the code above:
paddleRTouched = false
...and replace it with something akin to this:
let allowPaddleTouchAction = SKAction.run {
self.paddleRTouched = false
}
let allowTouchDelay = SKAction.wait(forDuration: 5)
run(SKAction.sequence([allowTouchDelay, allowPaddleTouchAction]))
Upvotes: 0