Swift - 触摸节点后延迟,直到可以再次触摸

时间:2016-09-28 07:39:48

标签: ios swift xcode sprite-kit skspritenode

在我的游戏中,我按顺序使用SKActions将节点(在这种情况下为桨)移动到某个位置并返回,这部分工作正常。只要用户在屏幕上触摸,桨就会移动。我的代码如下:

    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

然而,我需要创建一个5秒的延迟,在此期间如果触摸器不能移动桨(例如禁用一段时间)。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

我会提供一个替代好的T. Benjamin Larsen answer's,它可以在类似于您的常见情况下使用,您可以将 SKTUtils library与{{1}一起使用} extensions:

SKAction

因此,当您需要在一定延迟后执行操作时,您可以直接执行:

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))
    }
}

答案 1 :(得分:0)

删除上面代码的最后一行:

paddleRTouched = false

...并用类似于此的东西替换它:

    let allowPaddleTouchAction = SKAction.run {
        self.paddleRTouched = false
    }
    let allowTouchDelay = SKAction.wait(forDuration: 5)
    run(SKAction.sequence([allowTouchDelay, allowPaddleTouchAction]))