I need to make a sprite node to ignore touch, so that it fall through to other nodes behind it (lower z order).
In UIKit this can be done by overriding hitTest, but there doesn’t seem to be a way here in SpriteKit. Another approach in UIKit is to change the zPosition
of the CALayer. This way we can setup the view such that its zOrder is at the top (so that it renders on top), but it’s touch behavior is still based on the relative order in superview’s subviews
array. Basically, we can decouple the touch handling and rendering order. I dont think we can do that in SpriteKit either.
Note that setting isUserInteractionEnabled = false
doesn’t work, since it still swallows the touch and prevent the nodes behind to receive touch event.
Anyone who used cocos2d before – this is basically the swallow touch
flag.
My use case is that, I have a particle effect added to the screen during game play (it’s added to the top of screen). Currently the particle swallows touches on its region, and affect my game play. I want to just show the particle, but do not interfere with touches for other components on screen.
2
Answers
override your touch functions at the
SKScene
level, then filter bySKNode
class name. this will bypass any particles in frontand here is the corresponding SKNode
I guess you are looking for this kind of behaviour.
Let’s see how to implement it!
The
isSwallowTouchEnabled
Let’s add the property to
SKNode
.Enhancing
SKScene
We need to provide
SKScene
with a method capable of searching theSKNode
affected by a touch and forward the touch event to it. During this search the method will skip the nodes whereisSwallowTouchEnabled == true
.The
EmitterNodeWithSwallowTouch
classNow we need to subclass
SKEmitterNode
in order be able to forward a touch event to the scene.The
Square
classFinally, I have created this class to test the functionality.
We will put the
Square
node behind the particle effect in the next paragraph.That’s it! Let’s test it
Hope it helps.
P.S. Cocos2D was a fun game engine.