我正在开发一款cocos2dX游戏。我使用box2d进行物理模拟。我正在尝试添加圆形体和矩形体。这是我的代码
// 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);
矩形体在屏幕上按预期显示。
但是圆形体未显示在屏幕上。
当我在更新功能中打印圆形体的位置时,位置在2000左右是大数字。每次运行程序时这个位置都不同。
如果没有添加矩形体(注释行block_bodie-> CreateFixture(& blockShapeDef);)那么圆形体将按照我的预期显示在屏幕上。
我在这里做错了什么?
提前致谢。
答案 0 :(得分:1)
这两个实体在创建时是否重叠?很可能圆圈被矩形推开,因为矩形是静态的,圆是动态的。如果您尝试创建它们,但不要调用世界Step函数来运行物理模拟,您可能会在屏幕上看到它们。
你可以创建它们,使它们不重叠,或者至少不重叠,或者将它们中的一个作为传感器,或者设置它们的碰撞类别和掩码位,使它们不相互作用。
当然,我假设您正在查看调试绘制显示,这实际上是确定物理引擎正在做什么的唯一方法。