I want to have about 15 treats and I just want to change the x position of these treats. I don't want to copy and paste this code 15 times, so how can I go about doing this?
func createTreatNode() {
let atlas = SKTextureAtlas(named: "Treat")
let q1 = atlas.textureNamed("treat1.png")
let q2 = atlas.textureNamed("treat2.png")
let q3 = atlas.textureNamed("treat3.png")
let treatAnimation = [q1, q2, q3]
let treat = SKSpriteNode(texture: q1)
treat.position = CGPoint(x: 1000, y: 150)
print("treat position \(treat.position)")
treat.size = CGSize(width: 60, height: 50)
treat.name = "Treat"
let animate = SKAction.animate(with: treatAnimation, timePerFrame: 0.2)
let repeatAction = SKAction.repeatForever(animate)
treat.run(repeatAction)
let body = SKPhysicsBody(rectangleOf: treat.size)
body.usesPreciseCollisionDetection = true
body.affectedByGravity = false
body.collisionBitMask = 0x7FFFFFFF
body.contactTestBitMask = 0x80000000
treat.physicsBody = body
addChild(treat)
}
I recommend adding a parameter to your createTreatNode()
function. Then change treat.position = CGPoint(x: 1000, y: 150)
to treat.position = CGPoint(x: atXCoordinate, y: 150)
like this:
func createTreatNode(atXCoordinate: Int) {
let atlas = SKTextureAtlas(named: "Treat")
let q1 = atlas.textureNamed("treat1.png")
let q2 = atlas.textureNamed("treat2.png")
let q3 = atlas.textureNamed("treat3.png")
let treatAnimation = [q1, q2, q3]
let treat = SKSpriteNode(texture: q1)
treat.position = CGPoint(x: atXCoordinate, y: 150)
print("treat position \(treat.position)")
treat.size = CGSize(width: 60, height: 50)
treat.name = "Treat"
let animate = SKAction.animate(with: treatAnimation, timePerFrame: 0.2)
let repeatAction = SKAction.repeatForever(animate)
treat.run(repeatAction)
let body = SKPhysicsBody(rectangleOf: treat.size)
body.usesPreciseCollisionDetection = true
body.affectedByGravity = false
body.collisionBitMask = 0x7FFFFFFF
body.contactTestBitMask = 0x80000000
treat.physicsBody = body
addChild(treat)
}
This way you can call createTreatNode(atXCoordinate:)
15 times with different x coordinates and it will add treat child nodes to the current scene at the x coordinates you passed to it.
User contributions licensed under CC BY-SA 3.0