长时间触摸时增加跳跃高度,直到最大高度

Increase jump height on longer touch until maximum height

我正在使用以下方法让我的角色跳跃:

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

    if onGround && !gameOver {
        self.character.physicsBody?.applyImpulse(CGVectorMake(0, 75))
        self.onGround = false
    }

}

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {

}

这很好用,但我想让角色根据触摸的长度跳到一定高度,直到达到最大值。我已经尝试过一些带有帧持续时间的东西,但这没有用。

如何让角色根据触摸长度跳到最大高度?

触摸开始时开始计时动作,触摸结束时结束。包含在里面会像下面这样,

var force = 0.0

let timerAction = SKAction.waitForDuration(1.0)
let update = SKAction.runBlock({
    if(force < 100.0){
        force += 1.0
    }
})
let sequence = SKAction.sequence([timerAction, update])
let repeat = SKAction.repeatActionForever(sequence)
self.runAction(repeat, withKey:"repeatAction")

然后在你的touchesEnded中去掉action,使用force的值来执行你的跳跃。

self.removeActionForKey("repeatAction")
self.character.physicsBody?.applyImpulse(CGVectorMake(0, force))

您可以在抬起手指时禁用 body 在 y 轴上的速度,如果您想限制最大跳跃高度,请使用可选变量来存储跳跃前的初始 y 位置并检查当前 y 位置与初始 y 位置之间的增量:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    if onGround && !gameOver {
        if self.initialJumpY == nil {
           self.initialJumpY = self.character.position.y
        }

        if self.character.position.y - self.initialJumpY < <Your cap value> {            
           self.character.physicsBody?.applyImpulse(CGVectorMake(0, 75))              
        } else {
           self.character.physicsBody?.velocity.dy = 0.0
        }

        self.onGround = false
}

并在完成后重置它:

    override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
         self.character.physicsBody?.velocity.dy = 0.0
         self.initialJumpY = nil
    }

在定义触摸方法的节点 class 中声明 initialJumpY

class MyNode: SKNode {

    var initialJumpY: Float?

}