Reputation: 936
I have various sprites on my screen and they are chasing after their target. That all works fine.
My question is, is there a way to set a boundary? I do not want them to be able to move above 160 points on the screen?
Every example I see is always using box2d, is there a way to do it strictly with 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];
}
}
I keep getting this error? -[__NSArrayM position]: unrecognized selector sent to instance 0x84597b0
all I want to do is have the sprite stop at 160 and that what the checkCollision method is for. just sets its position to 160.
Upvotes: 0
Views: 446
Reputation: 8739
What do you want them to do when they get to their threshold?
You could just check them in an scheduled update method.
Somewhere in your init you can run
[self schedule:@selector(update:)];
This will call the update method every frame.
- (void)update:(ccTime)dt
{
for (CCSprite *s in self.arrayOfSpritesToCheck)
{
if(s.position.y > 160) {
//Do something
}
}
}
As for your updated question, you are running position on an NSMutableArray
. Your gameObjects array is an array of arrays. When you do for (CCNode *myNode in _gameObjects)
it doesn't guarantee the objects coming out will be CCNode's and in fact in your case they are NSMutableArray
's.
Upvotes: 1
Reputation: 447
You can override the setPosition method in your sprite (game object) class and limit the vertical position to never exceed 160.
Upvotes: 0