Reputation: 3575
I want to add an image to a CCSprite and then use that inside my Box2d world. The createBoxAtLocation
picks up the contentSize
correctly but never displays the image...what am I doing wrong? Do I need to add anything to the update() function?
CCSprite *sprite = [CCSprite spriteWithFile:@"slider_piece.png"];
[self createBoxAtLocation:loc1 withSize:boxSize forSprite:sprite];
-(void) createBoxAtLocation:(CGPoint)location withSize:(CGSize)size forSprite:(CCSprite *)_sprite
{
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
bodyDef.allowSleep = false;
//bodyDef.userData = _sprite;
b2Body *body = world->CreateBody(&bodyDef);
body->SetUserData(_sprite);
b2FixtureDef fixtureDef;
b2PolygonShape shape;
shape.SetAsBox(_sprite.contentSize.width/2/PTM_RATIO, _sprite.contentSize.height/2/PTM_RATIO);
fixtureDef.shape = &shape;
body->CreateFixture(&fixtureDef);
}
EDIT
Inside the update function I have this, but it causes a EXC_BAD_ACCESS error on sprite.position line
for(b2Body *b = world->GetBodyList(); b != NULL; b = b->GetNext())
{
if (b->GetUserData() != NULL) {
CCSprite *sprite = (CCSprite *) b->GetUserData();
sprite.position = ccp(b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);
sprite.rotation = CC_RADIANS_TO_DEGREES(b->GetAngle() * -1);
}
}
Upvotes: 3
Views: 701
Reputation: 13999
The sprite is not addChild'ed to any CCNode(CCLayer or CCScene or so forth)?
If so,
CCSprite *sprite = [CCSprite spriteWithFile:@"slider_piece.png"];
the sprite might be released in update() because the sprite is autoreleased object.
You have to retain the sprite in this case at CreateBody,
body->SetUserData([_sprite retain]);
And then release it at DestroyBody.
[(CCSprite *)body->GetUserData() release];
BTW, I recommend you to use CCBox2D.
EDITED:
Did you addChild the sprite to your CCScene or child nodes?
[self addChild:sprite];
Or the body's position (loc1) is in the screen range?
Upvotes: 2