user431791 user431791 - 9 days ago 5
Swift Question

Distribute 4 SKSpriteNodes along SkScene Width programmatically

I know scene coordinates are (0,0) at center so how can i distribute 4 SKNodes along the width using a for loop

for index 1...4 {

let node = SKNode()
node.postion = evenly distribute along the scene width. who can i do it?
}

Nik Nik
Answer

You could use the width of the scene divided by the number of nodes minus 1. This would then be multiplied by the index minus 1, then added to the minimum x value of your scene.

let widthRange = scene.frame.maxX - scene.frame.minX

for index 1...4 { 
    let node = SKNode() 
    node.postion = scene.frame.minX + widthRange/(4-1) * (index-1)
}

This should place each node an equal distance away from each other along the width of the scene, starting from each edge.

If your index for the for loop doesn't start at 1, the code would need to be modified to something like this:

let widthRange = scene.frame.maxX - scene.frame.minX

var counter = 0
for index 352...356 { 
    let node = SKNode() 
    node.postion = scene.frame.minX + widthRange/(4-1) * counter
    counter+=1
}

If you're unsure of which version to use, use the second version, as it's less reliant on the format of the for loop (as long as you reset counter to 0 before every time you use this).

If you need any clarifications as to what does what, feel free to ask.

Note that I haven't actually tested this yet.

Comments