0

I have a function that spawns little balls, randomly positioned, on the screen. The problem I face is that I want to distribute the balls randomly, but when I do so, some balls spawn on top of each other. I want to exclude all the positions that are already taken (and maybe a buffer of a few pixels around the balls), but I don't know how to do so. I worked around this by giving the balls a Physicsbody, so they move off from one another if they happen to spawn on top of each other. But I want them to not spawn on top of each other in the first place. My code for now is the following:

    spawnedBalls = [Ball]()
    level = Int()
    
    func setupLevel() {
            
        let numberOfBallsToGenerate = level * 2
        let boundary: CGFloat = 26
        let rightBoundary = scene!.size.width  - boundary
        let topBoundary   = scene!.size.height - boundary
        
        while spawnedBalls.count < numberOfBallsToGenerate {
            
            let randomPosition = CGPoint(x: CGFloat.random(in: boundary...rightBoundary), y: CGFloat.random(in: boundary...topBoundary))
            
            let ball = Ball()
            ball.position = randomPosition
            ball.size = CGSize(width: 32, height: 32)
            
            ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width)
            ball.physicsBody?.affectedByGravity = false
            ball.physicsBody?.allowsRotation = false
            ball.physicsBody?.categoryBitMask = 1
            ball.physicsBody?.collisionBitMask = 1
            
            spawnedBalls.append(ball)
            self.addChild(ball)
            
        }
        
    }

I don't know if this problem should be solved by having an array that stores all taken positions, or if I should use some kind of FiledNode, where occupied space can be sort of subtracted, but sadly I am unfamiliar with FieldNodes, so I don't know if that's the right way to face the problem.

4

1 回答 1

0

步骤 1) 更换

let randomPosition = ....

let randomPosition = randomPositionInOpenSpace()

步骤 2) 编写randomPositionInOpenSpace函数:

想法是:a)生成一个随机位置 b)它在开放空间中吗?如果是,则返回 c) 重复直到确定

然后步骤 3) 编写 ' is it in open space' 函数

为此,您需要知道建议的坐标是否靠近任何其他球。对于圆,您可以测试它们的中心之间的距离是否大于(半径 + 边距)。中心之间的距离是毕达哥拉斯:x delta 平方加上 y delta 平方的 sqrt。

于 2021-04-08T08:20:39.707 回答