您的位置:首页 > 其它

从零开始box2d(1) 创建世界

2016-09-02 14:11 176 查看
给自己的备忘录

1, 首先需要下载jbox2d 依赖包 导入我们的工程.

2, 介绍box2d的 基本概念

主要用到的类

World : 顾名思义 就是整个世界 沙盒 所有游戏内的操作都在world里面运行

AABB : 包围盒 主要用于设置界面的大小

Vec2 : 二维向量

直接上代码 看看怎么用

这是个surfaceView

public class MySurfaceView extends SurfaceView implements Callback, Runnable {
private Thread th;
private SurfaceHolder sfh;
private Canvas canvas;
private Paint paint;
private boolean flag;

// ----添加一个物理世界---->>
final float RATE = 30;// 屏幕到现实世界的比例 30px:1m;
World world;// 声明一个物理世界对象
AABB aabb;// 声明一个物理世界的范围对象
Vec2 gravity;// 声明一个重力向量对象
float timeStep = 1f / 60f;// 物理世界模拟的的频率
// ----添加一个物理世界---->>

public MySurfaceView(Context context) {
super(context);
this.setKeepScreenOn(true);
sfh = this.getHolder();
sfh.addCallback(this);
paint = new Paint();
paint.setAntiAlias(true);

// --添加一个物理世界--->>
aabb = new AABB();// 实例化物理世界的范围对象
gravity = new Vec2(0, 10);// 实例化物理世界重力向量对象
aabb.lowerBound.set(-100, -100);// 设置物理世界范围的左上角坐标
aabb.upperBound.set(100, 100);// 设置物理世界范围的右下角坐标
world = new World(aabb, gravity, true);// 实例化物理世界对象
}

public void surfaceCreated(SurfaceHolder holder) {
flag = true;
th = new Thread(this);
th.start();
}

public void myDraw() {
try {
canvas = sfh.lockCanvas();
if (canvas != null) {
canvas.drawColor(Color.WHITE);
}
} catch (Exception e) {
Log.e("Himi", "myDraw is Error!");
} finally {
if (canvas != null)
sfh.unlockCanvasAndPost(canvas);
}
}

public void Logic() {
// --开始模拟物理世界--->>
world.step(timeStep, iterations);// 物理世界进行模拟
}

public void run() {
while (flag) {
myDraw();
Logic();
try {
Thread.sleep((long) timeStep * 1000);
} catch (Exception ex) {
Log.e("tag", "Thread is Error!");
}
}
}

public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}

public void surfaceDestroyed(SurfaceHolder holder) {
flag = false;
}

}


这个只是把物理世界创建出来 界面上是什么东西都没有的 这个demo只是告诉我 怎么使用这个world 和aabb

声明:

1.
final float RATE = 30;// 屏幕到现实世界的比例 30px:1m;
屏幕到现实世界的比例

2.
World world;// 声明一个物理世界对象

3. AABB aabb;// 声明一个物理世界的范围对象

4. Vec2 gravity;// 声明一个重力向量对象

5. float timeStep = 1f / 60f;// 物理世界模拟的的频率


然后创建

aabb = new AABB();// 实例化物理世界的范围对象
gravity = new Vec2(0, 10);// 实例化物理世界重力向量对象
aabb.lowerBound.set(-100, -100);// 设置物理世界范围的左上角坐标
aabb.upperBound.set(100, 100);// 设置物理世界范围的右下角坐标
world = new World(aabb, gravity, true);// 实例化物理世界对象


开始模拟世界 相当于刷新把

// --开始模拟物理世界--->>
world.step(timeStep, iterations);// 物理世界进行模拟


================以上是世界的创建============================
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  box2d 游戏