Search code examples
ioscocos2d-iphonesubclassccsprite

How would I modify this code to make it suitable for a subclass?


I have got this code that I used before, but now that it I have subclassed my sprite, I need to adapt it. Here it is:

-(void)moveRandom:(CCSprite*)mos
{
CGPoint randomPoint = ccp(arc4random()%480, arc4random()%320);
NSLog(@"%@", NSStringFromCGPoint(randomPoint));

CGPoint start = mos.position;
CGPoint end = randomPoint;
float distance = ccpDistance(start, end);
float duration = distance/450;
[mos runAction:
 [CCSequence actions:
  [CCMoveTo actionWithDuration:duration position: randomPoint],
  [CCCallBlock actionWithBlock:^{
     [self performSelector:@selector(moveRandom:) withObject:mos afterDelay:0.5];
 }],
  nil]
 ];
}

What it does is that it chooses a random point on the screen, then it makes it so that the sprite moves at a constant speed between the two points, then it moves the sprite, and re-calls the method.

EDIT: The reason that I want to do this is because I will instances of this sprite in my sprite's layer, and they are all going to be doing this method.

Should I not be incorporating this in my CCSprite subclass, but more like my sprite's layer?


Solution

  • Typically, in an OO way, the subclass of CCSprite would be responsible for itself (encapsulated). So when you wanted the sprite to move you (or the object to which the subclass of CCSprite is exposed) would call its moveRandom method. Then it would do the moving all on its own without the CCLayer to which it's attached knowing anything about how it achieved the move.

    The method in the subclass of CCSprite would look like this:

    @interface AnotherSprite : CCSprite {}
    
    -(void) moveRandom;
    
    @implementation AnotherSprite
    
    -(void)moveRandom
    {
        CGPoint randomPoint = ccp(arc4random()%480, arc4random()%320);
        NSLog(@"%@", NSStringFromCGPoint(randomPoint));
    
        CGPoint start = self.position;
        CGPoint end = randomPoint;
        float distance = ccpDistance(start, end);
        float duration = distance/450;
        [self runAction:
            [CCSequence actions:
                [CCMoveTo actionWithDuration:duration position: randomPoint],
                    [CCCallBlock actionWithBlock:^{
                        [self performSelector:@selector(moveRandom) withObject:nil afterDelay:0.5];
                    }],
            nil]
        ];
    }
    
    @end