4

I have an array SKNodes, moving in a line, 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, I don't see the node of the frame, but some times, when my nodes are moving, the new node overlaps with the old ones, which it shouldn't (and btw, it overlaps sometimes in the middle of the line of nodes, that's why I'm sure that it is not caused by the 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
    }
}

}

The CGPoint.getRandom(....) gets called when adding a node, in the SKScene.

Fayyouz
  • 682
  • 7
  • 18

0 Answers0