FooTest(){//a static bodyb2BodyDefmyBodyDef;myBodyDef.type=b2_staticBody;myBodyDef.position.Set(0,0);b2Body*staticBody=m_world->CreateBody(&myBodyDef);//shape definitionb2PolygonShapepolygonShape;//fixture definitionb2FixtureDefmyFixtureDef;myFixtureDef.shape=&polygonShape;//add four walls to the static bodypolygonShape.SetAsBox(20,1,b2Vec2(0,0),0);//groundstaticBody->CreateFixture(&myFixtureDef);polygonShape.SetAsBox(20,1,b2Vec2(0,40),0);//ceilingstaticBody->CreateFixture(&myFixtureDef);polygonShape.SetAsBox(1,20,b2Vec2(-20,20),0);//left wallstaticBody->CreateFixture(&myFixtureDef);polygonShape.SetAsBox(1,20,b2Vec2(20,20),0);//right wallstaticBody->CreateFixture(&myFixtureDef);}
让我们调用我们的游戏实体类Ball并然其滚动和弹跳:
12345678910111213141516
//outside and before the FooTest classclassBall{public://class member variablesb2Body*m_body;floatm_radius;public:Ball(b2World*world,floatradius){m_body=NULL;m_radius=radius;}~Ball(){}};//FooTest class member variablestd::vector<Ball*>balls;
//Ball::rendervoidrender(){glColor3f(1,1,1);//white//nose and eyesglPointSize(4);glBegin(GL_POINTS);glVertex2f(0,0);glVertex2f(-0.5,0.5);glVertex2f(0.5,0.5);glEnd();//mouthglBegin(GL_LINES);glVertex2f(-0.5,-0.5);glVertex2f(-0.16,-0.6);glVertex2f(0.16,-0.6);glVertex2f(0.5,-0.5);glEnd();//circle outlineglBegin(GL_LINE_LOOP);for(floata=0;a<360*DEGTORAD;a+=30*DEGTORAD)glVertex2f(sinf(a),cosf(a));glEnd();}
// Ball class constructorBall(b2World*world,floatradius){m_body=NULL;m_radius=radius;//set up dynamic body, store in class variableb2BodyDefmyBodyDef;myBodyDef.type=b2_dynamicBody;myBodyDef.position.Set(0,20);m_body=world->CreateBody(&myBodyDef);//add circle fixtureb2CircleShapecircleShape;circleShape.m_p.Set(0,0);circleShape.m_radius=m_radius;//use class variableb2FixtureDefmyFixtureDef;myFixtureDef.shape=&circleShape;myFixtureDef.density=1;m_body->CreateFixture(&myFixtureDef);}
//in Ball classvoidrenderAtBodyPosition(){//get current position from Box2Db2Vec2pos=m_body->GetPosition();floatangle=m_body->GetAngle();//call normal render at different position/rotationglPushMatrix();glTranslatef(pos.x,pos.y,0);glRotatef(angle*RADTODEG,0,0,1);//OpenGL uses degrees hererender();//normal render at (0,0)glPopMatrix();}
//inside Ball::renderAtBodyPositionglPushMatrix();glTranslatef(pos.x,pos.y,0);glRotatef(angle*RADTODEG,0,0,1);glScalef(m_radius,m_radius,1);//add this to correct sizerender();glPopMatrix();
声明:本教程翻译自:Box 2D C++ turorials - Drawing your own objects,仅供学习参考。画自己的图像从之前的话题中可以看出,很显然使用debug draw不能做出视觉上具有吸引力的游戏。通常我们都会使用我们自己的方法在场景中画图像,然后访问Box2d获取物体的物理信息以此知道在哪里画图像。在本次话题中,我们将会专门定义一个类用作渲染