jjpp
jjpp

Reputation: 1328

Circular body positioning not working in box2d(cocos2dx)

I'm developing a cocos2dX game. I use box2d for physics simulation. I'm trying to add a circular body and a rectangular body. Here is my code

// Create circular sprite and body
CCSprite* ball_sprite = CCSprite::create("ball.png");
this->addChild(ball_sprite);

b2BodyDef ballBodyDef;
ballBodyDef.type = b2_dynamicBody;
ballBodyDef.position.Set(screenSize.width/PTM_RATIO, screenSize.height/2/PTM_RATIO);//im running it in an iphone retina and screensize is 640x960
ballBodyDef.userData = ball_sprite;
ball_body = _world->CreateBody(&ballBodyDef);

b2CircleShape ballshape;
ballshape.m_radius = BALL_SIZE/2;

b2FixtureDef ballShapeDef;
ballShapeDef.shape = &ballshape;
ballShapeDef.density = 100.0f;
ballShapeDef.friction = 0.5f;
ballShapeDef.restitution = 0.7f;
ball_body->CreateFixture(&ballShapeDef);

// Create rectangular sprite and body
CCSprite* block_sprite = CCSprite::create("HelloWorld.png");
this->addChild(block_sprite);

b2BodyDef blockBodyDef;
blockBodyDef.type = b2_staticBody;
blockBodyDef.position.Set(0, screenSize.height/2/PTM_RATIO);
blockBodyDef.userData = block_sprite;
block_bodie = _world->CreateBody(&blockBodyDef);

b2PolygonShape blockshape;
blockshape.SetAsBox(B_WIDTH/PTM_RATIO,B_HEIGHT/PTM_RATIO);
b2FixtureDef blockShapeDef;
blockShapeDef.shape = &blockshape;
blockShapeDef.density = 100.0f;
blockShapeDef.friction = 0.5f;
blockShapeDef.restitution = 0.7f;
block_bodie->CreateFixture(&blockShapeDef);

The rectangular body is shown in the screen as expected.

But the circular body is not shown in the screen.

When I printed the position of circular body in the update function, the positions are large numbers around 2000. And this position is different each time I run the programm.

If the rectangular body is not added(commenting the line block_bodie->CreateFixture(&blockShapeDef);) then the circular body is shown in the screen as I expected.

What I'm doing wrong here?

Thanks in advance.

Upvotes: 0

Views: 190

Answers (1)

iforce2d
iforce2d

Reputation: 8272

Are these two bodies overlapping when they are created? Most likely the circle is simply being pushed away by the rectangle, because the rectangle is static and the circle is dynamic. If you try creating both of them, but don't call the world Step function to run the physics simulation, you will probably see them both on screen.

You could create them so that they are not overlapping, or at least not overlapping as much, or make one of them a sensor, or set their collision category and mask bits so they don't interact.

Of course, I am assuming you are looking at the debug draw display, which is really the only way to know for sure what the physics engine is doing.

Upvotes: 1

Related Questions