如何使用vs来运行box2d中Testbed的案例
0 环境
vs: vs2012
box2d: Box2D_v2.1.2
1 得到box2d编译版本
可以参考:
https://blog.csdn.net/sty945/article/details/83823976
现在我们得到一个可以用vs2012打开的box2d版本,用vs2012打开如下图所示:
2 运行Testbed的项目
将testbed项目设置成启动项目,然后F7编译, Ctrl+F5运行就可以得到如下界面:
我们可以做一些演示练习
3 基于Testbed项目编写程序
推荐一个box2d教程:
http://ohcoder.com/blog/categories/box2d-tutorials/
我们如何编写自己的程序呢?
在vs2012中直接添加文件是不对的,添加文件只会添加到build目录下,必须要和原始文件在同一目录下才可以,以下是我采用的方法:
3.1 采用vscode打开源代码
路径是…\Box2D_v2.1.2\Box2D文件夹,会得到如下的界面:
3.2 打开testbed文件夹
3.3 创建测试
Testbed/Tests文件夹下面,添加自己创建的.h头文件,如创建一个FooTest.h,写入如下内容:
#ifndef FOO_TEST_H
#define FOO_TEST_H
#define DEGTORAD 0.0174532925199432957f
#define RADTODEG 57.295779513082320876f
class FooTest: public Test
{
public:
b2Body* dynamicBody;
FooTest()
{
b2BodyDef myBodyDef;
myBodyDef.type = b2_dynamicBody;
//start 10 units further to the right, 20 units higher
myBodyDef.position.Set(0, 20);
myBodyDef.angle = 0;
// b2Body* dynamicBody = m_world->CreateBody(&myBodyDef);
dynamicBody = m_world->CreateBody(&myBodyDef);
b2PolygonShape boxShape;
boxShape.SetAsBox(2, 1);
b2FixtureDef boxFixtureDef;
boxFixtureDef.shape = &boxShape;
boxFixtureDef.density = 1;
dynamicBody->CreateFixture(&boxFixtureDef);
//change the starting position and angle
dynamicBody->SetTransform(b2Vec2(10, 20), 1);
// set the linear velocity and angular velocity of the body
dynamicBody->SetLinearVelocity(b2Vec2(-5, 5));
dynamicBody->SetAngularVelocity(-90 * DEGTORAD);
//static Bodies
myBodyDef.type = b2_staticBody;
myBodyDef.position.Set(0, 10);
b2Body* staticBody = m_world->CreateBody(&myBodyDef);
staticBody->CreateFixture(&boxFixtureDef);
//kinematic body
myBodyDef.type = b2_kinematicBody;
myBodyDef.position.Set(-18, 11);
b2Body* kinematicBody = m_world->CreateBody(&myBodyDef);
kinematicBody->CreateFixture(&boxFixtureDef);
kinematicBody->SetLinearVelocity(b2Vec2(1, 0));
kinematicBody->SetAngularVelocity(360 * DEGTORAD);
};
void Step(Settings* setttings)
{
Test::Step(setttings);
m_debugDraw.DrawString(5, m_textLine, "now we have a foo test");
m_textLine += 15;
b2Vec2 pos = dynamicBody->GetPosition();
float angle = dynamicBody->GetAngle();
b2Vec2 vel = dynamicBody->GetLinearVelocity();
float angularvel = dynamicBody->GetAngularVelocity();
m_debugDraw.DrawString(5, m_textLine, "Position:%.3f,%.3f Angle:%.3f", pos.x, pos.y, angle*RADTODEG);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "Veloctiy:%.3f, %.3f Angular velocity:%.3f", vel.x, vel.y, angularvel * RADTODEG);
m_textLine += 15;
for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext())
{
b2Vec2 pos1 = b->GetPosition();
m_debugDraw.DrawString(5, m_textLine, "Position:%.3f,%.3f", pos1.x, pos1.y);
m_textLine += 15;
}
}
static Test* Create()
{
return new FooTest;
}
};
#endif
然后在同一目录下的TestEntries.cpp文件添加如下两行代码:
#include "FooTest.h"
{"Foo test", FooTest::Create},
3.4 运行测试
在vs2012中编译运行,会出现如下界面:
第一个演示的就是我们刚才编写的程序。
基于此就可以根据教程:
http://ohcoder.com/blog/categories/box2d-tutorials/
基于学习Box2D了
还没有评论,来说两句吧...