Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I spawn multiple nodes without them overlapping?

I have nodes spawning every 0.2-5.0 seconds on my screen like so:

override func didMoveToView(view: SKView) {
    backgroundColor = UIColor.whiteColor()

    runAction(SKAction.repeatActionForever(
        SKAction.sequence([
            SKAction.runBlock(blackDots),
            SKAction.waitForDuration(1.0)])))
}

func random() -> CGFloat {
    return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}

func random(min min: CGFloat, max: CGFloat) -> CGFloat {
    return random() * (max - min) + min
}

func blackDots() {
    let dot = SKSpriteNode(imageNamed: "first@2x")
    dot.size = CGSizeMake(75, 75)
    dot.name = "dotted"
    dot.position = CGPointMake(500 * random(min: 0, max: 1), 500 * random(min: 0, max: 1))
    addChild(dot)
}

However, when they are spawned, some intersect and lay on top of one another? Is there a way to prevent this? Thanks in advance.

like image 870
IHeartAppsLLC Avatar asked Aug 09 '26 12:08

IHeartAppsLLC


1 Answers

Here's how to check if a node exists at a particular position.

You might want to throw the check into a loop so that if the position is taken, it will retry with a newly generated point. Otherwise you'll get some dots that just won't show. Just depends on what you're doing with them.

override func didMoveToView(view: SKView) {
    backgroundColor = UIColor.whiteColor()

    runAction(SKAction.repeatActionForever(
        SKAction.sequence([
            SKAction.runBlock(blackDots),
            SKAction.waitForDuration(1.0)])))
}

func random() -> CGFloat {
    return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}

func random(min min: CGFloat, max: CGFloat) -> CGFloat {
    return random() * (max - min) + min
}

func blackDots() {
    let dot = SKSpriteNode(imageNamed: "first@2x")
    dot.size = CGSizeMake(75, 75)
    dot.name = "dotted"

    let position = CGPointMake(500 * random(min: 0, max: 1), 500 * random(min: 0, max: 1))

    if positionIsEmpty(position) {
        dot.position = position
        addChild(dot)
    }
}

func positionIsEmpty(point: CGPoint) -> Bool {
    self.enumerateChildNodesWithName("dotted", usingBlock: {
        node, stop in

        let dot = node as SKSpriteNode
        if (CGRectContainsPoint(dot.frame, point)) {
            return false
        }
    })
    return true
}
like image 90
Beau Nouvelle Avatar answered Aug 13 '26 14:08

Beau Nouvelle