【问题标题】:How would I set a timer where my node could jump every two seconds in Swift Xcode?我将如何设置一个计时器,让我的节点在 Swift Xcode 中每两秒跳一次?
【发布时间】:2015-05-05 02:38:00
【问题描述】:

我有这段代码,每次点击屏幕时我的节点都会跳转。我希望在点击屏幕时让节点再次跳转之前等待两三秒。我该怎么做?谢谢!

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    var touch: UITouch = touches.first as! UITouch

    theHero.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 250))
    theHero.texture = SKTexture(imageNamed: "jumpman")
    println("works")


 }

【问题讨论】:

  • 您要在两秒后忽略所有点击吗?或者你想记住在两秒不应期有过一次敲击,如果有敲击,则在这段时间结束后立即再次跳转?
  • 第二个就是我要找的。​​span>
  • 这是touchesBegan:withEvent: 方法在您的SKScene 中吗?
  • 是的,它在 SKScene 中。

标签: ios xcode swift touch


【解决方案1】:

由于您使用的是 SpriteKit,因此处理此问题的最简单方法是使用 SKScene.update 方法。如果场景已呈现且未暂停,SpriteKit 每帧调用一次此方法。

touchesBegan:withEvent: 中,只需设置一个指示请求跳转的标志。在update: 中,检查是否设置了标志以及自上次跳转后是否经过了足够的时间。如果两者都为真,则清除标志,更新“最后跳转时间”属性,然后跳转。

class MyScene: SKScene {

    let theHero: SKSpriteNode = SKSpriteNode()
    var lastJumpTime: NSTimeInterval = 0
    var jumpIsPending: Bool = false
    static let JumpCooldownSeconds: NSTimeInterval = 2

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        jumpIsPending = true
    }

    override func update(currentTime: NSTimeInterval) {
        jumpIfNeeded(currentTime)
        // ... other per-frame stuff
    }

    private func jumpIfNeeded(currentTime: NSTimeInterval) {
        if jumpIsPending && lastJumpTime + MyScene.JumpCooldownSeconds <= currentTime {
            jumpIsPending = false
            lastJumpTime = currentTime

            theHero.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 250))
            theHero.texture = SKTexture(imageNamed: "jumpman")
            println("works")
        }
    }

}

【讨论】:

  • 谢谢哥们,它工作得很好。我尝试用 runBlock 来做,但它不适合我。再次感谢!
  • 我有一个问题。我以前从未使用过静态...它有什么作用?
  • 正如我在这里使用的那样,static 有两个效果:它将属性与类 (MyScene) 本身而不是类的实例相关联,并且它的行为就像声明了 final ,意味着子类不能覆盖它。
【解决方案2】:

这就是属性的用途——在方法调用之间维护状态。每次跳跃时,将当前时间(触摸的timestamp)存储在属性中。现在,下一次,查看当前时间(new 触摸的timestamp)并减去存储的时间。如果不超过 2 秒,则什么也不做。如果是,则存储新的当前时间并跳转。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    相关资源
    最近更新 更多