I have a custom class Object
derived from SKSpriteNode
with an SKLabelNode
member variable.
#import <SpriteKit/SpriteKit.h>
@interface Object : SKSpriteNode {
SKLabelNode* n;
}
@end
In the implementation, I set up the SKLabelNode
.
#import "Object.h"
@implementation Object
- (instancetype) initWithImageNamed:(NSString *)name {
self = [super initWithImageNamed:name];
n = [[SKLabelNode alloc] initWithFontNamed:@"Courier"];
n.text = @"Hello";
n.zPosition = -1;
//[self addChild:n];
return self;
}
Note: I have not yet added the SKLabelNode
as a child to Object
. I have the line commented out.
I have a separate class derived from SKScene
. In this class, I add an instance of Object
as a child. This is my touchesBegan:withEvent:
method in this class:
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch* touch = [touches anyObject];
CGPoint loc = [touch locationInNode:self];
NSArray* nodes = [self nodesAtPoint:loc]; //to find all nodes at the touch location
SKNode* n = [self nodeAtPoint:loc]; //to find the top most node at the touch location
NSLog(@"TOP: %@",[n class]);
for(SKNode* node in nodes) {
NSLog(@"%@",[node class]);
}
}
When I tap on the instance of Object
in my SKScene
class, it works as I expected. It detects the node is an instance of Object
. It logs:
TOP: Object
Object
Now if I go back to my Object
class and uncomment [self addChild:n]
so that the SKLabelNode
is added as a child to Object
, this is logged:
TOP: SKLabelNode
Object
SKLabelNode
SKSpriteNode
Why does adding an SKLabelNode
as a child to a class derived from SKSpriteNode
cause the touch to detect the object itself, along with an SKLabelNode
and an SKSpriteNode
?
Furthermore, why is the SKLabelNode
on top? I have its zPosition as -1 so I would assume that in touchesBegan:withEvent:
of another class, the Object
would be detected as on top?
Surely, I am not understanding an important concept.