spritekit我的播放器节点根据我的触摸不移动?

时间:2018-01-17 09:57:20

标签: swift sprite-kit touches

我一直试图在我的代码中找出这个错误,每当我的播放器节点位于屏幕的最左侧/右侧时,它往往表现得很奇怪,即它向右移动/即使我已经触摸左/右

这是我的代码:

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {

        let location = touch.location(in: self)
        let action = SKAction.moveTo(x:location.x, duration: 0.45)
        if location.x > (player?.position.x)! {
            player?.run(action)
            moveLeft = false
        } else {
            player?.run(action)
            moveLeft = true
        }
    }
    canMove = true
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    canMove = false
}

这是Player.swift中的moveleft

// Move function
func move(left: Bool) {
    if left {
        position.x -= 10
        // Set boundary to minX so it wont go below
        if position.x < minX {
            position.x = minX
        }

    } else {
        position.x += 10

        // Set boundary to maxX so player cannot move over the right boundary
        if position.x > maxX {
            position.x = maxX
        }
    }
}

1 个答案:

答案 0 :(得分:0)

1)您的操作堆叠在一起,因此每次触摸时,都会添加新操作。如果你左,右,左触摸你的角色就会变得不稳定。为了解决这个问题,请指定一个键player?.run(action, withKey:"moving")(不要为左右分配不同的键,只使用1个键向任何方向移动)

2)你是在玩家的左边或右边触摸,当玩家一直到左边时,即使触摸屏幕的左边也会向右移动他。您可能希望将此切换为简单,如果x为负,则向左移动,如果x为正则向右移动(假设场景的中心为(0,0)

3)不确定何时调用move(left:Bool),我在代码中没有看到它。

这甚至不需要,我会避免一起检查这个bool。