---
title: "Box2D的编译与运行 － 自己的代码"
author: "mmdev"
date: "2013-02-07T11:54:00Z"
tags: []
slug: "box2d"
draft: false
lastmod: "2013-02-22T15:26:36Z"
id: 1812488
url: "https://mmdev.iteye.com/blog/1812488"
---

转发，请保持地址：[http://blog.csdn.net/stalendp/article/details/8575379](http://blog.csdn.net/stalendp/article/details/8575379)

这篇文章记录了《Box2D的编译与运行 － Rich Test》基础上的小试验（根据为：[Box2D C++ tutorials - Making a test](http://www.iforce2d.net/b2dtut/making-a-test)）。更多学习和试验，强烈推荐如下站点：[http://www.iforce2d.net/b2dtut/](http://www.iforce2d.net/b2dtut/)；（阅读英文不方便的朋友，也不用担心，国内已经有自愿者对其进行过翻译了，效果还不错；链接如下：[http://ohcoder.com/blog/categories/box2d-tutorials/](http://ohcoder.com/blog/categories/box2d-tutorials/)）

Box2D压缩目录的Testbed工程的目录结构如下：

![](http://img.my.csdn.net/uploads/201302/07/1360208633_1476.png)

编写测试代码可以放在Tests目录下。这个目录下，只有TestEntries.cpp是必须的（为了翻遍测试自己的代码，以及加快编译速度，可以把其他文件删除）。我工程的目录如下：

![](http://img.my.csdn.net/uploads/201302/07/1360208783_3042.png)

项目中我按照[iforce2d上的教程](http://www.iforce2d.net/b2dtut/)，写了两个例子：BodiesTest.h 和 FixturesTest.h；注册例子有需要2步，如下：

1）在xxxTest.h的Create方法中生成该文件中的对象（简单工程模式），BodiesTest.h中的代码：

```
class BodiesTest: public Test {
public:
	BodiesTest() {
		//.…..
	}
	//.….
	static Test* Create() {
		return new BodiesTest;
	}
};
```

2\) 在TestEntries.cpp中注册该测试类：

```
#include "../MyTests/BodiesTest.h"
#include "../MyTests/FixturesTest.h"

TestEntry g_testEntries[] = {
    {"Fixturesss test", FixturesTest::Create },
    {"Bodies test", BodiesTest::Create },
    { NULL, NULL }
};
```

这样就可以编译运行了，效果如下：

![](http://img.my.csdn.net/uploads/201302/07/1360209400_4552.png)

（另外要提一点的是，这个GUI在选择测试的时候，下拉框没有出现（在我的系统上是这样的），可以先选择下拉框，然后用键盘的上下键选择测试。）

Good luck!

相关文章：

《[Box2D的编译与运行 － Rich Test](http://blog.csdn.net/stalendp/article/details/8575231)》

《 [Box2D的编译与运行 － Hello world](http://blog.csdn.net/stalendp/article/details/8574894)》