SpriteKit - Create at random position without overlapping

前端 未结 1 932
天涯浪人
天涯浪人 2021-01-03 09:54

I want to create some sprites at random positions without getting overlapped, here is my code :

var sprites = [SKSpriteNode]()

 for index in 0...spriteArray         


        
相关标签:
1条回答
  • 2021-01-03 10:43

    I am sure there are a few different ways to attack the problem and this would be the closest to what you already wrote.

    let sprites = [SKSpriteNode]() //loaded with your sprites to spawn
    let maxX  = size.width //whatever your max is
    let maxY  = size.height //whatever your max is
    
    var spritesAdded = [SKSpriteNode]()
    
    for currentSprite in sprites{
    
        addChild(currentSprite)
    
        var intersects = true
    
        while (intersects){
    
            let xPos = CGFloat( Float(arc4random()) / Float(UINT32_MAX)) * maxX
            let yPos = CGFloat( Float(arc4random()) / Float(UINT32_MAX)) * maxY
    
            currentSprite.position = CGPoint(x: xPos, y: yPos )
    
            intersects = false
    
            for sprite in spritesAdded{
                if (currentSprite.intersectsNode(sprite)){
                    intersects = true
                    break
                }
            }
        }
    
        spritesAdded.append(currentSprite)
    }
    

    Things to consider is if you don't already know where it is safe to add a sprite you run the risk of performance. For instance adding your last sprite may take 1,000,000 attempts before it randomly picks a point that doesn't intersect with others.

    If you don't have to have them all added at once I would attack the problem on the update loop and do something like this...

    var sprites = [SKSpriteNode]() //loaded with your sprites to spawn
    var maxX : CGFloat = 0.0 //whatever your max is
    var maxY : CGFloat = 0.0 //whatever your max is
    
    var spritesAdded = [SKSpriteNode]()
    
    override func didMoveToView(view: SKView) {
        maxX  = size.width //whatever your max is
        maxY  = size.height //whatever your max is
    }
    
    func addSprite(){
    
        if let currentSprite = sprites.first {
    
            let xPos = CGFloat( Float(arc4random()) / Float(UINT32_MAX)) * maxX
            let yPos = CGFloat( Float(arc4random()) / Float(UINT32_MAX)) * maxY
    
            currentSprite.position = CGPoint(x: xPos, y: yPos )
    
            for sprite in spritesAdded{
                if (currentSprite.intersectsNode(sprite)){
                    return
                }
            }
    
            addChild(currentSprite)
            spritesAdded.append(currentSprite)
            sprites.removeFirst()
        }
    }
    
    override func update(currentTime: NSTimeInterval) {
        addSprite()
    }
    

    Kind of rough but the idea is every update it will try to add a sprite. This way if you run out of room it won't lock up. Hopefully that helps.

    0 讨论(0)
提交回复
热议问题