[英]In SpriteKit using Swift how can you set a specific limit for the amount of child nodes?
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!
目前,它们可以产生任意数量的球并使场景过饱和,从而导致FPS下降和非常简单的游戏!
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. 我知道我需要询问场景中场景中有多少个球节点,然后在达到极限时将其删除,但是我尝试尝试的所有操作都会导致错误。
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.
注意:除非您在某个时候将球从场景中移开,否则您将达到10个球的极限并被卡住。
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)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.