简体   繁体   English

SpriteKit + Swift中的多点触摸手势识别

[英]Multi-touch gesture recognition in SpriteKit + Swift

I am making a simple Pong game using SpriteKit + Swift. 我正在使用SpriteKit + Swift制作一个简单的Pong游戏。 I am only able to move each paddle at a single time, with only one finger on the display. 我只能一次用手指移动显示屏上的每个拨片。 I already saw the other questions which are related, but they have not helped me. 我已经看过其他相关的问题,但是它们并没有帮助我。 My code: 我的代码:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    let touch = touches.first as UITouch?
    let touchLocation = touch?.locationInNode(self)
    let body: SKPhysicsBody? = self.physicsWorld.bodyAtPoint(touchLocation!)

    if body?.node!.name == PaddleCategoryName {
        print("Paddle Touched!")
        fingerIsOnPaddle = true
    }

    if body?.node!.name == PaddleCategoryName2 {
        print("Paddle2 Touched!")
        fingerIsOnPaddle2 = true
    }


}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if fingerIsOnPaddle {
        let touch = touches.first as UITouch?
        let touchLocation = touch?.locationInNode(self)
        let previousTouchLocation = touch?.previousLocationInNode(self)

        let paddle = self.childNodeWithName(PaddleCategoryName) as! SKSpriteNode

        var newYPosition = paddle.position.y + (touchLocation!.y - previousTouchLocation!.y)

        newYPosition = max(paddle.size.height / 2, newYPosition)
        newYPosition = min(self.size.height - paddle.size.height / 2, newYPosition)

        paddle.position = CGPointMake(paddle.position.x, newYPosition)

    }

    if fingerIsOnPaddle2 {
        let touch = touches.first as UITouch?
        let touchLocation = touch?.locationInNode(self)
        let previousTouchLocation = touch?.previousLocationInNode(self)

        let paddle2 = self.childNodeWithName(PaddleCategoryName2) as! SKSpriteNode

        var newYPosition = paddle2.position.y + (touchLocation!.y - previousTouchLocation!.y)

        newYPosition = max(paddle2.size.height / 2, newYPosition)
        newYPosition = min(self.size.height - paddle2.size.height / 2, newYPosition)

        paddle2.position = CGPointMake(paddle2.position.x, newYPosition)
    }
}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    fingerIsOnPaddle = false
    fingerIsOnPaddle2 = false
}

I know this is a bit late, but thought I'd try to reduce the hassle for anyone in the future. 我知道这有点晚了,但我想以后会尽量减少任何人的麻烦。

The way I would do this is to firstly remove 我这样做的方法是首先删除

let touch = touches.first as UITouch?

then put your whole touchesMoved function inside this block of code: 然后将整个touchesMoved函数放在此代码块中:

for touch in touches
{

}

You can now use touch the same way you used your original touch, but multi-touch will be implemented. 现在,您可以像使用原始触摸一样使用触摸,但是将实现多点触摸。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM