Suzy Hakobyan Suzy Hakobyan - 25 days ago 7
Swift Question

How to set ball's random position in Spritekit?

I am making a game where there are two balls on the scene, but the user is going to tap on the correct ball. However, when user taps on the correct ball, I want to set a random position for my second ball that when the user taps on the correct ball, I want to also want the second ball to move randomly.
Here is my code for setting up the random positions of the ball:

//first ball
let currentBall = SKShapeNode(circleOfRadius: CGFloat(size))
currentBall.fillColor = redColor()

//second ball
let shape = SKShapeNode()
shape.path = UIBezierPath(roundedRect: CGRect(x: 64, y: 64, width: 160, height: 160), cornerRadius: 50).cgPath
shape.fillColor = cyanColor()

self.addChild(shape)
//Finding the random position of the ball
let xPosition = CGFloat(arc4random_uniform(UInt32((view?.bounds.maxX)! + 1)))
let yPosition = CGFloat(arc4random_uniform(UInt32((view?.bounds.maxY)! + 1)))

//Set the balls random position
currentBall.position = CGPoint(x: xPosition, y: yPosition)

//second balls random position
shape.position = CGPoint(x: xPosition, y: yPosition)

Answer

The issue is that you're setting the exact same position, which you have used for the first ball. As far as I understand both ball should appear at random independent positions. You should create a function to return a new position and call it for each ball:

class MyScene: SKScene {
    let firstBall = SKShapeNode()
    let secondBall = SKShapeNode()

    func handleTap() {
        //your code here, except that you don't create new nodes, just modify existing ones
        //at some point you will change balls' positions like this:
        currentBall.position = randomBallPosition()
        secondBall.position = randomBallPosition()
    }

    func randomBallPosition() -> CGPoint {
        let xPosition = CGFloat(arc4random_uniform(UInt32((view?.bounds.maxX)! + 1)))
        let yPosition = CGFloat(arc4random_uniform(UInt32((view?.bounds.maxY)! + 1)))
        return CGPoint(x: xPosition, y: yPosition)
    }
}

Hope this helps

Comments