Swift SpriteKit跟踪多点触摸
我有几个按钮可以移动主角。(左、右、跳跃等)但是,当我一次触摸多个按钮时,前一个按钮将结束。我的问题是,如何在两次触球的持续时间内保持两次触球的活力?例如,这将允许角色同时向前移动和跳跃。我已将MultipleToTouchEnabled设置为true。我曾读到,使用字典跟踪触摸会有所帮助,但我似乎无法理解实现Swift SpriteKit跟踪多点触摸,swift,sprite-kit,touchesbegan,Swift,Sprite Kit,Touchesbegan,我有几个按钮可以移动主角。(左、右、跳跃等)但是,当我一次触摸多个按钮时,前一个按钮将结束。我的问题是,如何在两次触球的持续时间内保持两次触球的活力?例如,这将允许角色同时向前移动和跳跃。我已将MultipleToTouchEnabled设置为true。我曾读到,使用字典跟踪触摸会有所帮助,但我似乎无法理解实现 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInView(nil)
if location.x < self.size.width / 2 && location.y > self.size.height / 2 {
movingLeft = true
}
if location.x > self.size.width / 2 && location.y > self.size.height / 2 {
movingRight = true
}
if location.x < self.size.width / 2 && location.y < self.size.height / 2 {
jump()
}
if location.x > self.size.width / 2 && location.y < self.size.height / 2 {
jump()
}
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
movingLeft = false
movingRight = false
}
func jump() {
mainCharacter.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
mainCharacter.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 400))
}
覆盖函数触摸开始(触摸:设置,withEvent事件:UIEvent?){
接触{
让位置=触摸。位置查看(无)
如果location.xself.size.height/2{
左移=真
}
如果location.x>self.size.width/2和&location.y>self.size.height/2{
movingRight=true
}
如果location.xself.size.width/2和location.y
逻辑
您应该创建一个活动触摸的字典
private var activeTouches = [UITouch:String]()
每次触摸开始时,您都会将其保存到字典中并为其指定一个标签
activeTouches[touch] = "left"
因此,当触摸结束时,您可以在字典中搜索它并找到相关标签。现在您知道用户已释放了哪个按钮
let button = activeTouches[touch]
if button == "left" { ... }
别忘了把它从字典里删除
实施
结论
我希望我说清楚了。如果有什么不对劲,请告诉我
activeTouches[touch] = nil
class GameScene: SKScene {
private var activeTouches = [UITouch:String]()
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let button = findButtonName(from:touch)
activeTouches[touch] = button
tapBegin(on: button)
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
guard let button = activeTouches[touch] else { fatalError("Touch just ended but not found into activeTouches")}
activeTouches[touch] = nil
tapEnd(on: button)
}
}
private func tapBegin(on button: String) {
print("Begin press \(button)")
// your custom logic goes here
}
private func tapEnd(on button:String) {
print("End press \(button)")
// your custom logic goes here
}
private func findButtonName(from touch: UITouch) -> String {
// replace this with your custom logic to detect a button location
let location = touch.locationInView(self.view)
if location.x > self.view?.frame.midX {
return "right"
} else {
return "left"
}
}
}
Begin press right
Begin press left
End press right
End press left