Skip to content

Instantly share code, notes, and snippets.

@vlaaad
Created July 1, 2014 10:52
Show Gist options
  • Save vlaaad/725ac16543f6b5f545d5 to your computer and use it in GitHub Desktop.
Save vlaaad/725ac16543f6b5f545d5 to your computer and use it in GitHub Desktop.
Libgdx pinch zoom + pan listener
private EventListener dragListener = new ActorGestureListener() {
private float initialScale;
private float iX;
private float iY;
@Override
public void touchDown(InputEvent event, float x, float y, int pointer, int button) {
if (event.getTarget() != stage.getRoot())
return;
initialScale = root.getScaleX();
iX = root.getX();
iY = root.getY();
}
@Override
public void pan(InputEvent event, float x, float y, float deltaX, float deltaY) {
if (event.getTarget() != stage.getRoot())
return;
root.setPosition(root.getX() + deltaX, root.getY() + deltaY);
}
@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
if (event.getTarget() != stage.getRoot())
return;
if (Math.abs(iX - root.getX()) > 10 || Math.abs(iY - root.getY()) > 10)
return;
int worldX = (int) ((x - root.getX()) / (CELL_SIZE * root.getScaleX()));
int worldY = (int) ((y - root.getY()) / (CELL_SIZE * root.getScaleY()));
WorldViewEvent viewEvent = world.dispatcher.obtain(WorldViewEvent.class);
viewEvent.init(worldX, worldY);
world.dispatcher.dispatch(WorldViewEvent.ON_TAP, viewEvent);
}
@Override
public void pinch(InputEvent event, Vector2 initialPointer1, Vector2 initialPointer2, Vector2 pointer1, Vector2 pointer2) {
float initialDistance = initialPointer1.dst(initialPointer2);
float distance = pointer1.dst(pointer2);
float pointerScale = distance / initialDistance;
float targetScale = initialScale * pointerScale;
root.setScale(targetScale);
float icx = (initialPointer1.x + initialPointer2.x) / 2;
float icy = (initialPointer1.y + initialPointer2.y) / 2;
float tcx = (pointer1.x + pointer2.x) / 2;
float tcy = (pointer1.y + pointer2.y) / 2;
float d = (float) Math.sqrt(iX * iX + iY * iY);
//initial x == 0 -> 0
root.setPosition(
iX + (tcx - (icx) * pointerScale) - iX * (initialScale - targetScale) / initialScale,
iY + (tcy - (icy) * pointerScale) - iY * (initialScale - targetScale) / initialScale
);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment