moving actors with the gesture listener Libgdx - 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.

Related

libgdx isometric tiled map screen to world with viewport

I wanted to create a simple 30x30 isometric tiled map and add a listener to be able to click on the tiles. I looked up a lot of the articles and posts here but none of them helped me.
My issue is, i have a viewport, 30x17, a camera, a stage and a tiled map with tileWidth = 32 and tileHeight = 16 pixels.
Now when i render the tiled map it looks fine.
When i click on stage and try to get the world coordinates i see some really weird coordinates.
This is the code:
private static final float TILE_WIDTH = 32;
private static final float TILE_HEIGHT = 16;
private OrthographicCamera camera;
private Viewport viewport;
private Stage stage;
private IsometricTiledMapRenderer isometricTiledMapRenderer;
private Matrix4 isoTransform;
private Matrix4 invIsotransform;
public void load(AssetManagerLoaderV2 assetManagerLoader) {
assetManagerLoader.load();
init();
camera = new OrthographicCamera();
viewport = new FitViewport(30, 17, camera);
stage = new Stage(viewport);
TiledMap tiledMap = new TiledMapGenerator(assetManagerLoader).generate(30, 30);
isometricTiledMapRenderer = new IsometricTiledMapRenderer(tiledMap, 1/32f);
stage.addListener(new InputListener() {
#Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
System.out.println(screenToCell(x, y));
return true;
}
});
}
#Override
public void show() {
Gdx.input.setInputProcessor(stage);
}
#Override
public void render(float delta) {
DrawUtils.clearScreen();
viewport.apply();
isometricTiledMapRenderer.setView(camera);
isometricTiledMapRenderer.render();
}
#Override
public void resize(int width, int height) {
stage.getViewport().update(width, height, true);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
isometricTiledMapRenderer.dispose();
stage.dispose();
}
public void init () {
//create the isometric transform
isoTransform = new Matrix4();
isoTransform.idt();
isoTransform.translate(0.0f, 0.25f, 0.0f);
isoTransform.scale((float)(Math.sqrt(2.0) / 2.0), (float)(Math.sqrt(2.0) / 4.0), 1.0f);
isoTransform.rotate(0.0f, 0.0f, 1.0f, -45.0f);
//... and the inverse matrix
invIsotransform = new Matrix4(isoTransform);
invIsotransform.inv();
}
public Vector2 worldToCell(float x, float y) {
float halfTileWidth = TILE_WIDTH * 0.5f;
float halfTileHeight = TILE_HEIGHT * 0.5f;
float row = (1.0f/2) * (x/halfTileWidth + y/halfTileHeight);
float col = (1.0f/2) * (x/halfTileWidth - y/halfTileHeight);
return new Vector2((int)col,(int)row);
}
public Vector2 screenToWorld(float x, float y){
Vector3 touch = new Vector3(x,y,0);
camera.unproject(touch);
touch.mul(invIsotransform);
touch.mul(isoTransform);
return new Vector2(touch.x,touch.y);
}
public Vector2 screenToCell(float x, float y) {
Vector2 world = screenToWorld(x,y);
world.y -= TILE_HEIGHT *0.5f;
return worldToCell(world.x,world.y);
}
Does anyone have an idea how to write worldToCell to get the proper coordinates?
I found the issue, i was missing one step.
This is what touchDown should look like:
#Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
Vector2 newCoords = stage.stageToScreenCoordinates(new Vector2(x, y));
System.out.println(screenToCell(newCoords.x, newCoords.y));
return true;
}
I need to convert stage coordinates to screen coordinates, now this code is working.

Actor in Stage Does Not Update the MoveTo XY Location

I am creating a game wherein an apple is being shot with an arrow. The apple's location is the XY location of the user input and the arrow actor has to move to that location using the code actor.moveto. The problem is the arrow only moves only once to the user input's direction. I know that the moveTo action of the actor is updated many times per second when I called stageArrow.act in the update method so I am wondering why the arrow only moves once. Here's my code:
appleclass.java
public class AppleClass implements Screen {
Arrow arrow;
private final MainApp app;
public Image ShotImage;
public AppleClass(final MainApp app){
this.app = app;
this.stageApple = new Stage(new StretchViewport(app.screenWidth,app.screenHeight , app.camera));
this.stageArrow =new Stage(new StretchViewport(app.screenWidth,app.screenHeight , app.camera));
arrow = new ArrowClass(app);
}
#Override
public void show() {
InputMultiplexer inputMultiplexer = new InputMultiplexer();
inputMultiplexer.addProcessor(stageApple);
inputMultiplexer.addProcessor(stageArrow);
Gdx.input.setInputProcessor(inputMultiplexer);
arrow();
}
public void arrow(){
arrow.isTouchable();
stageArrow.addActor(arrow);
arrow.addAction((moveTo(Gdx.input.getX(),Gdx.input.getY(),0.3f))); //===> only executes once.
arrow.addListener(new InputListener(){
public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor){
if (Gdx.input.isTouched()){
ShotImage.setVisible(true);
}
}
});}
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
update(delta);
}
public void update(float deltaTime){
stageApple.draw();
stageArrow.draw();
stageApple.act(deltaTime);
stageArrow.act(deltaTime);
}
ArrowClass.java
public class ArrowClass extends Actor {
MainApp app;
AppleClass appleClass;
public Texture arrowTexture;
public ArrowClass(final MainApp app){
this.app = app;
arrowTexture = new Texture("medievalarrow.png");
this.setSize(arrowWidth, arrowHeight);
this.setTouchable(Touchable.enabled);
this.setBounds(app.screenWidth*0.45f,0,arrowWidth,arrowHeight);
this.setOrigin(0,0);
}
#Override
public void draw(Batch batch, float parentAlpha) {
super.draw(batch, parentAlpha);
final float delta = Gdx.graphics.getDeltaTime();
this.act(delta);
app.batch.begin();
app.batch.draw(arrowTexture, getX(),getY(),getWidth(),getHeight());
app.batch.end();
}
}
Any help will be highly appreciated. Thanks.
I think the problem is because you are calling this.act(delta) in your ArrowClass' draw method. When you call Stage#act(), it will call the act method on all of its actors for you. Since you're calling it once when you draw and again when you update the stage, it's moving at twice the normal speed and that could be causing it to reach its destination prematurely.
A few other comments about your code, if I may:
First, you probably don't want two separate stages- unless you're using Scene2D.UI, you would normally have a single stage with Arrow and Apple added to it as actors.
Second, when you override Actor#draw(), you should use the batch it passes you to do the rendering instead of using the one from app. You also don't want to call begin() and end() inside your draw method- these are 'expensive' and you only want to call them once per frame. However, if you just use the batch that is passed to draw(), the Stage class will handle beginning and ending for you and you won't need to call them explicitly.
Third, you actually don't need to call super.draw(batch, parentAlpha) because it's an empty method in the Actor class.
Thus, your class could be simplified to the following:
public class ArrowClass extends Actor {
AppleClass appleClass; // You never set this; you may not need it
Texture arrowTexture;
public ArrowClass(MainApp app, arrowWidth, arrowHeight) {
arrowTexture = new Texture("medievalarrow.png");
this.setSize(arrowWidth, arrowHeight);
this.setTouchable(Touchable.enabled);
this.setBounds(app.screenWidth*0.45f,0,arrowWidth,arrowHeight);
this.setOrigin(0,0);
}
#Override
public void draw(Batch batch, float parentAlpha) {
batch.draw(arrowTexture, getX(),getY(),getWidth(),getHeight());
}
}

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.

Box2D can't understand the way it works - 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.

LibGdx Stage/Actor InputListener (Appropriate Area for InputListener)

I have a class Bubble that extends Actor.
public Bubble(MyGdxGame game,Texture texture){
this.game=game;
setPosition(0,0);
setSize(32,32);
gameObject=new GameObject("","bubble");
direction=new MovementDirection();
sprite=new Sprite(texture);
setTouchable(Touchable.enabled);
setWidth(sprite.getWidth());
setHeight(sprite.getHeight());
setBounds(0,0,sprite.getWidth(),sprite.getHeight());
addListener(new InputListener() {
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
Gdx.app.log("BUBBLE", "touchdown");
return true; // must return true for touchUp event to occur
}
public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
Gdx.app.log("BUBBLE", "touchup");
}
});
}
This is in a class that implements Screen
public void show() {
// TODO Auto-generated method stub
super.show();
//2 bubbles test
gameStage=new Stage(MyGdxGame.WIDTH,MyGdxGame.HEIGHT,true);
Gdx.input.setInputProcessor(gameStage);
for (int i=0; i<10; i++){
Bubble b=new Bubble(game,Assets.bubbleTexture);
b.randomize();
gameStage.addActor(b);
}
//if (bubbleList==null)
// createBubbles();
}
Am I going about this the wrong way by adding the listener # the bubble level? (It seems creating an InputListener for every bubble I spawn is a little crazy).
According to : http://libgdx.l33tlabs.org/docs/api/com/badlogic/gdx/scenes/scene2d/Actor.html
Actor has a touchUp() and touchDown event - but complains when i try to override them (which lead me to believe they dont exist). Overriding these I feel would be a better approach
The docs you linked to are outdated.
Those methods were deprecated and removed in favor of using InputListeners.
In your example if you want to use the same InputListener instance for all instances of your Actor class (Bubble) then you can just implement the InputListener to refer to the Actor class instance using inputEvent.getRelatedActor() and then instantiate one such InputListener as a static member of Bubble and pass it in the constructor to addListener.
class Bubble extends Actor{
private static InputListener bubbleListener= new InputListener() {
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
Bubble b = (Bubble) event.getRelatedActor();
b.doSomething();
...
return true; //or false
}
}
public Bubble(){
addListener(bubbleListener);
...
}
...
}