1

So I generated an SKShapeNode, and need to know when that node is clicked. I do so by calling:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
   UITouch *touch = [touches anyObject];
   CGPoint positionInScene = [touch locationInNode:self];
   SKNode *node = [self nodeAtPoint:positionInScene];
   if ([node.name isEqualToString:TARGET_NAME]) {
       // do whatever
    }
  }
}

So the result I'm getting is pretty weird. Clicking the dot itself does in fact work. However, pressing anywhere on the screen that is southwest of the SKShapeNode's position will also render the above code as true.

enter image description here

With the SKShapeNode represented by the red dot, any UITouch in the shaded region would render my code above as true.

Here is how I am building the SKShapeNode. It may also be important to note that my application runs in landscape mode.

#define RANDOM_NUMBER(min, max) (arc4random() % (max - min) + min)


- (SKShapeNode *)makeNodeWithName:(NSString *)name color:(UIColor *)color
{
  SKShapeNode *circle = [SKShapeNode new];

  int maxXCoord = self.frame.size.width;
  int maxYCoord = self.frame.size.height;
  CGFloat x = RANDOM_NUMBER((int)TARGET_RADIUS, (int)(maxXCoord - TARGET_RADIUS));
  CGFloat y = RANDOM_NUMBER((int)TARGET_RADIUS, (int)(maxYCoord - TARGET_RADIUS - 15));

  circle.fillColor = color;
  circle.strokeColor = color;
  circle.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(x, y, TARGET_RADIUS, TARGET_RADIUS)].CGPath;

  circle.name = name;
  return circle;
}

Thanks for any help!

4

1 回答 1

4

发生这种情况是因为圆形节点的位置在原点,并且它从 (x,y) 开始在矩形中绘制路径。因此,节点的框架被拉伸以包含 (0,0) 到 (x+TARGET_RADIUS, y+TARGET_RADIUS) 之间的所有内容。

您可以通过可视化圆圈的框架来亲自检查一下:

SKSpriteNode *debugFrame = [SKSpriteNode spriteNodeWithColor:[NSColor yellowColor] size:circle.frame.size];
debugFrame.anchorPoint = CGPointMake(0, 0);
debugFrame.position = circle.frame.origin;
debugFrame.alpha = 0.5f;
[self addChild:test];

这揭示了实际的可点击区域(在 OSX 上):

可视化的可点击区域

要解决您的问题,请尝试以下操作:

circle.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(-TARGET_RADIUS/2.0f, -TARGET_RADIUS/2.0f, TARGET_RADIUS, TARGET_RADIUS)].CGPath;

并添加

circle.position = CGPointMake(x, y);
于 2014-02-21T18:23:21.393 回答