Antonio C Antonio C - 1 year ago 90
Swift Question

Swift - After node is touched delay until it can be touched again

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])
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?

Answer Source

Remove he last line of the code above:

paddleRTouched = false

...and replace it with something akin to this:

    let allowPaddleTouchAction = {
        self.paddleRTouched = false
    let allowTouchDelay = SKAction.wait(forDuration: 5)
    run(SKAction.sequence([allowTouchDelay, allowPaddleTouchAction]))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download