如何在cocos2d中选择触摸rect的所有目标

时间:2012-01-26 19:57:59

标签: iphone objective-c ios5 cocos2d-iphone

我想使用touches

选择我的目标

通过以下编码创建未选择的点: -

    targets1 = [[NSMutableArray alloc] init];

         for(int i=0;i<3;i++)
            {
                for (int y=0; y<3; y++) {
                    CCTexture2D *texture = 
                    [[CCTextureCache sharedTextureCache] addImage:@"UnselectedDot.png"];
                        block = [CCSprite spriteWithTexture:texture rect:CGRectMake(0,0,82,82)];
                    CGFloat xoffset = ((block.contentSize.width)*10) + (((block.contentSize.height)-175)*y);
                    block.position = ccp( (i*82)+80,xoffset);
                   [bg1 addChild:block];

                    [targets1 addObject:block];
}
}

下面是我的示例输出。

现在我需要通过触摸方法选择所有点。我写了这样的编码: -

- (void)update:(ccTime)dt {
 //   NSLog(@"%@",targets1);
   for (CCSprite *sprite in targets1) {
       CGRect dotrect = CGRectMake(sprite.position.x, 
                             sprite.position.y-95, 
                             sprite.contentSize.width, 
                             sprite.contentSize.height);
       CGFloat x = location.x;
       CGFloat y = location.y;
       CGFloat width =  (location1.x - location.x);
       CGFloat height = -(location1.y - location.y);
       CGRect touchrect = CGRectMake (x, y, width,height); 
       NSLog(@"dotrect = %f,%f,%f,%f",dotrect.origin.x,dotrect.origin.y,dotrect.size.width,dotrect.size.height );                        
       NSLog(@"touch rect = %f,%f,%f,%f,%f,%f",touchrect.origin.x,touchrect.origin.y,touchrect.size.width,touchrect.size.height,location1.x,location1.y);
       if( CGRectContainsRect(dotrect, touchrect))
       {     //collision detection
            NSLog(@"am touched dot ");
       }
     }
}

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {    
    location = [touch locationInView:[touch view]]; 
    location = [[CCDirector sharedDirector] convertToGL:location];
    NSLog(@"am touched began");
    return YES;

}

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
    location1 = [touch locationInView:[touch view]]; 
    location1 = [[CCDirector sharedDirector] convertToGL:location1];
   location1 = [self convertToNodeSpace:location1]; 
}

按照上面的编码我的概念是: - 使用触摸开始和触摸结束我在这里制作矩形..在这些触摸正确我的未选择点矩形来了意味着collsison检测到..然后我可以在那里做我的东西。但它并没有全部碰撞。

我没有得到错误。

编辑:1

现在我知道为什么coillision不起作用...实际上我在触摸有多个矩形的矩...所以只...在这里,我使用rectcontainsrect ..问题..任何其他方法到rect有几个rect用于colllsion检测..

1 个答案:

答案 0 :(得分:0)

尝试使用:

CGPoint location=[touch locationInView:[touch view]];
    location = [self convertTouchToNodeSpace:touch];
CGRectContainsPoint([dot boundingBox], location);

在CCTouch ..方法内(根据您的意愿,根据您的意愿)。