Xavier Tan
Xavier Tan

Reputation: 53

SpriteKit- randomising spawn

I'm trying to spawn an object randomly in the X-axis, but its only spawning in the center.

below is my quote relating to the spawn. What's missing?

//random func

func random() -> CGFloat {
    return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}

func random(min: CGFloat, max: CGFloat) -> CGFloat {
    return random() * (max - min) + min
}

//spawn cat func

func spawnCat(){

    let randomXStart = random(min: gameArea.minX, max: gameArea.maxX)
    let randomXEnd  = random(min: gameArea.minX, max: gameArea.maxX)

    let startPoint = CGPoint(x: randomXStart, y:self.size.height * 1.2)
    let endPoint = CGPoint(x: randomXEnd, y: -self.size.height * 1)

    let cat = SKSpriteNode(imageNamed: "before right")
    cat.setScale(0.3)
    cat.position = startPoint
    cat.zPosition = 1
    self.addChild(cat)

    let moveCat = SKAction.move(to: endPoint, duration: 2)
    let deleteCat = SKAction.removeFromParent()
    let catSequence = SKAction.sequence([moveCat, deleteCat])
    cat.run(catSequence)

}

Upvotes: 1

Views: 63

Answers (1)

Knight0fDragon
Knight0fDragon

Reputation: 16827

Use arc4random_uniform instead to get the results you want

func spawnCat(){



    let randomXStart = CGFloat(arc4random_uniform(UInt32(gameArea.maxX - gameArea.minX))) + CGFloat(gameArea.minX)
    let randomXEnd   = CGFloat(arc4random_uniform(UInt32(gameArea.maxX - gameArea.minX))) + CGFloat(gameArea.minX)
    let startPoint = CGPoint(x: randomXStart, y:self.size.height * 1.2)
    let endPoint = CGPoint(x: randomXEnd, y: -self.size.height * 1)

    let cat = SKSpriteNode(imageNamed: "before right")
    cat.setScale(0.3)
    cat.position = startPoint
    cat.zPosition = 1
    self.addChild(cat)

    let moveCat = SKAction.move(to: endPoint, duration: 2)
    let deleteCat = SKAction.removeFromParent()
    let catSequence = SKAction.sequence([moveCat, deleteCat])
    cat.run(catSequence)

}

If you are getting 0 with this code then it means your gameArea width is 0

Upvotes: 3

Related Questions