Enable your node to respond to user input, like touches or mouse clicks.
There are two strategies you can adopt when supporting user interaction.
Enable user interaction on a single catch-all node, for example the scene, and calculate the child node or nodes that the user is interacting with by doing custom hit tests.
Enable user interaction on every node you want the user to interact with, and subclass them to implement their responder functions.
Catch All User Interaction by Using a Parent Node
Listing 1 shows an example of how to handle all user interaction on a parent node–in this case, the scene itself. The
Touch class subclasses
SKScene and overrides its
user to return
touches method shows two techniques to find the nodes that have been touched.
nodes returns an array of all of the sprites and
node returns the top-most touched node.
In this example, the child nodes should have
user set to
false. The parent scene is responsible for responding to user interactions.
Listing 2 shows the equivalent code for macOS.
Enable User Interaction on All Nodes
Listing 3 shows an example of supporting user interaction on individual nodes in your scene. Instances of
Touch are added as children of a standard scene and user interaction is handled by each independently.
In the case of overlapping nodes, only one will register a user interaction. For example, of two overlapping nodes, the one with the highest
z receives the touch. For two nodes with an equal
z, the last node in the parent's
children array receives the touch.
Handle User Interaction on Hidden Nodes by Using Alpha
Translucent nodes–those with an
alpha of less than
1 but greater than
0–still receive user interactions. You can set a node's
least to make it effectively transparent and yet still respond to touches or mouse movements, although giving it a color of
clear has the same effect.
Review the Bounds of Node User Interaction
User interaction is based on the bounding box of the node. Sprite nodes containing textures with transparent areas or shape nodes with non-rectangular shapes will still report touches and mouse interactions even if the interaction is over a transparent part of their content.
If you build a composite node, the region that receives user interaction events is dependent on the node tree. Listing 4 shows the code used to create a subclassed
SKNode that renders six circular shape nodes forming a larger circle.
If you were to add an instance of
Touch to an
SKScene with no other nodes behind it, all touches inside its
calculate would be reported. Figure 1 shows the accumulated frame of
Touch. Any user events within the dashed line will call
However, if you were to place an instance of
Touch above another node using, for example, the code in Listing 5, only touches on its child nodes would be reported.