Sunday, June 22, 2014

[libgdx] day 18 – gestures

If you’Ve got a touchscreen you probably like to use gestures like pinch to zoom to view for example details on a map.
Of couse libgdx makes this really simple for us.

Maybe you remember the InputProcessors from day 3. We first wrote our own and later took the one from the stage. But you can as well combine two InputProcessors. The second one only gets the event if the first let’s it through (return false for example if you do not press a button in a menu).
InputMultiplexer multiplexer = new InputMultiplexer();
multiplexer.addProcessor(stage);
multiplexer.addProcessor(new GameInputProcessor());
Gdx.input.setInputProcessor(multiplexer);
libgdx has a interface called GestureListener that you have to implement:

public class MyGestureListener implements GestureListener {

 @Override
 public boolean zoom (float originalDistance, float currentDistance) {
  return false;
 }

 @Override
 public boolean pinch (Vector2 initialFirstPointer, Vector2 initialSecondPointer, Vector2 firstPointer, Vector2 secondPointer) {
  return false;
 }

 @Override
 public boolean touchDown(float x, float y, int pointer, int button) {
  return false;
 }

 @Override
 public boolean tap(float x, float y, int count, int button) {
  return false;
 }

 @Override
 public boolean longPress(float x, float y) {
  return false;
 }

 @Override
 public boolean fling(float velocityX, float velocityY, int button) {
  return false;
 }

 @Override
 public boolean pan(float x, float y, float deltaX, float deltaY) {
  return false;
 }
}

// [...]
Gdx.input.setInputProcessor(new GestureDetector(new MyGestureListener()));
You pass this interface to a GestureDetector (that’s a special InputProcessor) and you’ll get all the gestures.
You can find an explanation to the methods of the GestureListener in the API.
I implemented zooming my tilemap. Important was to see that you get the original distance of the fingers and the current one. So you have to save the original zoom of the camera each time the zoom starts and have to calculate with that.
float origDistance;
float origZoom;
public boolean zoom (float originalDistance, float currentDistance) {
 if(originalDistance != origDistance){
  origDistance = origDistance;
  origZoom = camera.zoom;
 }
 camera.zoom = origZoom*currentDistance/originalDistance;
 return false;
}
20121218_09113520121218_09113020121218_091125

No comments:

Post a Comment

Popular Posts