1

I am making a simple Pong game using SpriteKit + Swift. 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
}
  • 1
    This should be what you're looking for http://stackoverflow.com/questions/27343926/multi-touch-gesture-in-sprite-kit – 0x141E Oct 19 '15 at 02:29

1 Answers1

0

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:

for touch in touches
{

}

You can now use touch the same way you used your original touch, but multi-touch will be implemented.

Jack
  • 955
  • 1
  • 9
  • 30