I am using the libgdx framework to create a game. I'm trying create onscreen buttons/controls.
Currently, I have a
class LevelOne that implements Screen.
This class has a private variable world (From Box2d)
I want to add a Table with Textbuttons or a Libgdx Touchpad to the Box2d world. However, I'm not sure how to do this.
Next, I know I can add a table or a touchpad to a Libgdx Stage. Is there anyway to get the Libgdx stage and Box2d world to work together so, I can add a Touchpad or Table to the Box2d world.
For onscreen controls, you can do it like this:
Make a new cam which will be fixed for the controls:
OrthographicCamera guicam = new OrthographicCamera(480, 320);
guicam.position.set(480/2F, 320/2F, 0);
Make a (libgdx) Rectangle for each control:
Rectangle wleftBounds = new Rectangle(0, 0, 80, 80);
Rectangle wrightBounds = new Rectangle(80, 0, 80, 80);
Create a new Vector3 to hold your unprojected touch coordinates:
Vector3 touchPoint = new Vector3();
Then you can poll the Input to see if the user is touching these rectangles:
//in render method
for (int i=0; i<5; i++){
if (!Gdx.input.isTouched(i)) continue;
guicam.unproject(touchPoint.set(Gdx.input.getX(i), Gdx.input.getY(i), 0));
if (wleftBounds.contains(touchPoint.x, touchPoint.y)){
//Move your player to the left!
}else if (wrightBounds.contains(touchPoint.x, touchPoint.y)){
//Move your player to the right!
}
}
Notice I'm checking the first 5 touch indexes, thats because you will surely want to have controls that are being used at the same time (i.e. Jumping while Moving Right).
Last but not least, you will want to draw some nice graphics over the controls:
batch.draw(leftRegion, wleftBounds.x, wleftBounds.y, wleftBounds.width, wleftBounds.height);
batch.draw(rightRegion, wrightBounds.x, wrightBounds.y, wrightBounds.width, wrightBounds.height);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With