【发布时间】:2014-07-27 17:08:32
【问题描述】:
我正在尝试对SKNode 进行子类化,以便当您触摸其框架(包含其子级的最小框架)时,touchesBegan:: 方法会通知它。
但是,似乎只有在触摸SKSpriteNode 孩子时才会通知它。我尝试过覆盖containsPoint: 方法,但没有成功。
这是我的代码:
@interface gameNode : SKNode {
SKSpriteNode* mainChar;
}
@property (weak, nonatomic) id <gameNodeDelegate> delegate;
@end
@implementation gameNode // When touched, touchesBegan: method not getting called.
-(id) init {
if (self = [super init]) {
self.userInteractionEnabled = YES;
mainChar = [SKSpriteNode node]; // When touched, touchesBegan: method gets called.
mainChar.color = [SKColor redColor];
mainChar.size = CGSizeMake(25, 25);
[mainChar runAction:[SKAction scaleTo:0 duration:0]];
mainChar.position = CGPointMake(100, 100);
[self addChild:mainChar];
SKSpriteNode* n = [SKSpriteNode node]; // When touched, touchesBegan: method gets called.
n.size = mainChar.size;
n.position = CGPointMake(-100, -100);
n.color = [SKColor greenColor];
[self addChild:n];
[mainChar runAction:[SKAction customAnimationWithProperties:CUAPropertiesForScaleBounce(CUADirectionTypeIn, 1)]];
}
return self;
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"That's a touch!");
}
-(void) touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
}
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
}
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
}
@end
只有当 mainChar 和 n 个 SKSpriteNodes 节点被触摸而不是屏幕的其余部分时,我才会得到一个触摸事件。
我能想到让它工作的唯一方法是在背景中添加一个透明的SKSpriteNode,但必须有更好的方法!
我怎样才能让SKNode“吞下”它收到的触摸,而不管孩子是否正在被触摸? 即我希望SKNodes 的框架中的触摸通过touchesBegan:: 方法通知它。
更新:我认为这是SKNode 框架的问题。当我添加孩子后..
NSLog(@"Frame Width: %f, Frame Height: %f", self.frame.size.width, self.frame.size.height);
框架返回的高度和宽度均为 0。但是,当我执行 [self calculateAccumulatedFrame] 时,它返回正确的大小。这是为什么呢?
更新:这个问题完全是一团糟。我将坚持使用添加透明SKSpriteNode 或使用SKScene 的解决方案。很抱歉给大家带来了困扰,感谢您的帮助。
【问题讨论】:
-
这不是您启用用户交互的方式。
self.userInteractionEnabled = YES;是正确的方式。 -
你不应该覆盖它。它可能会干扰
UIResponder系统,这可能就是您收不到触摸的原因。 -
我刚刚测试过,两者都一样,但我知道我应该通过 setter 完成它,我已经更新了 OP。
-
无论哪种方式都有效?但是您的帖子是关于节点不检测触摸?
-
抱歉,我的意思是它确实适用于儿童,但它仍然不适适用于
SKNode本身。 编辑: 实际上我说的是“工作方式相同”,它确实如此!我从两者中得到相同的结果。
标签: ios objective-c sprite-kit sknode