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