I have a class allc/init in the layer of a cocos2d game with this code:
flowerBody = [[[CPFlower alloc] initWithLocation:ccp(winSize.width*.25,winSize.height*5.05) space:space groundBody:groundBody] autorelease];
The class is called CPFlower. Its methods are:
-(void)updateStateWithDeltaTime:(ccTime)dt andListOfGameObjects:(CCArray*)listOfGameObjects {
//this is for when ole is in the air
[super updateStateWithDeltaTime:dt andListOfGameObjects:listOfGameObjects];
//prevent sprite from flying off the sides when in the air
float margin = 70;
CGSize winSize = [CCDirector sharedDirector].winSize;
if (body->p.x < margin) {
cpBodySetPos(body, ccp(margin, body->p.y));
}
if (body->p.x > winSize.width - margin) {
cpBodySetPos(body, ccp(winSize.width - margin, body->p.y));
}
}
- (id)initWithLocation:(CGPoint)location space:(cpSpace *)theSpace groundBody:(cpBody *)groundBody {
if ((self = [super initWithSpriteFrameName:@"flor.png"])) {
CGSize size;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
size = CGSizeMake(60, 60);
self.anchorPoint = ccp(0.5, 30/self.contentSize.height);
} else {
size = CGSizeMake(30, 30);
self.anchorPoint = ccp(0.5, 15/self.contentSize.height);
}
[self addBoxBodyAndShapeWithLocation:location size:size space:theSpace mass:1.0 e:0.0 u:0.5
collisionType:kCollisionTypeFlower canRotate:TRUE];
}
//call animations
[self initAnimations];
return self;
}
And its based off of CPSprite which has the method:
- (void)addBoxBodyAndShapeWithLocation:(CGPoint)location
size:(CGSize)size
space:(cpSpace *)theSpace
mass:(cpFloat)mass
e:(cpFloat)e
u:(cpFloat)u
collisionType:(cpCollisionType)collisionType
canRotate:(BOOL)canRotate {
space = theSpace;
float moment = INFINITY;
if (canRotate) {
moment = cpMomentForBox(mass, size.width, size.height);
}
body = cpBodyNew(mass, moment);
body->p = location;
cpSpaceAddBody(space, body);
shape = cpBoxShapeNew(body, size.width, size.height);
shape->e = e;
shape->u = u;
shape->collision_type = collisionType;
shape->data = self;
cpSpaceAddShape(space, shape);
}
It wasnt showing up and I noticed it wont show up unless I add this code block:
//prevent sprite from flying off the sides when in the air
float margin = 70;
CGSize winSize = [CCDirector sharedDirector].winSize;
if (body->p.x < margin) {
cpBodySetPos(body, ccp(margin, body->p.y));
}
if (body->p.x > winSize.width - margin) {
cpBodySetPos(body, ccp(winSize.width - margin, body->p.y));
}
So i guess in essence, unless I position the cpbody, the sprite doesnt show up.
In box2d I just have to add the sprite and the box2d body is added. Is this because box2d loops thru sprites and updates body properties and cp does it backwards?