I have an array of moving SKNodes, and I want to create one that does not have the same position of any others, how? I have some code that didn't actually work. You can check it below:
extension CGPoint {
static func getRandom(inside scene: SKScene, andArray array: [SKSpriteNode]) -> CGPoint {
let x: CGFloat = getRandomX(inside: scene, andArray: array)
let y: CGFloat = getRandomY(inside: scene, andArray: array)
let i = getRandomSign()
return Point(x * i, y * i)
}
private static func getRandomX(inside scene: SKScene, andArray array: [SKSpriteNode]) -> CGFloat {
var val = CGFloat(arc4random() % UInt32(scene.frame.width/2))
for node in array {
if val == node.position.x {
val = getRandomX(inside: scene, andArray: array)
}
}
return val
}
private static func getRandomY(inside scene: SKScene, andArray array: [SKSpriteNode]) -> CGFloat {
var val = CGFloat(arc4random() % UInt32(scene.frame.height/2))
for node in array {
if val == node.position.y {
val = getRandomY(inside: scene, andArray: array)
}
}
return val
}
private static func getRandomSign() -> CGFloat {
let val = arc4random()
if val % 2 == 0 {
return -1
} else {
return 1
}
}
}
The CGPoint.getRandom(....)
gets called when adding a node, in the SKScene.
Aucun commentaire:
Enregistrer un commentaire