I've been having a hard time figuring out how the whole box2d pixels to meter thing works. I've read a bunch of things on google trying to understand the logic behind this, but I just can't grasp it :P here is the code right now.
SpriteBatch batch;
Texture img;
Sprite player;
Body playerBody;
OrthographicCamera camera;
int FRUSTUM_WIDTH = 500; // 5 blocks 100 pixels wide
int FRUSTUM_HEIGHT = 900;
int PIXELS_TO_METERS = 100;
World world;
Box2DDebugRenderer debugRenderer;
@Override
public void create () {
batch = new SpriteBatch();
img = new Texture("player.png");
player = new Sprite(img);
player.setPosition(220 * PIXELS_TO_METERS, 300 * PIXELS_TO_METERS);
player.setOrigin(img.getWidth() / 2, img.getHeight() / 2);
camera = new OrthographicCamera(FRUSTUM_WIDTH, FRUSTUM_HEIGHT);
camera.position.set(FRUSTUM_WIDTH / 2, FRUSTUM_HEIGHT / 2, 0);
world = new World(new Vector2(0, -98), true);
debugRenderer = new Box2DDebugRenderer();
setUpBox2D();
}
private void setUpBox2D()
{
BodyDef bodyDef1 = new BodyDef();
bodyDef1.type = BodyDef.BodyType.DynamicBody;
bodyDef1.position.set((player.getX() + player.getWidth() / 2) / PIXELS_TO_METERS, (player.getY() + player.getHeight() / 2) / PIXELS_TO_METERS);
playerBody = world.createBody(bodyDef1);
PolygonShape square = new PolygonShape();
square.setAsBox(player.getWidth() / 2, player.getHeight() / 2);
FixtureDef fixtureDef1 = new FixtureDef();
fixtureDef1.shape = square;
fixtureDef1.density = 0.1f;
fixtureDef1.friction = 1f;
fixtureDef1.restitution = 0f;
Fixture fixture1 = playerBody.createFixture(fixtureDef1);
BodyDef groundBodyDef = new BodyDef();
groundBodyDef.type = BodyDef.BodyType.KinematicBody;
groundBodyDef.position.set(new Vector2(0, 100));
Body groundBody = world.createBody(groundBodyDef);
PolygonShape groundBox = new PolygonShape();
groundBox.setAsBox(camera.viewportWidth, 1.0f);
groundBody.createFixture(groundBox, 0);
}
@Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
drawScene();
updateScene();
}
private void drawScene()
{
debugRenderer.render(world, camera.combined);
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
player.draw(batch);
batch.end();
world.step(1/60f, 6, 2);
}
private void updateScene()
{
if(Gdx.input.isKeyPressed(Input.Keys.LEFT))
{
playerBody.setLinearVelocity(-100, 0);
}
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT))
{
playerBody.setLinearVelocity(100, 0);
}
player.setPosition(playerBody.getPosition().x, playerBody.getPosition().y);
}
Before I go any further with the program, I am wondering if I am doing this the right way?