我如何设置一个计时器,让我的节点可以在 Swift Xcode 中每两秒跳一次?
How would I set a timer where my node could jump every two seconds in Swift Xcode?
我有这段代码,每次我点击屏幕时我的节点都会跳转。我希望在我点击屏幕时让节点再次跳转之前等待两三秒。我该怎么做?谢谢!
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")
}
这就是属性的用途 - 在方法调用之间保持状态。每次跳跃时,将当前时间(触摸的 timestamp
)存储在 属性 中。现在,下一次,查看当前时间(new 触摸的 timestamp
)并减去存储的时间。如果不超过 2 秒,则什么都不做。如果是,存储新的当前时间并跳转。
由于您使用的是 SpriteKit,处理此问题的最简单方法是使用 SKScene.update
方法。如果场景已呈现且未暂停,SpriteKit 每帧调用此方法一次。
在touchesBegan:withEvent:
中,只是设置了一个表示请求跳转的标志。在 update:
中,检查标志是否已设置以及自上次跳跃以来是否经过了足够的时间。如果两者都为真,则清除标志,更新 "last jump time" 属性,然后跳转。
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")
}
}
}
我有这段代码,每次我点击屏幕时我的节点都会跳转。我希望在我点击屏幕时让节点再次跳转之前等待两三秒。我该怎么做?谢谢!
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")
}
这就是属性的用途 - 在方法调用之间保持状态。每次跳跃时,将当前时间(触摸的 timestamp
)存储在 属性 中。现在,下一次,查看当前时间(new 触摸的 timestamp
)并减去存储的时间。如果不超过 2 秒,则什么都不做。如果是,存储新的当前时间并跳转。
由于您使用的是 SpriteKit,处理此问题的最简单方法是使用 SKScene.update
方法。如果场景已呈现且未暂停,SpriteKit 每帧调用此方法一次。
在touchesBegan:withEvent:
中,只是设置了一个表示请求跳转的标志。在 update:
中,检查标志是否已设置以及自上次跳跃以来是否经过了足够的时间。如果两者都为真,则清除标志,更新 "last jump time" 属性,然后跳转。
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")
}
}
}