swift - 在 SpriteKit 中添加基本的左右点击并按住控件时遇到问题

标签 swift xcode sprite-kit uigesturerecognizer

所以基本上我想要完成的是在我的 SpriteKit 游戏中触摸并按住控件。我想让它在我的游戏中可以根据用户持有的屏幕的哪一侧来回移动玩家对象。此外,当用户不再握住一侧或另一侧时,我希望玩家自然地回到场景的中心。例如,如果用户触摸并按住屏幕左侧的触摸,则播放器会向该侧移动。但是,如果用户松开或触摸屏幕的另一侧,我希望播放器相应地移动到中心或另一侧。

虽然我已经能够使用下面的代码取得一些结果,但我遇到了一些错误。

我明确希望玩家必须同时触摸并按住屏幕的右侧或左侧,而不是在运行时发生这种情况。

有时,播放器会出现故障并返回中心,并出现触摸识别器无法评估调试器中显示的触摸的错误。

关于如何修复我的代码并获得预期结果的任何想法?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first!
    if player.contains(touch.location(in: self)) {
        if state == .inactive {
            startGame()
        }
    } else if touch.location(in: self).x < 0 {
        if state == .active {
            holdingRightControl = false
            holdingLeftControl = true
        }
    } else if touch.location(in: self).x > 0 {
        if state == .active {
            holdingLeftControl = false
            holdingRightControl = true
        }
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if state == .active {
        holdingLeftControl = false
        holdingRightControl = false
    }
}

override func update(_ currentTime: TimeInterval) {
    if holdingLeftControl == true {
        let moveLeftward: SKAction = SKAction.moveTo(x: -240, duration: getDuration(start: player.position.x, end: -240))
        player.run(moveLeftward)
    } else if holdingRightControl == true {
        let moveRightward: SKAction = SKAction.moveTo(x: 240, duration: getDuration(start: player.position.x, end: 240))
        player.run(moveRightward)
    } else {
        let reCenter: SKAction = SKAction.moveTo(x: 0, duration: getDuration(start: player.position.x, end: 0))
        player.run(reCenter)
    }
}

最佳答案

我不确定,但尝试一些东西可能会改变线路

let touch = touches.first!

进入

for touch in touches { }

这应该可以帮助您找到所有接触点。

找到数组中的最后一个元素也可能有所帮助。

我不知道 sprite 会出现故障到中心,但也许你可以在任何地方找到你改变 sprite 位置的地方。

希望对您有所帮助,祝您好运!

关于swift - 在 SpriteKit 中添加基本的左右点击并按住控件时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52799190/

相关文章:

swift - 如何在 Vapor 中使用 PostgreSQL 事务

swift - 将 NSMutableData 的一部分复制到新的 NSMutableData 对象

arrays - 将数组缩减为第一个和最后一个元素的元组?

ios - 图片(或视频)在 Swift 中发布到服务器

swift - 为什么我的 UIpickerView 现在需要 3 个小时才能完成构建?

Swift 3 子弹发射延迟

ios - 我如何在 Xcode 中打印我的代码的所有方法?

xcode - Swift 错误线程 1 : EXC_BAD_INSTRUCTION cell definition

ios - 如何为spritekit中的节点添加滑动手势

swift - Sprite Kit 按钮触摸位置错误 | swift