Spritekit添加节点而不重叠

时间:2018-01-24 18:00:42

标签: swift sprite-kit

我试图在屏幕上的随机位置添加20个节点,而没有任何节点重叠。我已经在随机位置部分添加了节点,但我会得到一些重叠的节点。到目前为止我所做的是:我会很高兴找到正确的方向。

    while i < 20 {
        let bubbleSize = self.frame.width / 12
        let bubble = SKShapeNode(circleOfRadius: bubbleSize)

        let widthL = -self.frame.size.width / 2 + bubble.frame.size.width / 2 
        let widthH = self.frame.size.width / 2 - bubble.frame.size.width / 2 

        let heightL = -self.frame.size.height / 2 + bubble.frame.size.height/ 2 
        let heightH = self.frame.size.height / 2 - bubble.frame.size.height / 2

        var randWidth = randomNumber(range: widthL..<widthH)
        var randHeight = randomNumber(range: heightL..<heightH)

        bubble.fillColor = SKColor.cyan
        bubble.position = CGPoint(x: randWidth, y: randHeight)

        self.addChild(bubble)
 }

func randomNumber(range: Range<CGFloat>) -> CGFloat {
    //function that gives a random number of a range of CGFloats entered
    let min = range.lowerBound
    let max = range.upperBound
    return CGFloat(arc4random_uniform(UInt32(CGFloat(max - min)))) + min
}

1 个答案:

答案 0 :(得分:1)

这应该让你开始。它基本上将屏幕划分为网格并将气泡放置在网格位置,同时确保没有其他气泡位于该位置。你还可以做更多的事情,比如在该位置添加一些轻微的随机位置(随机生成一些小的偏移-2到+2的x和y值,这样它们看起来就不那么完美了。)

let bubbleSize = self.frame.width / 12
let minX = 0 - self.frame.size.width / 2
let maxX = self.frame.size.width / 2
let minY = 0 - self.frame.size.height/ 2
let maxY = self.frame.size.height/ 2
var usedIndexes: [Int]!
let xRange = maxX * 2
let yRange = maxY * 2
let cols = xRange / bubbleSize
let rows = yRange / bubbleSize

func createBubbles(count: Int) {

    for _ in 0..<count {
        createBubble()
    }
}

func createBubble() {

    let index = findSlot()
    let posX = index % cols 
    let posY = index / cols
    let bubble = SKShapeNode(circleOfRadius: bubbleSize)
    bubble.fillColor = SKColor.cyan
    bubble.position = CGPoint(x: posX, y: posY)
    self.addChild(bubble)
}

func findSlot() -> Int {

    //preventative measure to stop endless loop from happening
    guard usedIndexes.count > rows * cols else { return 0 }

    let randomX = randomNumber(range: 0..<cols)
    let randomY = randomNumber(range: 0..<rows)

    let index = randomX + randomY * cols 
    if usedIndexes.contains(index) {
        return findSlot()
    }
    else {
        usedIndexes.append(index)
    }

    return index
}