views:

985

answers:

2

I've defined a sprite using the spriteWithFile method, providing a 120px by 30px .png

Sprite *trampoline = [Sprite spriteWithFile:@"trampoline.png"];  
[self addChild:trampoline];

When I add this to my Layer and position it, it is where I expect it to be on the screen.

trampoline = [Trampoline node];
trampoline.position = ccp(160,15);
[self addChild:trampoline z:0 tag:1];

However, it seems to have no contentSize. The following NSLog statement:

NSLog(@"Content Size x:%f, y:%f", trampoline.contentSize.width,trampoline.contentSize.height);

Gives the following read out:

2009-07-10 18:24:06.385 TouchSprite[3251:20b] Content Size x:0.000000, y:0.000000

Am I missing something? Shouldn't that be 120.000000 by 30.000000

Any help would be greatly appreciated.

Regards,

Rich

A: 

I assume Trampoline inherits from Sprite, which then inherits from Node. You are over-writing trampoline with [Trampoline node] which creates a node ... but is the Trampoline implementation overriding the node method to initialize your sprite file into the Trampoline node?

I think you are just getting an empty Node class back from the line:

trampoline = [Trampoline node];
Greg
Trampoline is a subclass of Sprite. The line trampoline = [Trampoline node] is initialising my object.trampoline is not empty, as it has it's position set, and displays the image on my screen.
Rich
+1  A: 

Are these lines part of the Trampoline class?

Sprite *trampoline = [Sprite spriteWithFile:@"trampoline.png"];
[self addChild:trampoline];

From my limited experience with cocos2d, contentSize of a Sprite seems to only apply to the content that actually belongs to the Sprite, and not all children of that Sprite. As a result, in your example above, asking for the contentSize in your log statement won't work, since there isn't any content added to the Trampoline node. However, if you were to override the contentSize method inside your Trampoline class to return the contentSize of the Sprite that actually loaded the graphic, that should work.

Here's a snippet of a Sprite I'm using in a game I'm currently working on that illustrates what I'm talking about:

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

if (self != nil)
{  
 self.textLabel = [Label labelWithString:@"*TEXT*"
           fontName:@"Helvetica"
           fontSize:18];

 [textLabel setRGB:0 :0 :0];

 textLabel.transformAnchor = CGPointZero;
 textLabel.position = CGPointZero;
 self.transformAnchor = CGPointZero;

 [self addChild:textLabel];
}

return self;
}
//

- (CGSize) contentSize
{
return textLabel.contentSize;
}

This comes from a class that extends Sprite. Until I added the override for contentSize, asking for it from another class would give me the same results your seeing. Now that I'm telling it return the content size of the textLabel, it's working just like I'd expect it to.

joshbuhler