跟踪精灵

时间:2013-04-22 21:12:18

标签: iphone ios objective-c cocos2d-iphone

我正在创建一个Cocos2D应用程序,它将拥有4到12个精灵,用户可以与之交互/移动(图片中的精灵1-4)。将有相同数量的目标精灵,用户将能够将其他精灵拖动到(图片中的目标1 - 4)。我正在考虑为所有精灵添加标签以区分它们。我遇到的困难是确定跟踪可移动精灵的正确方法,这些精灵与每个精灵的目标精灵相关。

我应该如何跟踪这些关系?

  • 精灵1 - 目标3
  • 精灵2 - 目标1
  • 精灵3 - 目标2
  • 精灵4 - 目标4

Sprites and Targets

1 个答案:

答案 0 :(得分:0)

创建两个不同的isntance可变数组来保存你的对象和一个数组来保存你正确的答案,即

//In your .h
NSMutableArray *_targets;
NSMutableArray *_moveableSprites;
NSArray *_answers;

//In your .m
_targets = [[NSMutableArray alloc] init];
_moveableSprites = [[NSMutableArray alloc] init];
_answers = [[NSArray alloc] initWithObjects:@"101", @"103", @"102", @"104", nil];

创建精灵时,为它们分配标签值,即

CCSprite *target1 = [CCSprite spriteWithFile:@"file.png"];
//Make sure target tags start from 0 and increment up
target1.tag = 0;

然后在将每个精灵添加到您的图层之前,将它们添加到各自的数组中,即

[_targets addObject:target1];

然后你可以写一个方法来检查精灵位置(类似于这个):

- (void)checkSprites {
    for(CCSprite *sprite in _moveableSprites) {
        for(CCSprite *target in _targets) {
            if(CGRectIntersectsRect(sprite.boundingBox, target.boundingBox)) {
                if(sprite.tag == [_answers objectAtIndex:target.tag]) {
                    // Correct sprite in target.....do stuff
                } else {
                    // Not correct sprite.....do stuff
                }
            }
        }
    }
}