3
votes

As a very beginner in Cocos2D i´m trying to make an iPhone game where some cows move randomly around the screen. I used the code for moving the sprites from here: highoncoding.com/.../. I´m adding the sprites in the init method wia an addAnimal method:

-(void) addAnimal {
animal = [CCSprite spriteWithFile:@"cow.png"];
animal.position = [self generateRandomCoordinates];

[self addChild:animal];
[self startAnimation:animal];
}

My problem: When i add more than one cow to my game, they move from that random spawn position to another random position and then the first cow stops and the other cow goes on correctly. The startAnimation command in the finishedMoving method goes always to the last sprite. That means i need better control over my sprites but how to da that right?

1
Check out BOIDS flocking algorithm.tallen11
I´ll try that later when i´m more familiar with Cocos2D. Thank you!gimp

1 Answers

4
votes

You can try to implement animal class, that will contain your sprite and incapsulate random movement. Smth like

@implementation Cow

- (id) init
{
    self = [super init];

    if( self != nil )
    {
        CCSprite* cowSprite = [CCSprite spriteWithFile:@"cow.png"];
        [self addChild: cowSprite];
    }

    return self;
}

- (void) onEnter
{
    [super onEnter];
    [self makeRandomMovement];
}

- (void) makeRandomMovement
{
    id randomMoveAction = // create your random move action here
    id moveEndCallback = [CCCallFunc actionWithTarget: self selector: @selector(makeRandomMovement)];
    id sequence = [CCSequence actionOne: randomMoveAction two: moveEndCallback];
    [self runAction: sequence];
}

@end

In such way after ending random movement part, method makeRandomMovement will be called again to generate and start new random movement part.

then remake your addAnimal method to smth like

- (void) addAnimal
{
    Cow* newCow = [Cow node];
    [newCow setPosition: [self generateRandomPosition]];
    [self addChild: newCow];
}