2010-12-04 26 views
6

Estoy tratando de detectar Colisión de dos sprites de la siguiente manera ... pero cuando trato de ejecutar el juego no ocurre ninguna colisión ... ¿qué estoy haciendo mal?Detección de colisión en el juego Cocos2d?

- (void)update:(ccTime)dt { 



    CGRect projectileRect = CGRectMake(projectile.position.x - (projectile.contentSize.width/2), 
             projectile.position.y - (projectile.contentSize.height/2), 
             projectile.contentSize.width, 
             projectile.contentSize.height); 

    //CGRectMake(0,220,320,50); 
    CGRect targetRects = CGRectMake(_monkey.position.x - (_monkey.contentSize.width/2), 
           _monkey.position.y - (_monkey.contentSize.height/2), 
           _monkey.contentSize.width, 
           _monkey.contentSize.height); 

     if (CGRectIntersectsRect(projectileRect, targetRects)) { 
        NSLog(@"ha ha Collision detected"); 
     }      

}

proyectil sprite animando desde la parte superior de la pantalla a la parte inferior y mono sprite animando de izquierda a derecha en la parte inferior del proyectil pasa por el mono, pero el registro no lo hace ser llamado ???

- (void)update:(ccTime)dt { 

CGRect projectileRect = [projectile boundingBox]; 
CGRect targetRects = [_monkey boundingBox]; 

if (CGRectIntersectsRect(projectileRect, targetRects)) 
{ 
    NSLog(@"ha ha Collision detected"); 
} 

CGRect projectileRects = CGRectMake(projectile.position.x - (projectile.contentSize.width/2), 
            projectile.position.y - (projectile.contentSize.height/2), 
            projectile.contentSize.width, 
            projectile.contentSize.height); 
CGRect targetRect = CGRectMake(_monkey.position.x - (_monkey.contentSize.width/2), 
           _monkey.position.y - (_monkey.contentSize.height/2), 
           _monkey.contentSize.width, 
           _monkey.contentSize.height); 
if (CGRectIntersectsRect(projectileRects, targetRect)) { 
    NSLog(@"@@@@@@@@@@@@@@@@@@@@@@@@@@@@");    
} 

}

- (void) spriteMoveFinished: remitente (id) {

//NSLog(@"spriteMoveFinished"); 
CCSprite *sprite = (CCSprite *)sender; 
[self removeChild:sprite cleanup:YES]; 

if (sprite.tag == 1) { 
    [_targets removeObject:sprite]; 



} else if (sprite.tag == 2) { 
    [_projectiles removeObject:sprite]; 
} 

}

- (void) addTarget {

projectile = [CCSprite spriteWithFile:@"egg.png" rect:CGRectMake(0, 0, 10, 10)]; 
projectile.position = ccp(_bear.position.x,_bear.position.y-20); 
projectile.tag=2; 
[self addChild:projectile]; 

CGPoint realDest = ccp(_bear.position.x, _bear.position.y - 380); 

int minDuration = 2.0; 
int maxDuration = 4.0; 
int rangeDuration = maxDuration - minDuration; 
int actualDuration = (arc4random() % rangeDuration) + minDuration; 

// Move projectile to actual endpoint 
[projectile runAction:[CCSequence actions: 
         [CCMoveTo actionWithDuration:actualDuration position:realDest], 
         [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)], 
         nil]]; 

// Add to projectiles array 
projectile.tag = 2; 
[_projectiles addObject:projectile]; 

}

-(void) registerWithTouchDispatcher 
{ 
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES]; 
} 

- (BOOL) ccTouchBegan: (UITouch *) toque withEvent: (UIEvent *) evento {

CGPoint touchLocation = [self convertTouchToNodeSpace:touch]; 


if(CGRectContainsPoint(CGRectMake(0,0,320,50),touchLocation)) 
{ 
    if (![_walkMonkey isDone]) { 
     [_monkey runAction:_walkMonkey]; 
    } 


} 
else { 

} 

return YES; 

}

- (void) ccTouchEnded: (UITouch *) withEvent contacto: (UIEvent *) evento {

CGPoint touchLocation = [self convertTouchToNodeSpace:touch]; 

if(CGRectContainsPoint(CGRectMake(0,0,320,50),touchLocation)) 
{ 

    [_monkey stopAction:_walkMonkey]; 

} 

}

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {  

    CGPoint touchLocation = [self convertTouchToNodeSpace:touch]; 

    CGPoint oldTouchLocation = [touch previousLocationInView:touch.view]; 
    oldTouchLocation = [[CCDirector sharedDirector] convertToGL:oldTouchLocation]; 
    oldTouchLocation = [self convertToNodeSpace:oldTouchLocation]; 

    CGPoint translation = ccpSub(touchLocation, oldTouchLocation);  

    if (translation.x > 3) { 

     _monkey.flipX=YES; 
    } 
    else if (translation.x < -3){ 
     _monkey.flipX=NO; 

    } 

    if(CGRectContainsPoint(CGRectMake(40,0,240,50),touchLocation)) 
    { 

     CGPoint newPos = ccpAdd(translation,_monkey.position); 
     if(newPos.x >= 320 || newPos.x <= 20) 
     { 
      NSLog(@"monkey not walking"); 
     } 
     else { 
      newPos.y = 100; 
      _monkey.position = newPos; 
     } 

    } 

} 

Respuesta

25

Se debe utilizar la funcionalidad integrada:

CGRect projectileRect = [projectile boundingBox]; 
CGRect targetRects = [_monkey boundingBox]; 

if (CGRectIntersectsRect(projectileRect, targetRects)) 
{ 
    NSLog(@"ha ha Collision detected"); 
} 

El método boundingBox lleva un par de cosas en cuenta, por ejemplo, si el nodo está posicionado en relación con su padre.

También tenga en cuenta que prefijar variables con un guión bajo se considera una mala práctica en Objective-C. Apple reserva nombres variables con caracteres de subrayado iniciales para sus bibliotecas internas. Si realmente necesita clasificar variables de instancia, una forma común es sufijarlas con un guión bajo.

Cuestiones relacionadas