我正在使用 Xcode 7、Swift 和 SpriteKit,并且我尝试允许用户在我的应用程序中同时使用两根手指。
基本上,我的屏幕有两半,我希望每一侧都有单独的触摸识别,并且同时。
下面是我当前的代码:
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?)
{
guard let touch = touches.first else {
return;
}
let location = touch.locationInNode(self)
let touchedNode = self.nodeAtPoint(location)
if (touchedNode == touch1){
//code1
}
else if (touchedNode == touch2){
//code2
}
}
touch1 和 touch2 是 SkSpriteNode,分别占据屏幕的不同一半。
只要您一次只有 1 个手指在屏幕上,此代码就可以正常工作。
然而,如果有两个(每半个),则首先放置在屏幕上的那个就是注册的。
如何才能使两者都被注册,从而运行 code1 和 code2?
最佳答案
你需要multipleTouchEnabled属性设置为 true
。来自关于此属性的文档:
When set to YES, the receiver receives all touches associated with a multi-touch sequence. When set to NO, the receiver receives only the first touch event in a multi-touch sequence. The default value of this property is NO.
编辑:
根据您的评论,您可以尝试这样做(使 Sprite 响应触摸):
class Button:SKSpriteNode {
init(size:CGSize, color:SKColor) {
super.init(texture: nil, color: color, size: size)
userInteractionEnabled = true
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let name = self.name {
print("Button with \(name) pressed")
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let name = self.name {
print("Button with \(name) pressed")
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let name = self.name {
print("Button with \(name) released")
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class GameScene: SKScene, SKPhysicsContactDelegate {
override func didMoveToView(view: SKView) {
let left = Button(size: CGSize(width: frame.size.width/2.0, height: frame.size.height), color: .blackColor())
left.name = "left"
left.position = CGPoint(x: left.size.width/2.0, y: frame.midY)
let right = Button(size: CGSize(width: frame.size.width/2.0, height: frame.size.height), color: .whiteColor())
right.name = "right"
right.position = CGPoint(x:frame.maxX-right.size.width/2.0, y: frame.midY)
addChild(left)
addChild(right)
}
}
关于ios - 一次检测多个触摸(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36672328/