首页 > 解决方案 > 在 SpriteKit 中添加基本的左右点击并按住控件时遇到问题

问题描述

所以基本上我想要完成的是在我的 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)
    }
}

标签: swiftxcodesprite-kituigesturerecognizer

解决方案


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

let touch = touches.first!

进入

for touch in touches { }

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

找到数组中的最后一件事也可能会有所帮助。

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

我希望这会有所帮助,祝你好运!


推荐阅读