Search code examples
sprite-kitskspritenode

How to detect if, one sprite node is the same colour as another sprite node then add to score if they are the same if not "restart game"


So I have a "Ball" (player) that you control, when the player hits a "colorOrb" the Ball changes to that colour all at random, so that part works, but I'm stuck on how to detect if the player changes to a random colour on how to detect if once it goes through a wall also of a random colour if they are both the same colour and add +1 or whatever to score. I've tried multiple ways but can't seem to figure it out. thanks in advance :)


Solution

  • Given a Ball and a Wall class

    class Ball: SKSpriteNode { }
    class Wall: SKSpriteNode { }
    

    In your didBegin(contact:) just compare the color property.

    class GameScene: SKScene, SKPhysicsContactDelegate {
    
        func didBegin(_ contact: SKPhysicsContact) {
    
            let nodeA = contact.bodyA.node
            let nodeB = contact.bodyB.node
    
            guard let nodes: (ball:Ball, wall:Wall) = (nodeA, nodeB) as? (Ball, Wall) ?? (nodeB, nodeA) as? (Ball, Wall) else { return }
    
            if nodes.ball.color == nodes.wall.color {
                // same color
                // TODO...
            }
    
        }
    }