Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting touch inside bounding box (alpha mask) of Sprite using SpriteKit

I am starting to learn Swift2 to develop on iOS using SpriteKit and I cannot seem to detect if I touched a visible part of my Sprite.

I can find which node was touched like this:

let touchedNode = self.nodeAtPoint(location)  

But this detect the touch on the sprite. I would like to detect the touch on the "not transparent" part of the sprite only.

I tried creating a PhysicsBody with an alpha mask bounding box and testing if the bounding box of the node I selected contains the location of the touch like this:

sprite.physicsBody = SKPhysicsBody.init(texture: sprite.texture!, size: sprite.size)
sprite.physicsBody?.affectedByGravity = false
if (touchedNode.containsPoint(location)){

But it didn't help. If I click in a transparent part of my sprite, the event still triggers.

The documentation says "A new physics body is created that includes all of the texels in the texture that have a nonzero alpha value.", so shouldn't it work?

Thanks for your time.

PS: I also tried to be more generous on my alpha threshold, but this also did not work (in case my transparency wasn't perfect).


UPDATE:

To add a little more details, I am building a level editor. This means that I will create many nodes, depending on what the user chooses, and I need to be able to select/move/rotate/etc those nodes. I am actually using SKSpriteNodes as my PNG pictures are automatically added in xcassette that way. I decided to use the PhysicsBody's Alpha Mask bounding box, as this value is shown in the Scene Editor (Xcode) when you select a node, and when selected, the Alpha Mask highlights exactly the part of my Sprite that I want to be able to detect a touch inside.

If I am using the wrong ideas/techniques, please tell me. This is possible as I am only starting to use Swift and SpriteKit.


UPDATE 2

I queried the physicsWord (as recommended) to get the right physicsBody and got the name of the attached node like this:

let body = self.physicsWorld.bodyAtPoint(location)
print(body?.node?.name)

But this is still printing the name of the node even if I touch outside the bounding box, which makes no sense to me.

Thank you anyway for your help.

like image 484
David Gourde Avatar asked Oct 16 '15 02:10

David Gourde


1 Answers

The SKPhysicsBody doesn't define the bounds of the SKNode. You can do the hit check by querying the SKPhysicsWorld of your scene by calling bodyAtPoint on it. That will return the SKPhysicsBody you are interested in.

like image 150
Good Doug Avatar answered Oct 02 '22 05:10

Good Doug