I recently started game development, but one of the things that I never put much thought to was the loading of images. I'm curious as to advice for improving my current code on loading images. I'm using cocos2d in iOS code, but if you know of optimization techniques in other languages I'd like to hear that as well.
//above the @implementation
#define kZLayerBase -1
#define kOffsetImg1 (-50)
#define kOffsetImg2 (50)
#define kPositionXImg1 (screenSize.width/2)
#define kPositionYImg1 (screenSize.height/2)
#define kPositionXImg2 kPositionXImg1
#define kPositionYImg2 kPositionYImg1
#define kWidthImg1 100
#define kHeightImg1 100
#define kWidhtImg2 100
#define kHeightImg2 100
//...
//individually
-(void)loadImages1{
CGSize screenSize = [[CCDirector sharedDirector] winSize];
CCSprite *img1 = [CCSprite spriteWithFile:@"img1.png"];
[img1 setPosition:ccp(kPositionXImg1, kPositionImg1)];
[self addChild:img1 z:kTagLayerBase];
CCSprite *img2 = [CCSprite spriteWithFile:@"img2.png"];
[img2 setPosition:ccp(kPositionXImg2, kPositionImg2)];
[self addChild:img2 z:kTagLayerBase];
}
//using a sprite sheet
-(void)loadImages2{
CCSprite *img1 = [CCSprite spriteWithFile:@"img.png" rect:CGRectMake(kWidthBean*0, kHeightBean*0, kWidthBean, kHeightBean)];
[img1 setPosition:ccp(kPositionXImg1, kPositionImg1)];
[self addChild:img1 z:kTagLayerBase];
CCSprite *img2 = [CCSprite spriteWithFile:@"img.png" rect:CGRectMake(kWidthBean*1, kHeightBean*0, kWidthBean, kHeightBean)];
[img2 setPosition:ccp(kPositionXImg2, kPositionImg2)];
[self addChild:img2 z:kTagLayerBase];
}
As you can see in loadImages1
, I've basically just made 2 images, and loaded them separately.
I'm curious on your input on this:
- Is this slow or a bad way to load images?
- Is there some sort of sprite cache in cocos2d?
- If this wasn't using ARC, does this ever pose a memory problem?
As you can see in loadImages2
, I tried having a sprite sheet and loading from there.
I'm curious:
- Is this better way to load images than the first?
- Is there a way to load the picture at once and then just pick out segments of it? The code seems to keep reloading the same image.