如何检测子类精灵触摸

时间:2013-10-17 15:49:20

标签: ios cocos2d-iphone ccsprite

我将一个名为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");
    }
  }
}

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

2 个答案:

答案 0 :(得分: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");
        }
    }
}

答案 1 :(得分:0)

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

首先,在NewSprite中将 nsprite 作为类变量,以便在从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");
    }
  }
}