[如何在玩家触发跳跃后添加延迟,以使跳跃不会被触发得太频繁(或被发送垃圾邮件?
func jumpRight() {
player.physicsBody?.velocity = CGVector(dx: 0,dy: 0)
player.physicsBody?.applyImpulse(CGVector (dx: 100, dy: 500))
}
func jumpLeft() {
player.physicsBody?.velocity = CGVector(dx: 0,dy: 0)
player.physicsBody?.applyImpulse(CGVector (dx: -100, dy: 500))
}
一种简单的方法是使用布尔值标志,当播放器触发跳跃时该标志会改变,并在短暂的延迟后自动重置。
var canJump: Bool = True
func jumpRight() {
guard canJump == True else { return }
self.canJump = False
player.physicsBody?.velocity = CGVector(dx: 0,dy: 0)
player.physicsBody?.applyImpulse(CGVector (dx: 100, dy: 500))
DispatchQueue.main.asyncAfter(deadline: .now()+0.2) {
self.canJump = True
}
}
有几种方法可以执行此操作,无论您在何处设置了跳转按钮,都必须选择要选择的目标(向右跳转或向左跳转),以检查是否按下了跳转命令,当跳转命令完成时。
我将从在您的函数上添加完成处理程序开始。
func jumpRight(arg: Bool, completion: (Bool) -> ()) {
completion(arg)
}
通过这样做,您正在确定函数何时完成。下面是您调用跳转按钮命令的位置。无论您在何处定义了操作,都应调用此方法。
jumpRight(arg: true, completion: { (success) -> Void in
print("Second line of code executed")
if success { // this will be equal to whatever value is set in this method call
print("true")
} else {
print("false")
}
})
如果该个人发送了垃圾邮件,则将从完成处理程序中打印“ false”。在该位置,您可以防止用户再次跳转,直到该功能定义的操作完成为止。
我的解决方案是尝试这样的事情
var lastUpdateTime: TimeInterval = 0
var dt: TimeInterval = 0
let jumpHysterisisTimeLimit: TimeInterval = 0.2
var jumpHysterisisTimer: TimeInterval = 0
var jumpAGoGo: Bool = false
func updateGameLoopTimer(currentTime: TimeInterval) {
if lastUpdateTime > 0 {
dt = currentTime - lastUpdateTime
} else {
dt = 0
}
lastUpdateTime = currentTime
}
override func update(_ currentTime: TimeInterval) {
updateGameLoopTimer(currentTime: currentTime)
}
func isJumpAGoGo() {
if jumpAGoGo {
jumpHysterisisTimer += dt
if jumpHysterisisTimer >= jumpHysterisisTimeLimit {
jumpHysterisisTimer = 0
jumpAGoGo = false
}
}
}
func jumpRight() {
if !jumpAGoGo {
jumpAGoGo = true
player.physicsBody?.velocity = CGVector(dx: 0,dy: 0)
player.physicsBody?.applyImpulse(CGVector (dx: 100, dy: 500))
}
}
func jumpLeft() {
if !jumpAGoGo {
jumpAGoGo = true
player.physicsBody?.velocity = CGVector(dx: 0,dy: 0)
player.physicsBody?.applyImpulse(CGVector (dx: -100, dy: 500))
}
}
然后您可以使用jumpHysterisisTimeLimit值来适应您的需求。