LibGdx--Box2d单位换算

在手机上用的单位是像素px,而在Box2d中用的是米m,Box2d用于模拟真实世界,

而真实世界是用米为单位来丈量的,所以为了更好地模拟真实世界,所以Box2d以

米为单位(这是我自己的理解)

 

为了更好地观察Box2d世界里的物体,我们需要一个Box2DDebugRenderer(渲染器)

和一个OrthographicCamera(照相机),这里的OrthographicCamera用的单位也是米,

为什么是米?可以把OrthographicCamera当成是我们的眼睛,眼睛看到的是以米为单位

来衡量的

 

package com.joye3g.change;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;

public class ChangeDemo implements ApplicationListener {
	private static final float PXTM = 30;//每30个像素就是1米
	private OrthographicCamera camera;
	private Box2DDebugRenderer renderer;
	private World world;
	private Body body;
	
	@Override
	public void create() {		
		//取得窗口宽高
		float w = Gdx.graphics.getWidth();
		float h = Gdx.graphics.getHeight();
		//camera宽高
		float cameraWidth = w / PXTM;
		float cameraHeight = h / PXTM;
		camera = new OrthographicCamera(cameraWidth, cameraHeight);
		renderer = new Box2DDebugRenderer();//渲染器
		world = new World(new Vector2(0f, 0f), true);//实例化一个世界
		BodyDef def = new BodyDef();
		def.type = BodyType.StaticBody;
		def.position.set(0f, 0f);//设置刚体的位置
		body = world.createBody(def);
		PolygonShape shape = new PolygonShape();
		shape.setAsBox(1f, 1f);//凡是与物理世界相关的都是以米为单位
		FixtureDef def2 = new FixtureDef();
		def2.shape = shape;
		body.createFixture(def2);
	}

	@Override
	public void dispose() {
	}

	@Override
	public void render() {		
		Gdx.gl.glClearColor(1, 1, 1, 1);
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		renderer.render(world, camera.combined);
	}

	@Override
	public void resize(int width, int height) {
	}

	@Override
	public void pause() {
	}

	@Override
	public void resume() {
	}
}


 

运行界面如下:

代码中设置刚体的位置为0,0   ,从运行界面可以看出,物理世界的原点是窗口的中心点

你可能感兴趣的:(libgdx,游戏引擎,box2D,单位换算)