我使用以下方法让我的角色跳跃:
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) {
}
这很好用,但我想让角色根据触摸的长度跳到一定高度,直到达到最大值。我已经尝试了帧持续时间的东西,但这没有用。
如何根据触摸长度使角色跳跃到最大高度?
答案 0 :(得分:1)
触摸开始时启动计时器操作,触摸结束时结束计时器操作。内部包含的内容类似于以下内容,
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中,删除动作并使用force的值来执行你的跳跃。
self.removeActionForKey("repeatAction")
self.character.physicsBody?.applyImpulse(CGVectorMake(0, force))
答案 1 :(得分:1)
您可以在抬起手指时禁用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
}
在节点类中声明定义触摸方法的initialJumpY
:
class MyNode: SKNode {
var initialJumpY: Float?
}