【发布时间】:2023-03-27 20:39:02
【问题描述】:
我有一个自定义类 Object 派生自 SKSpriteNode 并带有一个 SKLabelNode 成员变量。
#import <SpriteKit/SpriteKit.h>
@interface Object : SKSpriteNode {
SKLabelNode* n;
}
@end
在实现中,我设置了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;
}
注意:我还没有将SKLabelNode 作为孩子添加到Object。我已将这行注释掉。
我有一个从SKScene 派生的单独类。在这个类中,我添加了一个Object 的实例作为一个孩子。这是我在此类中的touchesBegan:withEvent: 方法:
- (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]);
}
}
当我在SKScene 类中点击Object 的实例时,它会按预期工作。它检测到节点是Object 的一个实例。它记录:
TOP: Object
Object
现在,如果我回到我的 Object 类并取消注释 [self addChild:n] 以便将 SKLabelNode 作为子级添加到 Object,则会记录以下内容:
TOP: SKLabelNode
Object
SKLabelNode
SKSpriteNode
为什么将SKLabelNode 作为子类添加到派生自SKSpriteNode 的类会导致触摸检测到对象本身,以及SKLabelNode 和SKSpriteNode?
此外,为什么SKLabelNode 在顶部?我的 zPosition 为 -1,所以我假设在另一个类的 touchesBegan:withEvent: 中,Object 会被检测到顶部?
当然,我没有理解一个重要的概念。
【问题讨论】:
标签: objective-c sprite-kit uiresponder