我有几个移动主角的按钮。 (左,右,跳等)但是,当我一次触摸多个按钮时,前一个按钮结束。我的问题是,如何在触摸期间保持两种触摸活动?例如,这将允许角色向前移动并同时跳跃。我已将multipleTouchEnabled设置为true。我已经读过,使用字典来跟踪触摸会有所帮助,但我似乎无法围绕实施工作。
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))
}
答案 0 :(得分:2)
您应该创建一个活动触摸词典。
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"
}
}
}
在上面的代码中,您应该将自己的代码放入
tapBegin
:此方法接收按钮的标签并开始一些操作。
E.g。开始跑步。
tapEnd
:此方法接收按钮的标签并停止某些操作。
E.g。停止运行。
findButtonName
:此方法收到UITouch
并返回用户按下的按钮标签。我在iPhone上测试了以前的代码。我执行了以下操作。
正如您在以下日志中所看到的,代码能够识别不同的触摸
Begin press right
Begin press left
End press right
End press left
我希望自己清楚明白。如果不是,请告诉我。