2

Hi im new to swift and im creating a game based on touching target but each target is an image or an SKSpriteNode they have small size but sometime touch miss the target so i want to know how to make hit area bigger without making the target bigger. I use this code to detect touch for each target

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    /* Called when a touch begins */

    for touch in touches {

        let location = touch.locationInNode(self)

        let node = self.nodeAtPoint(location)
            if (node.name == "target1") {
//do some stuff
}
        }
}

Any suggestion.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Michel Kansou
  • 2,851
  • 4
  • 13
  • 22
  • You could create an invisible UIView that is above the sprites and make this view handle all the touch stuff. Then you could handle stuff with a given target when a touch on the UIView is close enough to the center of a given sprite or something. – spektr Oct 15 '15 at 19:21

3 Answers3

3

You can create a transparant clickable area which is bigger than the final image you want to show.

So for example you create:

let newNode = SKSpriteNode(bigger size, clearColor)
let originalNode = SKSpriteNode(size, finalColor/image)
newNode.addchild(originalNode)
rootNode.addchild(newNode).

You can also do this by using this in touchesbegan:

let touch = touches.first
touch.locationInNode(rootNode)

when you know the hitarea you want for each sprite you can now calculate which sprite is the one you want to hit.

This way you have a big transparant area to work with. Same holds for UIImageView, you can add a view which is empty for the biggest part but is only there to register touches. Now you can add an UIImageView to this view, and the imageview is only there to display the image and does not have to be as big as the view.

Hope this helps ;)

Simon
  • 2,419
  • 2
  • 18
  • 30
0

A view cannot simply detect a touch outside itself. By default, the user must touch the view in order for that view to be the hit-test view and to receive touchesBegan. What is your objection to making the target bigger?

The alternative is to detect the touch elsewhere and calculate, yourself, that you want to respond with respect to this view. But you would not do that through touchesBegan on this view.

matt
  • 515,959
  • 87
  • 875
  • 1,141
0

You can override func 'pointInside' of UIView class to expand clickable area.

Check this out, my post in another question.

https://stackoverflow.com/a/34505224/2303609

Community
  • 1
  • 1
Mark
  • 493
  • 5
  • 10