P.Dane
P.Dane

Reputation: 91

Setting node to spawn randomly from an array of points and to fall at gradually faster speeds

The result I am looking to achieve: I am looking to spawn a node randomly from 3 different locations stored in an array. Once spawned, I would like the node to fall. Gradually over time, I would like to have the node fall at faster speeds.

What I currently have: The node spawns at a set location and falls like it should. The node currently doesn't spawn randomly and the speed at which it falls doesn't increase. I have an array written but it currently isn't functioning the way it should.

Updated code:

 var nodeDropTime:TimeInterval = 5

   func fallingNodeAction(){

        self.node = SKSpriteNode(imageNamed: "node 2")
        self.node.zPosition = 1
        self.node.physicsBody = SKPhysicsBody(circleOfRadius: self.node.size.height / 10.0)
        self.node.physicsBody?.isDynamic = true
        self.node.physicsBody?.allowsRotation = false
        self.node.physicsBody?.affectedByGravity = true

        nodeDropTime -= 1

        var nodePosition = Array<CGPoint>()

        nodePosition.append((CGPoint(x:400, y:475)))
        nodePosition.append((CGPoint(x:450, y:475)))
        nodePosition.append((CGPoint(x:500, y:475)))

        self.node.physicsBody?.categoryBitMask = ColliderType.nodeCategory
        self.node.physicsBody?.contactTestBitMask = ColliderType.boundary
        self.node.physicsBody?.collisionBitMask = 0

        let shuffledLocations = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: nodePosition) as! [CGPoint]

        self.node.position = shuffledLocations[0]

    }

    fallingNodeAction()

Upvotes: 3

Views: 87

Answers (1)

Nik
Nik

Reputation: 1664

For the random location, import GameplayKit, so you can use arrayByShufflingObjectsInArray on the array of CGPoints to then choose the first item in the array as the location. The code:

let shuffledLocations = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: nodePosition) as! [CGPoint]

self.node.position = shuffledLocations[0]

Upvotes: 1

Related Questions