Box2D can't understand the way it works - libgdx - libgdx

I'm trying to play around with Box2D in libgdx but unfortunately I can't seem to understand the way it works.
Here are a few examples that drive me crazy:
.1. It is known that Box2D works with meters. Everybody knows that. Then, why I getting results by Pixels? For instance, if I define some body definition and I set the position to 0,1, It draws the related fixture/sprite at the bottom-left corner of the screen! I thought the 0,0 point in Box2D is at the center of the screen.
.2. Another problem that I have been struggling to understand and solve is the values of the Shapes, Joints and other stuff. Let's start with the shapes: I defined a Polygon shape like this:
shape.setAsBox(1, 2);
Now the shape was supposed to be 2 meters wide and 4 meters height, but it's not the case. What I got is a super small shape.
And lastly, the values of the joints. I defined a body with a polygon shape and a ground body. Now I "pinned" those two to the center of the ground body using the Revolute Joint, with the goal to create some sort of a catapult that rotates nicely within a certain range.
Now I defined also a Mouse Joint so I could drag the catapult(the polygon shape) back and forth nicely, but it seems that I need to set the maxForce of the joint to an enormous value so I can actually see movement/rotation of the catapult! I don't understand. All this matter should be operated by small values, with regard to the values I had to set up.
Here is my very basic code that contains all of the above. Please tell me what I'm doing wrong, I'm freaking out here:
GameScreen.java
package com.david.box2dpractice;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
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.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.ChainShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.physics.box2d.joints.RevoluteJointDef;
import com.badlogic.gdx.utils.Array;
public class GameScreen implements Screen{
private Box2DDebugRenderer debugRenderer;
private Texture texture;
private Sprite sprite;
private Sprite tempSprite;
private SpriteBatch batch;
private Body arm , ground;
private World world;
public OrthographicCamera camera;
private RevoluteJointDef jointDef;
private Array<Body> tempBodies;
public GameScreen() {
debugRenderer = new Box2DDebugRenderer();
batch = new SpriteBatch();
texture = new Texture(Gdx.files.internal("catapult_arm.png"));
camera = new OrthographicCamera();
camera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
tempBodies = new Array<Body>();
}
#Override
public void render(float delta) {
// TODO Auto-generated method stub
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
world.getBodies(tempBodies);
batch.begin();
for(Body body : tempBodies) {
if(body.getUserData() != null && body.getUserData() instanceof Sprite) {
tempSprite = (Sprite) body.getUserData();
tempSprite.setPosition(body.getPosition().x-tempSprite.getWidth()/2, body.getPosition().y-tempSprite.getHeight()/2);
tempSprite.setRotation((float) Math.toDegrees(body.getAngle()));
tempSprite.draw(batch);
}
}
batch.end();
debugRenderer.render(world, camera.combined);
world.step(1/60f, 6, 2);
}
#Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
Gdx.app.log("System", "resize() was invoked");
}
#Override
public void show() {
// TODO Auto-generated method stub
Gdx.app.log("System", "show() was invoked");
world = new World(new Vector2(0,0), true);
sprite = new Sprite(texture);
BodyDef bodyDef = new BodyDef();
bodyDef.position.set(Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2+sprite.getHeight()/2);
bodyDef.type = BodyType.DynamicBody;
// The shape
PolygonShape shape = new PolygonShape();
shape.setAsBox(11, 91);
// The fixture
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = .10f;
arm = world.createBody(bodyDef);
arm.createFixture(fixtureDef);
sprite.setOrigin(sprite.getWidth()/2, sprite.getHeight()/2);
arm.setUserData(sprite);
shape.dispose();
bodyDef = new BodyDef();
bodyDef.position.set(Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2);
bodyDef.type = BodyType.StaticBody;
ChainShape shape2 = new ChainShape();
shape2.createChain(new Vector2[] {new Vector2(-20*Pixels_To_Meters,0),new Vector2(20*Pixels_To_Meters,0)});
// The fixture
fixtureDef.shape = shape2;
fixtureDef.restitution = .65f;
fixtureDef.friction = .75f;
ground = world.createBody(bodyDef);
ground.createFixture(fixtureDef);
shape2.dispose();
// joint
jointDef = new RevoluteJointDef();
jointDef.bodyA = arm;
jointDef.bodyB = ground;
jointDef.localAnchorB.set(ground.getLocalCenter());
jointDef.localAnchorA.set(arm.getLocalCenter().x,arm.getLocalCenter().y-sprite.getHeight()/2);
jointDef.enableLimit = true;
jointDef.enableMotor = true;
jointDef.motorSpeed = 15;
jointDef.lowerAngle = (float) -Math.toRadians(75);
jointDef.upperAngle = (float) -Math.toRadians(9);
jointDef.maxMotorTorque = 4800;
world.createJoint(jointDef);
Gdx.input.setInputProcessor(new InputHandler(arm,ground,world,camera));
}
#Override
public void hide() {
// TODO Auto-generated method stub
Gdx.app.log("System", "hide() was invoked");
dispose();
}
#Override
public void pause() {
// TODO Auto-generated method stub
Gdx.app.log("System", "pause() was invoked");
}
#Override
public void resume() {
// TODO Auto-generated method stub
Gdx.app.log("System", "resume() was invoked");
}
#Override
public void dispose() {
// TODO Auto-generated method stub
Gdx.app.log("System", "dispose() was invoked");
texture.dispose();
batch.dispose();
world.dispose();
}
}
InputHandler.java
package com.david.box2dpractice;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.QueryCallback;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.physics.box2d.joints.MouseJoint;
import com.badlogic.gdx.physics.box2d.joints.MouseJointDef;
public class InputHandler implements InputProcessor{
Body ground;
MouseJoint mouseJoint;
MouseJointDef mouseJointDef;
World world;
Vector2 target,initialPos;
Vector3 temp;
QueryCallback query;
OrthographicCamera camera;
boolean firstTime = true;
public InputHandler(Body arm, Body ground, final World world, OrthographicCamera camera) {
this.camera = camera;
this.ground = ground;
this.world = world;
mouseJointDef = new MouseJointDef();
target = new Vector2();
temp = new Vector3();
mouseJointDef.bodyA = ground;
mouseJointDef.collideConnected = true;
mouseJointDef.maxForce = 9000;
query = new QueryCallback() {
#Override
public boolean reportFixture(Fixture fixture) {
// TODO Auto-generated method stub
if(!fixture.testPoint(temp.x, temp.y))
return true;
if(firstTime) {
initialPos = new Vector2(fixture.getBody().getPosition().x,fixture.getBody().getPosition().y);
firstTime = false;
}
mouseJointDef.bodyB = fixture.getBody();
mouseJointDef.target.set(temp.x,temp.y);
mouseJoint = (MouseJoint) world.createJoint(mouseJointDef);
return false;
}
};
}
#Override
public boolean keyDown(int keycode) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean keyUp(int keycode) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean keyTyped(char character) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
// TODO Auto-generated method stub
camera.unproject(temp.set(screenX, screenY, 0));
world.QueryAABB(query, temp.x, temp.y, temp.x, temp.y);
return true;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
// TODO Auto-generated method stub
if(mouseJoint == null)
return false;
mouseJoint.setTarget(initialPos);
world.destroyJoint(mouseJoint);
mouseJoint = null;
firstTime = true;
return true;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
// TODO Auto-generated method stub
if(mouseJoint == null)
return false;
camera.unproject(temp.set(screenX, screenY, 0));
mouseJoint.setTarget(target.set(temp.x, temp.y));
return true;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean scrolled(int amount) {
// TODO Auto-generated method stub
return false;
}
}
If you could help me out here I would really really appreaciate that. Thanks!!

Box2D is only the Physic-Engine, the logical part. It does nothing with the view, so it is your job to convert the meters to pixels.
In Libgdx this could be done by using a Camera.
You are allready using a Camera, but you give it the "wrong" Viewport-Size.
You tell the Camera to be as big as the game (Gdx.graphics.getWidth, Gdx.graphics.getHeight), instead you should think about how many meters you want to show on your Screen.
If you want to show 80 meters in width and 45 meters i height (16/9), then you need to setup the Camera like this:
camera = new OrthographicCamera();
camera.setToOrtho(false, 80, 45);
So if your Game has a resolution of 1600*900 px, every meter would be convertet to 20px (camera does this for you), if you are using a resolution of 800*450, every meter would be converted to 10px.
Also box2Ds P(0/0) is not in the middle of the Screen, it is nowhere on the screen. It is on the P(0/0) of the box2D world, it is your job to draw it in the middle or the bottom or whererever you want.
Again, this is done by Camera. the Cameras P(0/0) by default is in the middle of the Screen, but you can move the camera arround, so it could be everywhere.
Now it should be clear, that the shape you created is not "super-small", but you just did not "zoom in". A 3m long car seems verry small if you watch it from a few 100m of distance. If you instead stand 1m away from it, you are almost unable to see the whole car at one time, as it is bigger then your "viewport".
I am not sure about the joints/forces, but it could be, that your problem is solved, if you "zoom in" by using a camera. But i also can be wrong, as i never used box2D...
Some tutorials:
IForce2D - Box2D, it is a tutorial fpr C++. but by reading the explanations you should understand it and be able to implement it in java/libgdx.
Using Box2D in Libgdx Game, this tutorial showes you how to create a game with box2D and libgdx. It really helps by understanding how to connect box2D with Libgdx.

Related

libgdx android app crashes when loading uiskin | no logs

For some reason after adding buttons to my application it has stopped functioning on android. It works as expected on desktop, but when attempting to run on android the app builds successfully, launches, then immediately crashes before it ever loads the scene. I attempted to view the logs via aLogcat, however I see nothing in these logs indicating an issue has occurred.
I have come to the conclusion that this issue has something to do with the uiskin/buttons being added to the stage, as I can add the stage without any actors and the app will still function in android. The files outlined in the uiskin.json file are all located in /android/assets directory as they should be. Is there something I have done incorrectly? Something I have missed?
uiskin.json
{
"com.badlogic.gdx.graphics.g2d.BitmapFont":{
"default_font": {
"file": "book_antiqua.fnt"
}
},
"com.badlogic.gdx.scenes.scene2d.ui.TextButton$TextButtonStyle":{
"default": {
"down": "default-round-down",
"up": "default-round",
"font": "default_font"
}
},
"com.badlogic.gdx.scenes.scene2d.ui.Window$WindowStyle":{
"default": {
"titleFont": "default_font"
}
}
}
Main class
package com.freedom.thirty;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.Material;
//import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.graphics.FPSLogger;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.viewport.FillViewport;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.freedom.thirty.MyCameraInputController;
public class FreedomThirty implements ApplicationListener {
public ScreenViewport vp;
public ScreenViewport stageVp;
public OrthographicCamera cam;
public MyCameraInputController camController;
public ModelBatch modelBatch;
public AssetManager assets;
public Array<ModelInstance> allModelInstances = new Array<ModelInstance>();
public Environment environment;
public boolean loading;
// Model instances that make up the map
public ModelInstance bridge;
public ModelInstance container_001;
public ModelInstance crate_001;
public ModelInstance crate_002;
public ModelInstance crate_003;
public ModelInstance crate_004;
public ModelInstance crate_005;
public ModelInstance grass_area;
public ModelInstance gravel_area;
public ModelInstance rock_wall;
public ModelInstance water;
public ModelInstance player;
public ModelInstance skybox;
public Skin skin;
public Stage stage;
public Table table;
//public FPSLogger fpsLogger = new FPSLogger();
#Override
public void create() {
modelBatch = new ModelBatch();
assets = new AssetManager();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.8f, 0.8f, 0.8f, 1f));
//environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new OrthographicCamera();
cam.position.set(-4f, 4f, 4f);
cam.lookAt(8f, 0f, -8f);
cam.near = 1f;
cam.far = 2000f;
cam.update();
// Create input controller for default scene camera. This is what allows the user to orbit around the scene
camController = new MyCameraInputController(cam);
// Set the position where the camera will look. This will need to come from json config file in the future
camController.target.set(8f, 0f, -8f);
vp = new ScreenViewport(cam);
vp.setUnitsPerPixel(0.017f);
vp.apply();
stageVp = new ScreenViewport();
stageVp.apply();
stage = new Stage(stageVp);
assets.load("uiskin.json", Skin.class);
assets.load("map_003.g3db", Model.class);
loading = true;
}
private void doneLoading(){ // Assets are now loaded into memory and can be accessed without error
// Load UI skin
skin = assets.get("uiskin.json", Skin.class);
// Define the buttons that will be in the ui table
final TextButton zoomOut = new TextButton("Zoom Out",skin,"default");
final TextButton zoomIn = new TextButton("Zoom In",skin,"default");
// Create UI table actor
table = new Table();
table.setWidth(stage.getWidth());
table.align(Align.center | Align.top);
// In the future determine what the current viewport height/width is, and set these
// to different sizes based on where the viewport falls between. Just like bootstrap's xs,sm,md,lg classes
table.setSize(250f, 250f);
table.setPosition(800f,400f);
zoomOut.setWidth(200);
zoomOut.setHeight(50);
zoomIn.setWidth(200);
zoomIn.setHeight(50);
// Event listeners for ui buttons
zoomOut.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y){
//Gdx.app.log("Zoom Out", "Press successful");
vp.setUnitsPerPixel(vp.getUnitsPerPixel() + 0.001f);
vp.update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
stageVp.update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
event.stop();
}
});
zoomIn.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y){
//Gdx.app.log("Zoom In", "Press successful");
vp.setUnitsPerPixel(vp.getUnitsPerPixel() - 0.001f);
vp.update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
stageVp.update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
event.stop();
}
});
// Add buttons to table
table.row().padBottom(30).padTop(30);
table.add(zoomOut);
table.add(zoomIn);
// Add table to stage
stage.addActor(table);
// Create an input multiplexer and add our stage and camController to it, set input processor to our new multiplexer
InputMultiplexer im = new InputMultiplexer(stage, camController);
Gdx.input.setInputProcessor(im);
// Load the 3d map, and character as character happens to be in the map file as of right now
// In the future each map and it's elements will be contained within it's own class, extended from
// map class
Model model = assets.get("map_003.g3db", Model.class);
bridge = new ModelInstance(model, "bridge");
allModelInstances.add(bridge);
container_001 = new ModelInstance(model, "container_001");
allModelInstances.add(container_001);
crate_001 = new ModelInstance(model, "crate_001");
allModelInstances.add(crate_001);
crate_002 = new ModelInstance(model, "crate_002");
allModelInstances.add(crate_002);
crate_003 = new ModelInstance(model, "crate_003");
allModelInstances.add(crate_003);
crate_004 = new ModelInstance(model, "crate_004");
allModelInstances.add(crate_004);
crate_005 = new ModelInstance(model, "crate_005");
allModelInstances.add(crate_005);
grass_area = new ModelInstance(model, "grass_area");
allModelInstances.add(grass_area);
gravel_area = new ModelInstance(model, "gravel_area");
allModelInstances.add(gravel_area);
rock_wall = new ModelInstance(model, "rock_wall");
allModelInstances.add(rock_wall);
water = new ModelInstance(model, "water");
allModelInstances.add(water);
player = new ModelInstance(model, "character");
allModelInstances.add(player);
player.transform.setTranslation(8f,0f,-6f); // Test character movement on the map
loading = false;
}
#Override
public void render() {
if(loading && assets.update()){
doneLoading();
}
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
camController.update();
//Gdx.app.log("Camera Position: ", cam.position.toString());
modelBatch.begin(cam);
modelBatch.render(allModelInstances, environment);
modelBatch.end();
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
//fpsLogger.log();
}
#Override
public void dispose() {
modelBatch.dispose();
allModelInstances.clear();
assets.dispose();
}
#Override
public void resize(int width, int height) {
vp.update(width, height);
stageVp.update(width, height);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
What finally corrected this issue was downloading the default uiskin files from the libgdx repository on github. Apparently I missed something when I built them from scratch? The files I used from the repo are:
uiskin.json
uiskin.atlas
default.png
uiskin.png
I think it takes to long to load the uiskin file. Try instead of skin = new Skin(Gdx.files.internal("uiskin.json")); something like that:
AssetManager manager = new AssetManager();
manager.load("uiskin.json", Skin.class);
manager.finishLoading();
skin = manager.get("uiskin.json", Skin.class);
Don't forget to dispose the AssetManager, when before you finish your game.

LibGDX Stage and Actor, Events and Actor properties

I'm just starting android game development with LibGdx framework.
I read many online tutorial so far and the more I read the more I got confused: ApplicationListener, ApplicationAdapter, Stages, Game, Screens, Actors, Sprites, Images... not mentioning Input and Gesture listeners of all king).
I finally understood what kind of "model" I should use for the game I have in mind (a kind of puzzle game): Game, Screens, Stage and Actor.
So here is my first code.
This is the main application (Game):
package com.my.game1;
import com.badlogic.gdx.Game;
public class MyGame extends Game {
#Override
public void create () {
setScreen(new StarterScreen());
}
}
This is the main screen class:
package com.my.game1;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.Stage;
public class StarterScreen implements Screen {
private Stage stage;
private float screenW, screenH;
private Tess tessera;
#Override
public void show() {
tessera = new Tess("image.png");
stage = new Stage();
screenW = stage.getViewport().getWorldWidth();
screenH = stage.getViewport().getWorldHeight();
Gdx.input.setInputProcessor(stage);
stage.addActor(tessera);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0,0,0,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act();
stage.draw();
}
#Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void hide() {
dispose();
}
#Override
public void dispose() {
stage.dispose();
}
}
And the following is the class that extends Actor:
package com.my.game1;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.utils.ActorGestureListener;
public class Tess extends Actor {
private Texture texture;
private boolean selected = false;
public Tess (String img) {
this.texture = new Texture(Gdx.files.internal(img));
this.setBounds(0f, 0f, this.texture.getWidth(), this.texture.getHeight());
this.setOrigin(this.texture.getWidth() / 2, this.texture.getHeight() / 2);
this.setScale(0.25f);
this.addListener(new ActorGestureListener() {
public void tap(InputEvent event, float x, float y, int pointer, int button) {
((Tess)event.getTarget()).toggleSelect();
((Tess)event.getTarget()).setColor(0.5f, 0f, 0.5f, 1f);
}
});
}
#Override
public void draw(Batch batch, float alpha){
batch.draw(texture, 0, 0);
}
public void finalize() {
this.texture.dispose();
}
public void toggleSelect(){
this.selected = !this.selected;
if (this.selected == true)
this.setColor(0.5f, 0f, 0.5f, 1f);
else
this.setColor(0f, 0f, 0f, 0f);
}
}
The screen shows correctly the actor, but I cannot set the Actor's position or its scale, nor the "tap" event seems to get detected; and the color doesn't change.
What I did wrong?
Several things were wrong. First, just on the side, you don't want to call dispose() from the Screen's hide() method. hide() can be called simply when the screen is turned off, or when the app is switched to the background, and disposing of the Screen during that would cause serious issues on resume.
With that out of the way, here's what your Actor should have looked like:
package com.my.game1;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Touchable;
public class Tess extends Actor {
private Sprite sprite;
private boolean selected = false;
public Tess (String img) {
this.sprite = new Sprite(new Texture(Gdx.files.internal(img)));
this.setTouchable(Touchable.enabled);
this.setBounds(this.sprite.getX(), this.sprite.getY(), this.sprite.getWidth(), this.sprite.getHeight());
this.setOrigin(this.sprite.getWidth() / 2, this.sprite.getHeight() / 2);
this.setScale(0.25f);
this.addListener(new ActorGestureListener() {
#Override
public void tap (InputEvent event, float x, float y, int pointer, int button) {
((Tess)event.getTarget()).toggleSelect();
}
});
}
#Override
public void draw(Batch batch, float alpha){
sprite.draw(batch);
}
#Override
public void positionChanged(){
sprite.setPosition(getX(), getY());
}
public void toggleSelect(){
this.selected = !this.selected;
if (this.selected == true)
sprite.setColor(0.5f, 0f, 0.5f, 1f);
else
sprite.setColor(0f, 0f, 0f, 0f);
}
}
First thing changed: you should use a Sprite, not a Texture, to handle color, drawing and transformations easily. Texture is possible, but is not as straightforward as Sprite is.
Next, you need to call setTouchable(Touchable.enabled) inside the actor to actually enable hit detection. Without this, no touch events are passed to the Actor.
After that, with setBounds(), you need to use sprite.getX() and sprite.getY(), to utilize the Sprite's positional values. Setting them to any arbitrary number seems to disable any touch capacity for that Actor.
Another thing, if all of that had been OK, is that you were setting the color twice for each touch, once based on the selected field, and then immediately after straight to the dark purple, so I removed the second set and just used your toggle method.
Next, since we have a Sprite now, we can use the draw() method attached to the Sprite itself and feed it the Batch, instead of calling the Batch's draw.
Finally, when you want to change the position of the image, call setPosition on the actor itself, and utilize an override of the positionChanged() method to set the Sprite's position based on the Actor's new position.

Pause Menu is "moving down" & improving the code

I have a problem with my pause screen. I made a simple Splash screen, followed by the main menu, where you can start or end the game, followed by a random picture. If the user presses Esc it switches to the pause screen, which is very similar to the main menu. Only difference is that it doesn't generate a new picture if the user clicks on "Continue", instead it just renders the game screen again. But if I press Esc after continuing again, the pause menu appears lower on the screen than it should. If I repeat pressing Continue and then Escape, the buttons eventually moved out of the displayed screen. I didn't find a solution yet, so I made an account here, since this site helped me a lot so far.
Furthermore I want to know if there are things I could improve. I just started with libGDX, so there probably are a lot of things I could've done better, and I want to know that. SO if you have a few improvements, I would be glad to read them :)!
This is the code:
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
public class GameScreen implements Screen{
private Texture[] monsterTextures = {new Texture(Gdx.files.internal("Ressources/DemonHunter.jpg")), new Texture(Gdx.files.internal("Ressources/WingedDemon.jpg")),
new Texture(Gdx.files.internal("Ressources/Viking.jpg")), new Texture(Gdx.files.internal("Ressources/DemonWarrior.jpg"))};
private Image[] monsterImages = {new Image(monsterTextures[0]), new Image(monsterTextures[1]), new Image(monsterTextures[2]), new Image(monsterTextures[3])};
private Stage gameStage = new Stage(), pauseStage = new Stage();
private Table table = new Table();
private Skin menuSkin = new Skin(Gdx.files.internal("skins/menuSkin.json"),
new TextureAtlas(Gdx.files.internal("skins/menuSkin.pack")));
private TextButton buttonContinue = new TextButton("Continue", menuSkin),
buttonExit = new TextButton("Exit", menuSkin);
private Label title = new Label ("Game", menuSkin);
private int randomMonster;
public static final int GAME_RUNNING = 0;
public static final int GAME_PAUSING = 1;
public static final int GAME_PAUSED = 2;
private int gamestatus = 0;
#Override
public void show() {
randomMonster = 0 + (int)(Math.random() * ((3-0) + 1));
gameStage.addActor(monsterImages[randomMonster]);
}
#Override
public void render(float delta) {
if(Gdx.input.isKeyJustPressed(Keys.ESCAPE)) pauseGame();
if(gamestatus == GAME_RUNNING) {
Gdx.gl.glClearColor(0,0,0,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
gameStage.act();
gameStage.draw();
}
if(gamestatus == GAME_PAUSING) {
buttonContinue.addListener(new ClickListener(){
public void clicked(InputEvent event, float x, float y) {
Gdx.gl.glClearColor(0,0,0,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
gamestatus = GAME_RUNNING;
}
});
buttonExit.addListener(new ClickListener(){
public void clicked(InputEvent event, float x, float y) {
Gdx.app.exit();
}
});
table.add(title).padBottom(40).row();
table.add(buttonContinue).size(150, 60).padBottom(20).row();
table.add(buttonExit).size(150, 60).padBottom(20).row();
table.setFillParent(true);
pauseStage.addActor(table);
Gdx.input.setInputProcessor(pauseStage);
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
pauseStage.act();
pauseStage.draw();
gamestatus = GAME_PAUSED;
}
if(gamestatus == GAME_PAUSED) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
pauseStage.act();
pauseStage.draw();
}
}
public void pauseGame() {
gamestatus = GAME_PAUSING;
}
#Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void pause() {
pauseGame();
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void hide() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
for(int i = 0; i < monsterTextures.length; i++) {
monsterTextures[i].dispose();
}
gameStage.dispose();
pauseStage.dispose();
menuSkin.dispose();
}
}
Thanks, Joshflux
I think your render() method is doing things it shouldn't. Like creating the clickListener and also adding buttons to the table (and possibly some other items in there).
The render method gets called every "frame". You don't want to be recreating this, say 60 times a second. You want to do it once (like when you create the particular screen) and then just draw (render) it every frame.
Restructure your code to do the "Creation" stuff once. The render() method should just draw it. I think you continually adding items to your table each frame may be what is causing the buttons to move off the screen.

libGDX 1.4.1 button listener on a secondary screen

I have two screens, a MainActivity in my core folder, that has the render() method split into a few switch cases. On game-over, this part of the switch case gets triggered, which calls the render part of my game-over class:
case STOPPED:
// Exit and clean the game
gameOverScreen.render(Gdx.graphics.getDeltaTime());
break;
...
This is my GameOverScreen class:
public class GameOverScreen implements Screen {
private SpriteBatch gameOverBatch;
private FreeTypeFontGenerator gameOverFontGen;
private FreeTypeFontGenerator.FreeTypeFontParameter gameOverLogoParam;
private FreeTypeFontGenerator.FreeTypeFontParameter gameOverButtonParam;
private final MainActivity mainActivity;
private OrthographicCamera camera;
private BitmapFont bitmapLogoFont;
private BitmapFont bitmapButtonFont;
private Button exitGameButton;
private Button gameRestartButton;
private Sound buttonSound;
private Stage stage;
private float w;
private float h;
// Constructor
public GameOverScreen(MainActivity mainActivity) {
w = Gdx.graphics.getWidth();
h = Gdx.graphics.getHeight();
gameOverBatch = new SpriteBatch();
this.mainActivity = mainActivity;
camera = new OrthographicCamera();
camera.setToOrtho(false, 300, 300);
// Instantiate the font for this screen from file
gameOverFontGen = new FreeTypeFontGenerator(Gdx.files.internal("fonts/SF_Wonder_Comic.ttf"));
gameOverLogoParam = new FreeTypeFontGenerator.FreeTypeFontParameter();
gameOverLogoParam.size = 110;
gameOverButtonParam = new FreeTypeFontGenerator.FreeTypeFontParameter();
gameOverButtonParam.size = 40;
// Font for the logo
bitmapLogoFont = new BitmapFont();
bitmapLogoFont = gameOverFontGen.generateFont(gameOverLogoParam);
// Font for the buttons
bitmapButtonFont = new BitmapFont();
bitmapButtonFont = gameOverFontGen.generateFont(gameOverButtonParam);
// Instantiate the buttonSound
buttonSound = Gdx.audio.newSound(Gdx.files.internal("sounds/pauseBtn_sound.ogg"));
/*************************************** Create a Stage *******************************************/
stage = new Stage();
// Add some actors as the buttons
exitGameButton = new Button(new TextureRegionDrawable(
new TextureRegion(new Texture(Gdx.files.internal("images/off_red.png")))),
new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("images/off_white.png")))));
//exitGameButton.setX((w, 150));
//pauseButton.setY(flipCoordinates(h, 150));
exitGameButton.setOrigin(exitGameButton.getWidth() / 2, exitGameButton.getHeight() / 2);
exitGameButton.setBounds(w / 2 + 100, h / 2 - 60, exitGameButton.getWidth(), exitGameButton.getHeight());
exitGameButton.act(Gdx.graphics.getDeltaTime());
stage.addActor(exitGameButton);
exitGameButton.addListener(new ChangeListener() {
#Override
public void changed (ChangeEvent event, Actor actor) {
buttonSound.play();
}
});
// Add some actors as the buttons
TextButton.TextButtonStyle restartStyle = new TextButton.TextButtonStyle();
restartStyle.font = bitmapButtonFont;
restartStyle.up = new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("images/back_red.png"))));
restartStyle.down = new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("images/back_white.png"))));
gameRestartButton = new Button(new TextButton.TextButtonStyle(restartStyle));
gameRestartButton.setOrigin(gameRestartButton.getWidth() / 2, gameRestartButton.getHeight() / 2);
gameRestartButton.setBounds(w / 2 - 100, h / 2 - 60, gameRestartButton.getWidth(), gameRestartButton.getHeight());
gameRestartButton.act(Gdx.graphics.getDeltaTime());
stage.addActor(gameRestartButton);
// Capture the event listener for the return button
gameRestartButton.addListener(new ChangeListener() {
#Override
public void changed(ChangeEvent event, Actor actor) {
// Do something on restart
//MainActivity.state = MainActivity.State.RUN;
Gdx.app.log("GameRestartButton", " has been pressed");
}
});
gameRestartButton.act(Gdx.graphics.getDeltaTime());
//stage.addActor(exitGameButton);
//stage.addActor(gameRestartButton);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
gameOverBatch.begin();
bitmapLogoFont.setColor(Color.RED);
bitmapLogoFont.draw(gameOverBatch, "Game Over", w / 2 - 210, h / 2 + 150f);
gameOverBatch.end();
exitGameButton.act(Gdx.graphics.getDeltaTime());
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
gameOverFontGen.dispose();
}
}
In GameOverScreen constructor I have two buttons (exitGameButton and gameReturnButton) I'd like to be able to trigger their event-listeners, but I can't seem to be able to do it. Neither of my buttons responds to the event listener. What am I doing wrong? Do I need to add something else on to my MainActivity class for these buttons to work ? Thanks much.
I figured it out, on the second screen I was missing from the constructor this: Gdx.input.setInputProcessor(stage); , of course, that only works if a stage has been previously created.
try this in your class GameOverScreen
.//
public Stage getStageGameOverScreen(){
return this.stage;
}
your Case:
case STOPPED:
// Exit and clean the game
Gdx.input.setInputProcessor(gameOverScreen.getStageGameOverScreen());
gameOverScreen.render(Gdx.graphics.getDeltaTime());
break;
...

moving actors with the gesture listener Libgdx

Hello I've been stuck on an issue for a while trying to create a simple game using the Libgdx framework.
I have a stage with a background Image actor and a stick figure image actor that is placed in the center of the stage.
I cant seem to understand, after reading many posts on stackoverflow and the libgdx wiki on event handling, how events such as fling and pan are passed to the actor to simply move it my stickman around the screen.
I would greatly appreciate any help or explanations on how exactly this works.
I just don't know how to get the integer values from pan and the velocity values from fling into my actor's Vector2 position variable so that it can move around every time the render method is called.
Here is some of my code:
My GestureDetection Class:
public class GestureDetection implements GestureListener{
public GestureDetection(){
}
#Override
public boolean touchDown(float x, float y, int pointer, int button) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean tap(float x, float y, int count, int button) {
System.out.println("tapped");
return false;
}
#Override
public boolean longPress(float x, float y) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean fling(float velocityX, float velocityY, int button) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean panStop(float x, float y, int pointer, int button) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean zoom(float initialDistance, float distance) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2,
Vector2 pointer1, Vector2 pointer2) {
// TODO Auto-generated method stub
return false;
}
}
My Game class
public class Game implements Screen{
StickFlick game;
SpriteBatch batch;
Texture gameBackground;
Stage stage;
GestureDetector gd;
InputMultiplexer im;
WalkingEnemy testEnemy;
public Game(StickFlick game){
this.game = game;
testEnemy = new WalkingEnemy("basic", 100, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
//enemy1.update(delta);
System.out.println("");
stage.act(Gdx.graphics.getDeltaTime());
batch.begin();
stage.draw();
batch.end();
}
#Override
public void resize(int width, int height) {
stage = new Stage(width, height, true);
stage.clear();
gd = new GestureDetector(new GestureDetection());
im = new InputMultiplexer(gd, stage);
Gdx.input.setInputProcessor(im);
Texture gameBackground = new Texture("data/gameBackground.png");
Image backgroundImage = new Image(gameBackground);
backgroundImage.setWidth(Gdx.graphics.getWidth());
backgroundImage.setHeight(Gdx.graphics.getHeight());
stage.addActor(backgroundImage);
stage.addActor(testEnemy.getImage());
stage.addAction(Actions.sequence(Actions.alpha(0), Actions.fadeIn(1)));
}
#Override
public void show() {
batch = new SpriteBatch();
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
}
}
Ok, so at start you have to make some variables where you will keep X and Y coords of your stick man. Set some initial values to them, i.e. x should be half of screen width and y half of screen height to have your stick man at the center of the screen.
Then you have to use information you are getting in your GestureListener implementation to move your stick man, that is to change it's coordinates. Your current implementation does absolutely nothing - methods are empty, so when some gesture happens your code is not reacting to it.
So, you can i.e. inside of your pan method use deltaX and deltaY to change stick man coordinates for those values. Something like:
X+=deltaX;
y+=deltaY;
Or you can multiply deltaX and deltaY with some constant if you want faster or slower movement and/or multiply deltaY with -1 if movement is in opposite way from what you want it to be.
Or if you want to use fling use those variables that method provides - velocityX and velocityY - add them to you stick man x and y to move it.
So basically, you are always drawing stick man at x,y coords and from some method of GestureListener interface you implemented you should change stick man coords and make him move.