【问题标题】:Objective C - SKNode subclass to 'swallow' touches?Objective C - SKNode 子类“吞下”触摸?
【发布时间】: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


【解决方案1】:

SKNode 没有任何内在界限。它不执行任何绘图,您可以有效地认为它也没有在屏幕上呈现。 它不会检测触摸。

您正在寻找的功能最好由SKScene 提供。使用SKScene。

【讨论】:

  • 将SKScene 添加到另一个SKScene 是否正确?
  • @originaluser2 可以,但您最好使用SKSpriteNode。
  • 这就是我打算做的,但不想SKSpriteNodes 带来的额外包袱!尽管如此,这似乎是最好的解决方案。感谢您的帮助,对于最初令人困惑的问题,我深表歉意。
  • @originaluser2 SKSpriteNode 带来的“额外负担”包括正确的触摸处理。真的,这就是它带来的一切。说真的,根本没有“额外的行李”。
  • 好的。我只是希望Apple Documentation 更清楚,因为它声明“所有节点都是响应者对象,可以直接响应用户与屏幕上的节点的交互。”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多