ArtS
ArtS

Reputation: 43

How to get the size of a CCSprite before it's initialized?

I'm writing a simple game using cocos2d with objective-c. In this game I give random positions to the enemy sprites. To avoid overlapping of different enemies, I write a check to make sure that the new sprite's CGRect with its random position is not overlapped with any other sprites' CGRect.

My questions is how can you get the size of the CGRect before you initialize the new sprite? And how do you do this if you use ccbi file(cocosbuilder) to initialize the sprite?

What I did before is that before initializing the new sprite, I initialize a temporary sprite with the png file, which shows the first frame of the enemy(every frame has the same size). Then just use it's size like this: tempSprite.boundingBox. Though it works well, I think this is not efficient to make a tempSprite before initializing every new enemy sprites.

Now I'm trying to convert my game using cocosbuilder(because using ccbi file makes it easier to adjust animation). How can I know the size of the sprite before initializing? I think I can still make a tempSprite using [CCBReader nodeGraphFromFile:@"enemySprite.ccbi"], and using tempSprite.boundingBox to get its size. But is it the right way to do it? It felts very wasteful for CPU and memory resources. update: I tried my way which doesn't work. Because the boundingBox size value is (0,0) (position value is right).

Upvotes: 0

Views: 206

Answers (1)

ArtS
ArtS

Reputation: 2012

I found solution by myself. The problem is caused because I misunderstood the structure of the instance created by the ccbi file. It is a CCNode with a CCSprite as it's variable, instead of simply a CCSprite. The CCNode has size of (0,0) (it works as a container for the CCSprite), and the CCSprite has the right size and the right position.

I assigned the CCSprite with a CCSprite* variable in CocosBuilder. And use the CCSprite.boundingBox to check for collision. This solves all the problems.

Upvotes: 0

Related Questions