恒定速度,同时仍然能够施加脉冲

Constant velocity while still being able to apply an impulse

我正在制作一个游戏,其中主要 sprite/player 不断移动,he/she 需要跳过障碍。

我需要有关如何为我的移动精灵设置恒定速度的帮助。当我尝试在 SpriteKit 更新功能中执行此操作时,我无法在用户点击屏幕时应用跳跃的冲动。

这是我的代码。我评论了我遇到问题的地方:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
   /* Called when a touch begins */
    if (gameStarted == false) {
        gameStarted = true

        mainSprite.physicsBody?.affectedByGravity = true
        mainSprite.physicsBody?.allowsRotation = true
        let spawn = SKAction.runBlock({
            () in

            self.createWalls()
        })


        let delay = SKAction.waitForDuration(1.5)

        let spawnDelay = SKAction.sequence([spawn, delay])

        let spawnDelayForever = SKAction.repeatActionForever(spawnDelay)

        self.runAction(spawnDelayForever)

        let distance = CGFloat(self.frame.height + wallPair.frame.height)

        let movePipes = SKAction.moveByX(0, y: -distance - 50, duration: NSTimeInterval(0.009 * distance)) // Speed up pipes

        let removePipes = SKAction.removeFromParent()

        moveAndRemove = SKAction.sequence([movePipes, removePipes])

    } else {
        if died == true {

        }
        else {
            mainSprite.physicsBody?.applyImpulse(CGVectorMake(0, 20)) // TRYING TO APPLY AN IMPULSE TO MY SPRITE SO IT CAN JUMP AS IT MOVES
        }
    }



    for touch in touches {
        let location = touch.locationInNode(self)
    }
}

override func update(currentTime: CFTimeInterval) {
    /* Called before each frame is rendered */
    updateSpritePosition()
    mainSprite.physicsBody?.velocity = CGVectorMake(400, 0) // SETS A CONSTANT VELOCITY, HOWEVER I CAN NOT APPLY AN IMPULSE.
}

问题是您覆盖了 update 方法中的速度。因此,即使您添加了一个脉冲,它也会立即被 update 中的代码覆盖。尝试只覆盖速度的 dx 部分。

override func update(currentTime: CFTimeInterval) {

    updateSpritePosition()
    mainSprite.physicsBody?.velocity = CGVectorMake(400, mainSprite.physicsBody?.velocity.dy)
}