Created
July 1, 2014 10:52
-
-
Save vlaaad/725ac16543f6b5f545d5 to your computer and use it in GitHub Desktop.
Libgdx pinch zoom + pan listener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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