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

时间:2015-10-10 18:40:27

标签: swift random sprite-kit overlap

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

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循环有一些不对的东西,但是无法理解。

1 个答案:

答案 0 :(得分:4)

我确信有几种不同的方法来解决问题,这将是你最接近你已经写的。

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

有点粗糙,但想法是每次更新都会尝试添加精灵。这样,如果你没有房间,它将无法锁定。希望这会有所帮助。