Increase jump height on longer touch until maximum height

一笑奈何 提交于 2019-12-10 10:06:20

问题


I'm using the following methods to make my character jump:

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

}

This works fine, but I want to make the character jump a certain height based on the length of the touch until a maximum. I've tried something with frame durations but this didn't work.

How can I make the character jump based on touch length until a maximum height?


回答1:


You can disable the body's velocity on the y axis as you lift your finger and if you want to cap the maximum jump height use an optional variable to store the initial y position just before the jump and check the delta between your current y poistion to the initial y position:

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
}

and reset it when done:

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

declare the initialJumpY in your node class where the touch methods are defined:

class MyNode: SKNode {

    var initialJumpY: Float?

}



回答2:


Start a timer action when your touch begins and end it when the touch ends. Contained inside would be something like the following,

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

Then in your touchesEnded, remove the action and use the value of force to execute your jump.

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


来源:https://stackoverflow.com/questions/30223997/increase-jump-height-on-longer-touch-until-maximum-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!