SpriteKit - 在随机位置创建而不重叠

SpriteKit - Create at random position without overlapping

我想在随机位置创建一些精灵而不重叠,这是我的代码:

var sprites = [SKSpriteNode]()

 for index in 0...spriteArray { 

                let sprite = SKSpriteNode(imageNamed: named)
                sprites.append(sprite)

                checkInterception(sprite, sprite2: sprites)// positioning using a function

                addChild(sprite)
            }

这里我检查重叠:

func checkInterception(sprite1: SKSpriteNode, sprite2: [SKSpriteNode]) {

        let xPos = CGFloat( Float(arc4random()) / Float(UINT32_MAX)) * maxX
        let yPos = CGFloat( Float(arc4random()) / Float(UINT32_MAX)) * maxY
        sprite1.position = CGPoint(x: xPos, y: yPos )

        for index in 0...sprite2.count-1 {

            if sprite1.intersectsNode(sprite2[index]) {

                let yPos = sprite1.position.y + sprite1.size.height
                sprite1.position = CGPoint(x: xPos, y: yPos )
            }
        }
    }

但有些精灵仍然重叠。我知道 for 循环有些不对劲,但就是想不通。

我相信有几种不同的方法可以解决这个问题,这将是最接近您已经写过的方法。

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)
}

需要考虑的事情是,如果您还不知道在哪里添加精灵是安全的,那么您 运行 性能的风险。例如,添加你的最后一个精灵可能需要 1,000,000 次尝试,然后它会随机选择一个不与其他精灵相交的点。

如果您不必一次全部添加它们,我会解决更新循环中的问题并执行类似这样的操作...

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()
}

有点粗糙,但想法是每次更新都会尝试添加精灵。这样,如果您 运行 离开房间,它就不会上锁。希望对您有所帮助。