Search code examples
swiftsprite-kittouchxcode7game-physics

How can i alter my program to allow this object to only react to a single touch?


I am making a basketball game. My problem is when I shoot the ball, i can then touch the ball in mid-air again, which i do not want. Once the user shoots the ball I do not want touch to have an effect. Here is my code:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?
{
    touching = false
    for touch: AnyObject in touches {
    let location = touch.locationInNode(self)
    if ball.frame.contains(location){
        touchingPoint = location
        touching = true
    }
    }
}


override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch: AnyObject in touches {
    let location = touch.locationInNode(self)
        touchingPoint = location
    }
}


override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if touching{
        let dt:CGFloat = 8.25/29.5
        let distance = CGVector(dx: touchingPoint.x-ball.position.x, dy: touchingPoint.y-ball.position.y)
        let velocity = CGVector(dx: distance.dx/dt, dy: distance.dy/dt)
        ball.physicsBody!.velocity=velocity
    }
}

What can i add to my program so that a touch won't have any effect once the ball has been shot?


Solution

  • after you shoot the ball disable userInteraction

    ball.userInteractionEnabled = false
    

    then enable it again when you want them to be able to touch it