I am trying to implement a mechanic you can visualize as a top-down flashlight.
I am using LibGDX and Box2D. I have never done anything using Box2D before, so the PPM scaling and the integration with Sprites, etc, really confuses me. I have made a small game with LibGDX before, you can find it here.
Problems:
- I feel like I am scaling the camera with PPM (pixels per meter) incorrectly
- The light does not turn correctly
- Do not know how to tween between positions
To do this, in the show() method, I have attached a ConeLight to a Box2D body using the following method:
PolygonShape shape = new PolygonShape();
shape.setAsBox(5 / PPM, 5 / PPM);
BodyDef bdef = new BodyDef();
bdef.position.set(160 / PPM, 200 / PPM);
bdef.type = BodyType.DynamicBody;
body = world.createBody(bdef);
FixtureDef fdef = new FixtureDef();
fdef.shape = shape;
body.createFixture(fdef);
rayHandler = new RayHandler(world);
cone = new ConeLigh
(rayHandler, 40, Color.WHITE, 30, 160 / PPM, 200 / PPM, -90, 40);
Then, again in the show() method, I set up the camera:
b2dcam = new OrthographicCamera();
b2dcam.setToOrtho(false, Gdx.graphics.getWidth() / PPM, Gdx.graphics.getHeight() / PPM);
I am rendering it like this in the render() method:
Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
world.step(1f/60f, 6, 2);
b2dr.render(world, b2dcam.combined);
rayHandler.setCombinedMatrix(b2dcam.combined);
rayHandler.updateAndRender();
I am handling the input in this fashion:
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
if(button == Buttons.LEFT){
body.setTransform(body.getPosition(), (float) (Math.atan2( (body.getPosition().y - screenY),
(screenX - body.getPosition().x) ) ));
}
return false;
}
The light rotates on mouse click, which means the listener is working, but it does not rotate to the correct point. I assume it has something to do with my math being incorrect, and the scaling done from meters to pixels being wrong.
Can someone help me on both of these issues? The intended behavior is illustrated below:
When the mouse is clicked, the body, and by association the ConeLight, should move to face the direction of the mouse click.
My full code can be viewed here: https://gist.githubusercontent.com/Elsealabs/1afaa812aafb56ecd3c2/raw/5d0959df795516c89fb7e6ab81aecc01dc8cd441/gistfile1.txt
[2]: http://i.stack.imgur.com/S6e5u.png