-1
    func createBall(){
        ballS = SKNode()
        let ball = SKSpriteNode(imageNamed: "Ball")

        saw.zPosition = 2
        ballS.addChild(ball)
        self.addChild(ballS)
}

This creates a Ball node with z position 2. But while running the game, I want to create another ball that has a z position at 1. How can I do this, or do I have to make a whole new function that makes a ball node with z position 1?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291

3 Answers3

0

If each ball sprite has to be a child of the ballS node, then you could do the following.

Define ballS as a property (i.e. after the class definition but before any functions)

let balls = SKNode()

in didMove(to:), add the ballS Node:

addChild(ballS) 

Create a addBall function: (don't call it createBall unless all it does create the ball)

func addBall(withZPosition zPos: Int) {
    let newBall = SKSpriteNode(imageNamed: "Ball")
    newBall.zPosition = zPos
    ballS.addChild(newBall)
    }

Then simply call addBall(withZPosition:) to create and add a new ball:

addBall(withZPosition: 2)

If you want more control over the ball that is created (e.g. you want to change some of it's properties before adding it to the scene), you can make a createBall function that creates a new ball and returns the new node:

func createBall(withZPosition zPos: Int) -> SKSpriteNode {
    let newBall = SKSpriteNode(imageNamed: "Ball")
    newBall.zPosition = zPos
    return newBall
    }

and use this as follows:

let newBall = createBall(withZPosition: 2)
newBall.size = CGSize(x: 50, y:50)
ballS,addchild(newBall)
Steve Ives
  • 7,894
  • 3
  • 24
  • 55
0

U can have a global variable so that whenever you want to change u set it and create the ball

so create a variable

var myZposition = 2

and create a ball at the start in didmove to view by calling createBall()

   func createBall(){
    ballS = SKNode()
    let ball = SKSpriteNode(imageNamed: "Ball")

    saw.zPosition = myZPosition
    ballS.addChild(ball)
    self.addChild(ballS)
 }

then after these if you want to change the zPosition just set it at the end of didmove to view

myZposition = 1

Then whenever u create balls from here your zPosition would be 1. This would be an easy setup if you have lots of balls and implement a change in zPosition for reaching a specific area of the game Hope this helped

-1

I'd suggest to use an argument, like:

func createBall(z: Int) {
    ballS = SKNode()
    let ball = SKSpriteNode(imageNamed: "Ball")

    saw.zPosition = z
    ballS.addChild(ball)
    self.addChild(ballS)

}

And use it as:

createBall(z: 2)
sabi
  • 423
  • 2
  • 8