Trying to randomly run some functions in an array for my SpriteKit game, but they are not appearing in the Simulator

46 Views Asked by At

I want 8 functions to be called at random. I know the functions individually work, but when I try and run them randomly with this code they do not appear in the Simulator...

    func randomizeBuildingFunction() {
    let wait = SKAction.wait(forDuration: 6)
        let randomBuildings = [createBuildingOne, createBuildingTwo, createBuildingThree, createBuildingFour, createBuildingFive, createBuildingSix, createBuildingSeven, createBuildingEight]
    let useRandomResult = SKAction.run {
        let randomResult = Int(arc4random_uniform(UInt32(randomBuildings.count)))
        return randomBuildings[randomResult]()
    }
    SKAction.repeatForever(SKAction.sequence([useRandomResult, wait]))

   }
    randomizeBuildingFunction()

This code is in the .didMove function. Here is an example of one of the functions since they are all essentially the same except for slight interval modifications and texture changes.

func createBuildingOne() {
            let one = SKSpriteNode(imageNamed: "BuildingOne.png")

            one.anchorPoint = CGPoint(x: 0.5, y: 0.5)
            one.physicsBody = SKPhysicsBody(rectangleOf: one.size)
            one.physicsBody?.affectedByGravity = false
            one.physicsBody?.contactTestBitMask = ColliderType.Buildings.rawValue
            one.physicsBody?.categoryBitMask = ColliderType.Buildings.rawValue
            one.physicsBody?.collisionBitMask = ColliderType.Buildings.rawValue
            self.addChild(one)

            one.zPosition = 2
            one.position = CGPoint(x: self.frame.width * 0.5, y: -self.frame.height * 0.5 + one.size.height / 1.5)

            let moveLeft = SKAction.moveBy(x: -self.frame.width - one.size.width, y: 0, duration: 6)

            one.run(SKAction.sequence([moveLeft, SKAction.removeFromParent()]))
        }

Is there something wrong with my randomizing code at the top? The app builds fine and there are not any errors...

Thanks in advance!

1

There are 1 best solutions below

0
Brantley On

Thanks for the comment @Knight0fDragon! Yes you are right, and after hours of wondering what I was missing, and a little help from a friend of mine who is an Apple Developer, I finally realized that I had to call the run block somehow...

Hence the answer to my question were these 2 little lines of code:

let useFunctionForever = SKAction.repeatForever(SKAction.sequence([useRandomResult, wait]))

    run(useFunctionForever)

I had to run the repeatForever action, which would then call and run my block. I had the repeatForever Action already there, but my mistake was expecting it to run automatically when the entire function was called. So I guess my issue wasn't necessarily with the arc4Random, but with the repeatForever part of my code.