0
votes

I'm making a game where I have a ball(the player) that is suppose to get from on side to the other of the screen. On both of the sides I have a SKSpriteNode that the ball needs to touch to score one point. When the ball touches the SKSpriteNode on on of the sides, then the ball needs to get to the other side and touch the other SKSpriteNode to score another point. And so on. How can I make so that when the game starts, the spritenode at the top is active, and when that is touched, the one at the bottom is active?

I've made a "incrementScore" function that adds one to the score everytime the ball touches the "points":

func incrementScore() {
    score += 1
    scoreLabel.text = String(score)
}

Then I have my two "goals" that the ball needs to touch to score:

func createGoals() {

    let goalTop = SKSpriteNode(imageNamed: "Goal")
    goalTop.name = "Goal"
    goalTop.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    goalTop.position = CGPoint(x: 0, y: 465)
    goalTop.physicsBody = SKPhysicsBody(rectangleOf: goalTop.size)
    goalTop.physicsBody?.affectedByGravity = false
    goalTop.physicsBody?.isDynamic = false
    goalTop.zPosition = 2
    self.addChild(goalTop)

    let goalBottom = SKSpriteNode(imageNamed: "Goal")
    goalBottom.name = "Goal"
    goalBottom.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    goalBottom.position = CGPoint(x: 0, y: -435)
    goalBottom.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 
    goalBottom.size.width - 10, height: goalBottom.size.height - 10))
    goalBottom.physicsBody?.affectedByGravity = false
    goalBottom.physicsBody?.isDynamic = false
    goalBottom.zPosition = 2
    self.addChild(goalBottom)

}

Also I've started on the didBegin contact function:

func didBegin(_ contact: SKPhysicsContact) {

    var firstBody = SKPhysicsBody()
    var secondBody = SKPhysicsBody()

    if contact.bodyA.node?.name == "Player" {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    } else {
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }

    if firstBody.node?.name == "Player" && secondBody.node?.name == 
    "Point" {
        incrementScore()
    }
}
1

1 Answers

0
votes

use the categoryBitMask to enable active bodies:

When you want goalTop to be active:

goalTop.categoryBitMask = category.Goal
goalBottom.categoryBitMask = 0

When you want goalBottom to be active:

goalTop.categoryBitMask = 0
goalBottom.categoryBitMask = category.Goal

Note: category.Goal is whatever number you use as your category