Reputation: 3
I have a simple scene which adds a bouncing ball to the scene once a user touches in an area. The goal will be to bounce the balls off pins in order to 'score' in a certain area.
I'm just at the very beginning of coding the app, but I can't as yet find a way to create a limit for the amount of balls a user can generate. At the moment, they can generate any number of balls and over-saturate the scene, leading to a drop in FPS and a very easy game!
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
let ball = SKSpriteNode(imageNamed:"ball")
ball.xScale = 0.2
ball.yScale = 0.2
ball.position = location
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height / 2.0)
ball.physicsBody!.dynamic = true
ball.physicsBody!.friction = 0
ball.physicsBody!.restitution = 0.8
ball.name = "ball"
self.addChild(ball)
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
I know I need to ask the scene how many ball nodes are in the scene and then remove a ball once it reached a limit but everything I seem to try results in errors.
Upvotes: 0
Views: 492
Reputation: 8130
there are a ton of ways to do this, but this is probably the easiest. NOTE: unless you remove balls from the scene at some point, you're going to hit a ten ball limit and get stuck.
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
// ball limit
let limit = 10
// setup counter
var i = 0
// loop through the ball nodes added to the scene
self.enumerateChildNodesWithName("ball", usingBlock: {
_, _ in // we dont need to use these variables right now
i += 1 // increment the counter
})
// if we haven't hit our limit, add a ball (YOUR CODE HERE)
if i <= limit {
let ball = SKSpriteNode(imageNamed:"ball")
ball.xScale = 0.2
ball.yScale = 0.2
ball.position = location
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height / 2.0)
ball.physicsBody!.dynamic = true
ball.physicsBody!.friction = 0
ball.physicsBody!.restitution = 0.8
ball.name = "ball"
self.addChild(ball)
}
}
}
Upvotes: 0