Detecting if a specific sprite was touched on Cocos2d-iphone

巧了我就是萌 提交于 2019-12-01 08:19:43
glogic

That looks like a very difficult way to go about doing it. I havent been coding long myself but maybe the following might help you. lets say u have a nsmutablearray called enemies and you add the new enemy object to this array when ever you create one. enemy object would be a ccnode and have a ccsprite within it called _enemySprite then do the touch

 -(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");

}

hope this helps

Another way of doing it is that calculating distance between touch position and your sprites.. If touch is close enough to one of your sprites, you can kill it.. Something like this..

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;
         }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!