Search code examples
swiftsprite-kittouchesbegan

touchesBegan with physhicsBody


I am creating a 2x2 matrix, and putting nodes into it. When I select a node inside a position of the matrix, he changes his color to red using the colorize action.

The problem is that if the node image is too big he'll recognize the touch even if i touch in another square of the matrix.

For example :

[0-0][0-1]
[1-0][y]

My node is in the Y square (position : 1-1). If the image is bigger than the size of the square he will get the touch even if I click on the 1-0 square.

I can't get the touch using the matrix position of the node because the image overlaps it so it never touches the matrix square.

Is there anyway I could get the touch using the PhyshicsBody of the node instead of the

let location = touch.locationInNode(self)
let node = nodeAtPoint(location)

Solution

  • If I understand your issue.

    I understand you need paint element conform touch position.

    What I do, in this example I am using Scene for reference, but you can do with others Sprite, well, I slice my screen in 4 pieces, and I got the touch point and verify position in Scene.

    class test:SKScene{
        override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
            if let touch = touches.first as? UITouch{
                let touchLocation = touch.locationInNode(self)
    
                if touchLocation.x < self.size.width/2 && touchLocation.y < self.size.height/2 {
                    //paint red [1,0]
                }else if touchLocation.x < self.size.width/2 && touchLocation.y > self.size.height/2 {
                    //paint red [0,0]
                }else if touchLocation.x > self.size.width/2 && touchLocation.y > self.size.height/2 {
                    //paint red [0,1]
                }else if touchLocation.x > self.size.width/2 && touchLocation.y < self.size.height/2 {
                    //paint red [1,1]
                }
            }
        }
    }
    

    Hope helped you..