Search code examples
swiftsprite-kitskshapenode

How to populate an SKShapeNode uniformly


The code I am using to generate lines is so:

 func populate(num: Int) {
    for var i = 0; i < num; i++ {
        let lines = Line(size: CGSizeMake(lineWidth, lineHeight))
        let x = CGFloat(arc4random_uniform(UInt32(size.width * 20))) - size.width / 4
        let y = CGFloat(arc4random_uniform(UInt32(size.height * 90))) - size.height / 100
        lines.position = CGPointMake(x, y)
        addChild(lines)
        lines.zPosition = -1

    }

It populates just fine, but they are all randomly placed (I got this code from a tutorial). I would like to know if there is a way I can uniformly generate a line every x number of points without having to manually place them. Thanks in advance.


Solution

  • Instead of let x = CGFloat(arc4random_uniform(UInt32(size.width * 20))) - size.width / 4 let y = CGFloat(arc4random_uniform(UInt32(size.height * 90))) - size.height / 100 you define how you want your x to be placed, for example:

    let x = (i * size.width)
    let y = 0
    

    will place your lines in a single straight line along the x axis where y is 0