rulezzer
rulezzer

Reputation: 55

How detect which sprites I touch

I'm generating a grid of bricks (SKSpriteNode) in a for loop like this:

for row in 0..<numRows
    {
        for col in 0..<numColumns
        {
            let brick = SKSpriteNode(color: UIColor.white, size: CGSize(width: brickWidth, height: brickHeight))

            brick.anchorPoint = CGPoint.zero
            brick.name = "brick_d" 
            brick.position = CGPoint(x: brickFirstXPosition + col * 65, y: brickFirstYPosition + row * 65)

            self.addChild(brick)
        }
    }

Now I don't know how distinguish one node from another, I have to do this according to their different position or something else? Practically I need to touch one specific node with a touchesBegan func. for doing things according to the node properties (bg, image contained, etc.)

Upvotes: 0

Views: 255

Answers (1)

Steve Ives
Steve Ives

Reputation: 8134

Use touchesBegan():

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        let touch = touches.first // get the first touch
        let touchedNode = selectNodeForTouch(touch.location(in: self))
        // do stuff with your 'touchedNode'
    }

Upvotes: 2

Related Questions