Load a class from String

I often need to dynamically load a class from a concatinated combination of strings and integers. So here is how you do it. In a game for example, you may have a LevelID stored in your appdelegate that changes at the game progresses, so I’ve made the example grabbing such a levelID from the delegate class.

YourAppDelegate *theDelegate = (YourAppDelegate*)[[UIApplication sharedApplication] delegate];
int LevelID = [theDelegate getLevelID];
NSString *levelToLoad = [NSString stringWithFormat:@"Level%i",LevelID];
Class newLevel = NSClassFromString(levelToLoad);

BAM, and it’s done.

simple cocos2d animation using .png sequence

Right, so I do a lot of animation in my apps, so here is the most simple creation of it

yourfile.h

@private CCSprite *youranimref;
@private CCAnimation *animation;

yourfile.m

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

self.isTouchEnabled = YES;

size = [[CCDirector sharedDirector] winSize];

// DECLARE ANIMATION
animation = [[CCAnimation alloc] initWithName:@"youranimref" delay:1/24.0];
youranimref = [CCSprite spriteWithFile:@"yourFirstAnimGrfx.png"];
[animation addFrameWithFilename: @"yourSecondAnimGrfx.png"];
[animation addFrameWithFilename: @"yourThirdAnimGrfx.png"];
[animation addFrameWithFilename: @"yourFourthAnimGrfx.png"];

// ADD ANIMATION
youranimref.position = ccp( 512, 435 );
[self addChild:youranimref z:5];

}
return self;
}

- (void) dealloc
{

// !!!!! VERY IMPORTANT - REMOVE TEXTURES AND RELEASE REFERENCE TO THE ANIMATION

[[CCTextureCache sharedTextureCache] removeUnusedTextures];
[[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames];

// RELEASE RETAINED OBJECTS
[animation release];

[super dealloc];
}

- (void) runAnimation
{

// RUN THE ANIMATION

CCAnimate* action = [CCAnimate actionWithAnimation:animation];
[youranimref runAction:action];

}

Code for multitouch

In my latest app Loopy Tunes, I needed to add multitouch functionality to a keyboard. I use Cocos2D, so if you’re like me, then just do the following.

In your delegate.m class, add this line

[glView setMultipleTouchEnabled:YES];

right after this one.

[director setOpenGLView:glView];

Then in your class.m where you are testing for multitouch, up in your init method, add the following line

self.isTouchEnabled = YES;

And then add your touch method somewhere down under the init method, just update the values of the areaToCheck


- (void)ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
NSSet *allTouches = [event allTouches];
for (UITouch* touch in allTouches) {

CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];

CGRect areaToCheck = CGRectMake(100,100,100,100);
if(CGRectContainsPoint(areaToCheck, location)) {
// whatever you want to happen here
}
}
}