点击时如何让精灵改变方向?

How do I make a sprite change directions when tapped?

第一次触摸时,我的播放器开始沿 y 轴向上移动,我的设置如下:

 override func touchesBegan(...) {
if isMovingup == true  {
        let up = SKAction.moveByX(0, y: 900, duration: 9)
         player.runAction(up)
    }
    else {
        let down = SKAction.moveByX(0, y: -900, duration: 9)
        player.runAction(down)
 }
    isMovingup = !isMovingup
    }

但是,当第二次点击节点时,我希望它沿着 y 轴向下移动,但到目前为止,它什么也没做。如有必要,将 post 更多代码。

你需要用player.removeAllActions()停止之前的动作,否则你的动作会继续叠加。

override func touchesBegan(...) {
    player.removeAllActions() //<-- Touching always causes the player to change direction, so lets cancel out the previous action before assigning a new one
    if isMovingup == true  {
        let up = SKAction.moveByX(0, y: 900, duration: 9)
        player.runAction(up)
    }
    else {
        let down = SKAction.moveByX(0, y: -900, duration: 9)
        player.runAction(down)
    }
    isMovingup = !isMovingup
}

看起来你的布尔翻转超出了函数的范围。尝试将行 isMovingup = !isMovingup 移动到最后一个大括号内。

override func touchesBegan(...) {
    if isMovingup {
        let up = SKAction.moveByX(0, y: 900, duration: 9)
        player.runAction(up)
    }
    else {
        let down = SKAction.moveByX(0, y: -900, duration: 9)
        player.runAction(down)
    }
    isMovingup = !isMovingup
}

好像是代码片

isMovingup = !isMovingup

是在函数外定义的,所以它不是运行。将它移到函数内的 else 语句之后,这样每次调用函数时它都会是 运行

override func touchesBegan(...) {
    if isMovingup == true  {
        let up = SKAction.moveByX(0, y: 900, duration: 9)
        player.runAction(up)
    }
    else {
        let down = SKAction.moveByX(0, y: -900, duration: 9)
        player.runAction(down)
   }
   isMovingup = !isMovingup
}