pulitr pulitr - 5 months ago 21
Swift Question

Generating positions for SKSpriteNode

I am generating Y position for SKSpriteNode. I need to generate y position, but it should not be in the position previously generated image, should not overlap. How would I be able to do this in Swift in SpriteKit?

for _ in 1...3 {
let lower : UInt32 = 100
let upper : UInt32 = UInt32(screenSize.height) - 100
let randomY = arc4random_uniform(upper - lower) + lower

obstaclesTexture = SKTexture(imageNamed: "levaPrekazka")
obstacle = SKSpriteNode(texture: obstaclesTexture)
prekazka = obstacle.copy() as! SKSpriteNode

prekazka.name = "prekazka"
prekazka.position = CGPoint(x: 0, y: Int(randomY))
prekazka.zPosition = 10;
prekazka.size = CGSize(width: screenSize.width / 7, height: screenSize.height / 7)
prekazka.physicsBody = SKPhysicsBody(texture: obstaclesTexture, size: obstacle.size)
prekazka.physicsBody?.dynamic = false
prekazka.physicsBody?.categoryBitMask = PhysicsCatagory.obstacle
prekazka.physicsBody?.contactTestBitMask = PhysicsCatagory.ball
prekazka.physicsBody?.contactTestBitMask = PhysicsCatagory.ball
self.addChild(prekazka)
}

Answer

To avoid both overlapping sprites and different positions you need to take the height of the sprite into consideration. Something like this perhaps:

let spriteHeight = 60 // or whatever
let lower  = 100
let upper = Int(screenSize.height) - 100
let area = upper - lower
let ySpacing = area/spriteHeight
var allowedYs = Set<CGFloat>()
let numberOfSprites = 3

while allowedYs.count < numberOfSprites {
    let random = arc4random_uniform(UInt32(spriteHeight))
    let y = CGFloat(random) * CGFloat(ySpacing)
    allowedYs.insert(y)
}

for y in allowedYs {
    obstaclesTexture = SKTexture(imageNamed: "levaPrekazka")
    obstacle = SKSpriteNode(texture: obstaclesTexture)
    prekazka = obstacle.copy() as! SKSpriteNode

    prekazka.name = "prekazka"
    prekazka.position = CGPoint(x: 0, y: y)
    // etc...
}
Comments