2013-03-21 118 views
0

我在屏幕上有各种精灵,他们追逐他们的目标。这一切都很好。cocos2d中的精灵边界?

我的问题是,有没有办法设置边界?我不希望他们能够在屏幕上移动超过160点?

我看到的每个例子总是使用box2d,有没有办法严格使用cocos2d?

- (void)addPlayers { 
    winSize = [CCDirector sharedDirector].winSize; 
    _officer = [[Officer alloc] initWithLayer:self]; 
    _officer.position = ccp(winSize.width/2, 40); 
    _officer.tag = 1; 
    [_batchNode addChild:_officer]; 

    _shotCaller = [[ShotCaller alloc] initWithTeam:2 layer:self]; 
    //create spawn point 
    _shotCaller.position = ccp(100, 100); 
    [_batchNode addChild:_shotCaller]; 

    NSString *gunName = [NSString stringWithFormat:@"gun.png"]; 
    _gun = [CCSprite spriteWithSpriteFrameName:gunName]; 
    _gun.anchorPoint = ccp(0.5, 0.25); 
    _gun.position = ccp(_shotCaller.contentSize.width/2, _shotCaller.contentSize.height/2 - 20); 
    [_shotCaller addChild:_gun]; 
    [self moveRandom:_shotCaller]; 

    NSMutableArray *team1GameObjects = [NSMutableArray arrayWithObject:_officer]; 
    NSMutableArray *team2GameObjects = [NSMutableArray arrayWithObject:_shotCaller]; 
    _gameObjects = [NSMutableArray arrayWithObjects:team1GameObjects, team2GameObjects, nil]; 
} 

for(CCSprite *myNode in _gameObjects) 
{ 
    if (myNode.position.y == 160) { 
     NSLog(@"1"); 
     [self checkCollision]; 
    } 
} 

我不断收到此错误? - [__ NSArrayM position]:发送到实例0x84597b0的无法识别的选择器

我想要做的就是使精灵停止在160处,并且checkCollision方法用于什么。只是将其位置设置为160.

+0

Ehhh,任何代码移动你的精灵,让这个不会搬过去你的边界。 – dqhendricks 2013-03-21 19:52:46

回答

1

当他们达到阈值时,你希望他们做什么?

您可以在计划的更新方法中检查它们。

某处在你的初始化,您可以运行

[self schedule:@selector(update:)]; 

这将调用Update方法每一帧。

- (void)update:(ccTime)dt 
{ 
    for (CCSprite *s in self.arrayOfSpritesToCheck) 
    { 
      if(s.position.y > 160) { 
       //Do something 
      } 
    } 
} 

至于您更新的问题,您正在运行NSMutableArray上的位置。你的gameObjects数组是一个数组数组。当你做for (CCNode *myNode in _gameObjects)它并不能保证出来的对象将是CCNode的,事实上在你的情况下,他们是NSMutableArray的。

+0

我正在这样做,它的工作。我遇到的唯一问题是它也将我的背景移到了我设定的精灵所做的事情上。所以我想真正的问题是,我怎么能做到这一点,并排除背景,这是一个精灵? – 2013-03-22 02:26:49

+0

不要通过self.children循环。循环播放你想要修正的精灵的数组 – 2013-03-22 20:15:30

+0

我知道你告诉我要做的100%正确,但我仍然收到错误。我要编辑我的问题,并在那里放一些代码。 – 2013-03-23 02:10:10

0

可以重写setPosition两种方法在你的精灵(游戏对象)类和限制的垂直位置不能超过160