0

我继承了一个名为 newSprite.h / newSprite.m 的精灵,并在其中添加了一个精灵

CCSprite *nsprite = [CCSprite spriteWithFile:@"mouse.png"];
[self addChild: nsprite];

在gamelayer.m中,我添加了以下代码

newSprite *newp = [newSprite node];
newp.position = ccp(actualX, actualY);
[self addChild:newp];
[_NSMutableArrayName addObject:newp];

当我使用以下代码来检测我触摸了哪个精灵时

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
  UITouch *touch = [touches anyObject];
  CGPoint location = [self convertTouchToNodeSpace: touch];

 for (CCSprite *target in _NSMutableArrayName) {
    if (CGRectContainsPoint(target.boundingBox, location)) {
        CCLOG(@"yes i am touched");
    }
  }
}

但它不起作用,无法检测到精灵,那么错在哪里?请帮助我,谢谢

4

2 回答 2

0

您正在尝试检测子精灵的触摸并给出父精灵的边界。

首先,将nsprite作为 NewSprite 中的类变量,以便在从 GameLayer 调用它时保留它的引用。然后尝试更改此方法,例如:

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
  UITouch *touch = [touches anyObject];
  CGPoint location = [self convertTouchToNodeSpace: touch];

  for (CCSprite *target in _NSMutableArrayName) {
    CCSize size = target.nSprite.contentSize;
    CCRect rect = CCRectMake(target.position.x - size.width/2, target.position.y - size.height/2, width, height);

    if (CGRectContainsPoint(rect, location)) {
        CCLOG(@"yes i am touched");
    }
  }
}
于 2013-10-17T20:49:57.993 回答
0

尝试使用这个:

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [self convertTouchToNodeSpace:touch];

    for (CCSprite *target in _NSMutableArrayName) {
        CGSize size = node.contentSize;
        CGRect r = CGRectMake(0.f, 0.f,
                              size.width, size.height);
        if (CGRectContainsPoint(r, local)) {
            CCLOG(@"yes i am touched");
        }
    }
}
于 2013-10-17T15:57:11.740 回答