Обнаружение касания определенного спрайта на Cocos2d-iphone

Я следовал руководству Рэя по созданию простой игры для iPhone (здесь: http://goo.gl/fwPi ), и решил, что хочу, чтобы враги уничтожались, когда их касаются.

Мой первоначальный подход заключался в том, чтобы создать небольшой спрайт CCSprite в месте касания, а затем использовать CGRectMake для создания ограничивающего прямоугольника указанного спрайта, чтобы определить, был ли затронут спрайт врага. Так же, как Рэй со снарядом / противником. Но, конечно, мой способ сделать это не работает, и я не могу выбраться из этой ямы.

Вот соответствующий фрагмент кода. Любая помощь приветствуется:

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    // Choose one of the touches to work with
    UITouch *touch = [touches anyObject];
    CGPoint location = [self convertTouchToNodeSpace: touch];
    location = [[CCDirector sharedDirector] convertToGL:location];
    CCSprite *touchedarea = [CCSprite spriteWithFile:@"Icon-72.png" rect:CGRectMake(location.x, location.y, 2, 2)];
    touchedarea.tag = 2;
    [self addChild:touchedarea];
    [_touchedareas addObject:touchedarea];

}



- (void)update:(ccTime)dt {

    NSMutableArray *touchedareasToDelete = [[NSMutableArray alloc] init];
    for (CCSprite *touchedarea in _touchedareas) {
        CGRect touchedareaRect = CGRectMake(
                                           touchedarea.position.x, 
                                           touchedarea.position.y, 
                                           touchedarea.contentSize.width, 
                                           touchedarea.contentSize.height);

        NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init];
        for (CCSprite *target in _targets) {
            CGRect targetRect = CGRectMake(
                                           target.position.x - (target.contentSize.width/2), 
                                           target.position.y - (target.contentSize.height/2), 
                                           target.contentSize.width, 
                                           target.contentSize.height);

            if (CGRectIntersectsRect(touchedareaRect, targetRect)) {
                [targetsToDelete addObject:target];             
            }                       
        }

        for (CCSprite *target in targetsToDelete) {
            [_targets removeObject:target];
            [self removeChild:target cleanup:YES];                                  
        }

        if (targetsToDelete.count > 0) {
            [touchedareasToDelete addObject:touchedarea];
        }
        [targetsToDelete release];
    }

    for (CCSprite *touchedarea in touchedareasToDelete) {
        [_touchedareas removeObject:touchedarea];
        [self removeChild:touchedarea cleanup:YES];
    }
    [touchedareasToDelete release];
}

person thoumad    schedule 16.01.2011    source источник
comment
Я задал вопрос о лучших практиках для этого: stackoverflow.com/questions/2900691/ Надеюсь, это поможет!   -  person donkim    schedule 16.01.2011


Ответы (2)


Похоже, это очень сложный способ сделать это. Сам я кодил недолго, но, возможно, вам поможет следующее. Допустим, у вас есть nsmutablearray с именем враги, и вы добавляете новый объект врага в этот массив при его создании. вражеским объектом будет ccnode и внутри него будет ccsprite, называемый _enemySprite, затем выполните касание

 -(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {

    NSSet *allTouches = [event allTouches];
    UITouch * touch = [[allTouches allObjects] objectAtIndex:0];
    //UITouch* touch = [touches anyObject];
    CGPoint location = [touch locationInView: [touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location]; 

    int arraysize = [enemies count];
    for (int i = 0; i < arraysize; i++) {


        if (CGRectContainsPoint( [[[enemies objectAtIndex:i] _enemySprite] boundingBox], location)) {

            //some code to destroy ur enemy here


        }
    }
    //  NSLog(@"TOUCH DOWN");

}

надеюсь это поможет

person glogic    schedule 18.01.2011
comment
это часто не работает. Например, когда CCSprite принадлежит CCLayer, который не заполняет весь экран, и его позиция не (0, 0) - person Gargo; 02.07.2012
comment
Но когда это действительно convertToGL: мне помогло - person richy; 26.08.2012

Другой способ сделать это - вычислить расстояние между позицией касания и вашими спрайтами ... Если касание достаточно близко к одному из ваших спрайтов, вы можете убить его ... Примерно так ...

for (CCSprite *sprite in anArrayThatCOntainsAllYourSprites) {

  float distance = pow(sprite.position.x - location.x, 2) + pow(sprite.position.y - location.y, 2);

   distance = sqrt(distance);

         if (distance <= 10) {
                sprite.dead  = YES;
         }

}
person user123    schedule 09.03.2013