Creating a random SKNode position without being equal to others

I have an SKNodes array moving in a string and I want to create one that has no other position, how? I have code that actually doesn't work, I don’t see the node of the frame, but sometimes, when my nodes move, the new node overlaps with the old ones, which should not (and by the way, it sometimes overlaps in the middle of the node string, so I sure this is not caused by a delay). You can check it below:

extension Point {

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
    }
}

}

CGPoint.getRandom(....) called when node is added to SKScene.

+4
source share

Source: https://habr.com/ru/post/1681991/


All Articles