I have a sprite, a square which has a body, also a square. The body isn't lining up with the sprite even though the positions are the same and I'm not overriding setPosition:.
Basically, if the position on screen is x=100,y=100 with a size of the sprite 48x48, the body is lining up at x=124,y=76 with a size of 48x48. So the centre of the body is on the upper right hand corner of the sprite. Code i'm using to create the sprite & body is below:
- (void)createBlock:(Block*)block withAssets:(NSBundle*)assets
{
BlockSprite* sprite;
int x = block.bounds.origin.x;
int y = block.bounds.origin.y;
NSMutableString* c = [[NSMutableString alloc] init];
switch(block.blockColour)
{
case kBlockColourGreen:
[c setString:@"green"];
break;
case kBlockColourOrange:
[c setString:@"orange"];
break;
case kBlockColourRed:
[c setString:@"red"];
break;
case kBlockColourBlue:
[c setString:@"blue"];
break;
}
sprite = [BlockSprite spriteWithFile:[assets pathForResource:c ofType:@"png" inDirectory:@"Blocks"]];
[c release];
sprite.position = ccp(x, y);
sprite.scaleY = 0.75f;
sprite.scaleX = 0.75f;
[self addChild:sprite];
float halfWidth = block.bounds.size.width / 2;
float halfHeight = block.bounds.size.height / 2;
cpVect verts[] = {
cpv(-halfWidth, -halfHeight),
cpv(-halfWidth, halfHeight),
cpv(halfWidth, halfHeight),
cpv(halfWidth, -halfHeight)
};
cpBody* blockBody;
if(block.blockColour == kBlockColourOrange || block.blockColour == kBlockColourBlue || [block.gravitySpeed intValue] == 0)
{
blockBody = cpBodyNew(INFINITY, cpMomentForPoly(INFINITY, 4, verts, cpvzero));
}
else
{
blockBody = cpBodyNew([block.mass floatValue], cpMomentForPoly([block.mass floatValue], 4, verts, cpvzero));
}
blockBody->p = cpv(block.bounds.origin.x, block.bounds.origin.y);
blockBody->v = cpvzero;
if((block.blockColour == kBlockColourGreen || block.blockColour == kBlockColourRed) && [block.gravitySpeed intValue] != 0)
cpSpaceAddBody(space, blockBody);
cpShape* blockShape = cpPolyShapeNew(blockBody, 4, verts, cpvzero);
blockShape->e = 0.9f;
blockShape->u = 0.9f;
blockShape->collision_type = 1;
sprite.scaleX = 1.0f;
sprite.scaleY = 1.0f;
blockShape->data = sprite;
if(block.blockColour == kBlockColourOrange || block.blockColour == kBlockColourBlue || [block.gravitySpeed intValue] == 0)
{
blockBody->v = cpvzero;
// Static object's victory is always YES.
sprite.victory = YES;
cpSpaceAddStaticShape(space, blockShape);
}
else
cpSpaceAddShape(space, blockShape);
sprite.scaleX = 0.75f;
sprite.scaleY = 0.75f;
sprite.space = space;
sprite.shape = blockShape;
[blockSprites addObject:sprite];
}