如何在Touchesmoved中左右移动玩家

时间:2018-03-09 01:52:37

标签: ios swift sprite-kit touchesmoved

如何在游戏“Line Zen”中左右移动玩家?

???

1 个答案:

答案 0 :(得分:0)

您可以使用 SKAction.moveBy

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        if let location = touch?.location(in: self){
            if location.x > 0{
                player.run(SKAction.moveBy(x: 1, y: 0, duration: 0.1))
            }else{
                player.run(SKAction.moveBy(x: -1, y: 0, duration: 0.1))
            }

           // OR 

           if location.x > player.position.x {
               player.run(SKAction.moveBy(x: 1, y: 0, duration: 0.1))
           }else{
               player.run(SKAction.moveBy(x: -1, y: 0, duration: 0.1))
           }
        }
    }

但这并不是一个好主意因为当玩家手指没有移动时, touchesMoved 将不会被调用且玩家将无法移动。

我建议永远移动touchMoved中的动作,当touchesEnded时,删除动作如下:

   override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        if let location = touch?.location(in: self){
            if location.x > player.position.x {
                let moveToRight = SKAction.moveBy(x: 1, y: 0, duration: 0.1)
                let forever = SKAction.repeatForever(moveToRight)
                player.run(forever)
            }else{
                let moveToLeft = SKAction.moveBy(x: -1, y: 0, duration: 0.1)
                let forever = SKAction.repeatForever(moveToLeft)
                player.run(forever)
            }
        }
    }
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        player.removeAllActions()
    }

顺便说一句,您可以使用 removeAction删除特定操作(forKey:&#34; actionKey&#34;)