Hey All.
Weird problem. I have a sprite that is a sub class of AtlasSprite. It has a cpBody - and I have over-ridden the setPosition method. For some reason when I use the drawObject method to test the cpBody - the body is quite some distance away from the sprite! A consistant distance that seems to move with the sprite around the sprites anchor points. Some code to follow - any ideas what is going on?
I am only using chipmunk to do collision detection - and it looks okay, except the body is way off!
Justin
mysprite.h
@interface mysprite : AtlasSprite
{
cpBody *spriteBody;
mysprite.m
-(id) initWithCPBody: (cpBody *) bodyIn{
self = [super init];
if(self != nil){
spriteBody = bodyIn;
}
return self;
}
-(void) setPosition:(cpVect)pos
{
[super setPosition:pos];
// Sync Chipmunk with sprite
spriteBody->body->p = pos;
}
MotionLayer.m
// C function to update the location for each shape
static void eachShape(void *ptr, void* unused)
{
cpShape *shape = (cpShape*) ptr;
Sprite *sprite = shape->data;
if( sprite ) {
cpBody *body = shape->body;
[sprite setPosition: cpv( body->p.x, body->p.y)];
[sprite setRotation: (float) CC_RADIANS_TO_DEGREES( -body->a )];
}
}
//Create a sprite
- (id) init
{
self = [super init];
if (self != nil) {
mysprite *testSprite = [[mysprite alloc] initWithCPBody:[self makeSpriteX:-50 y:-50]];
[self addChild:testSprite];
[testSprite setPosition:cpv(416,320-54)];
[testSprite setRotation:270];
id action1 = [MoveBy actionWithDuration:2 position:ccp(-38,0)];
id action = [Sequence actions: action1,
action1,
action1,
action1,
action1,
nil];
[testSprite runAction: action];
}
-(cpBody *) makeSpriteX: (float) x y:(float) y
{
AtlasSpriteManager *mgr = (AtlasSpriteManager*) [self getChildByTag:kTagSpriteManager];
AtlasSprite *spriteTest = [AtlasSprite spriteWithRect:CGRectMake(0,0,30,60) spriteManager:mgr];
[mgr addChild:spriteTest];
spriteTest.position = ccp( x, y);
spriteTest.anchorPoint = ccp(0.5f, 0.75f);
cpVect verts1[] = {
cpv(-15,-30),
cpv(-15, 30),
cpv(15, 30),
cpv(15,-30),
};
cpBody *spriteBod = cpBodyNew(100.0f, INFINITY);
spriteBod->p = cpv(x, y);
spriteBod->v = cpv(0, 0);
//cpSpaceAddBody(space, spriteBod);
cpShape * spriteShape;
spriteShape = cpPolyShapeNew(spriteBod, 4, verts1, cpv(x, y));
spriteShape->e = 0.9f; spriteShape->u = 0.9f;
spriteShape->data = spriteTest;
spriteShape->collision_type = 1; //this is new!
cpSpaceAddShape(space, spriteShape);
return spriteShape;
}