【问题标题】:Move node left and right without snapping to touch左右移动节点而不捕捉到触摸
【发布时间】:2018-07-05 23:42:02
【问题描述】:

我在屏幕上有一个精灵节点,玩家可以左右移动。我知道如何使用 touchesMoved 使其左右移动,但是,如果玩家触摸某个位置,则节点会捕捉到该位置。 例如,如果节点在屏幕左侧,玩家触摸屏幕右侧,节点会立即移动到触摸位置。我不想要这种行为。我只想在玩家向左或向右移动手指时移动节点,而不是在他们触摸某个位置时移动。下面是我目前使用的代码。在 touchesBegan 或 touchesEnded 函数中没有任何代码会影响 playerNode x 位置。

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches
    {
        if game.state == .game
        {
            let position = touch.location(in: playableArea)

            game.playerNode.position.x = position.x

        }
    }
}

我怎样才能阻止这种行为发生,并且只有当玩家的手指向左或向右移动时节点才会移动?

【问题讨论】:

    标签: swift sprite-kit skspritenode touchesmoved


    【解决方案1】:

    我最终解决了我的问题。我知道我必须相对于触摸位置移动节点,但我不知道该怎么做。这就是我让它工作的方式。

    首先我创建了一个变量,它等于玩家的触摸位置。此变量在 touchesBegan 中设置。

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
    {
            if game.state == .game
            {
                let position = touch.location(in: playableArea)
    
                playerTouchPosition = position
            }
    }
    

    我使用这个变量作为触摸的起点。当玩家移动他们的手指时,它会计算玩家的手指相对于起点移动了多少。例如,如果玩家在 X 值 100 处触摸,并将手指移动到 X 值 120,它会计算玩家手指移动了 20。找到该值后,我将 playerTouchPosition 设置为感动了。这是为了使下一步动作与上一次触摸有关。然后我将玩家节点移动玩家手指移动的量。

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches
        {
            if game.state == .game
            {
                let position = touch.location(in: playableArea)
                let newX : CGFloat!
    
                if position.x > playerTouchPosition.x
                {
                    newX = position.x - playerTouchPosition.x
                }else
                {
                    newX = -(playerTouchPosition.x - position.x)
                }
    
                playerTouchPosition = position
    
                game.playerNode.position.x = game.playerNode.position.x + newX
    
            }
        }
    }
    

    这阻止了玩家节点立即移动到触摸位置 X 值所在的位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多