Reputation: 599
I have the following segment of code in which I want a tap to cause the ball to move in my screen.
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
moveBallUp()
moveBallLeft()
moveBallRight()
}
func moveBallUp() -> Void {
ball.physicsBody?.applyImpulse(CGVectorMake(0, impulseFactor))
}
func moveBallLeft() -> Void {
var random = -1 * CGFloat(Float(arc4random()))
ball.physicsBody?.applyImpulse(CGVectorMake(random % impulseFactor, 0))
}
func moveBallRight() -> Void {
var random = CGFloat(Float(arc4random()))
ball.physicsBody?.applyImpulse(CGVectorMake(random % impulseFactor, 0))
}
How do I make it such that only taps on the SKSpriteNode variable "ball" will cause the ball to move?
Upvotes: 1
Views: 37
Reputation: 13675
You can set ball's name (ballNode.name = "ball"
) and access it like this:
touchesBegan:
let location = (touch as UITouch).locationInNode(self)
if let ball = self.nodeAtPoint(location)
if ball.name == "ball" {
//move the ball
}
}
Another way would be using subclassing SKSpriteNode (and implementing touchesBegan method) like this:
class Ball : SKSpriteNode
{
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
//do your stuff here
}
}
If you are subclassing SKSpriteNode you have to set userInteractionEnabled = true.
you can do this in ball's init method or after you create Ball object.
Upvotes: 1