Skip to content

Instantly share code, notes, and snippets.

@Akjosch
Created October 7, 2015 19:39
Show Gist options
  • Save Akjosch/7f038fc070d610baef6b to your computer and use it in GitHub Desktop.
Save Akjosch/7f038fc070d610baef6b to your computer and use it in GitHub Desktop.
Example mouse-driven map input processor for libgdx
package mygame;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Input.Buttons;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.OrthographicCamera;
/**
* A simple input processor which supports dragging the view by clicking and holding the left mouse button,
* as well as scrolling with the mouse wheel.
* <p>
* Example usage:
* <p>
* In {@link Screen#show()} or {@link ApplicationListener#create()}
* <pre>
* mapInputProc = new MapInputProcessor();
* Gdx.input.setInputProcessor(mapInputProc);
* </pre>
* In {@link Screen#render()} or {@link ApplicationListener#render()}, assuming the usage of an {@link OrthographicCamera}
* <pre>
* camera.viewportWidth = Gdx.graphics.getWidth() * mapInputProc.scale;
* camera.viewportHeight = Gdx.graphics.getHeight() * mapInputProc.scale;
* camera.position.x = mapInputProc.offsetX;
* camera.position.y = mapInputProc.offsetY;
* camera.update();
* </pre>
*/
public class MapInputProcessor extends InputAdapter {
private static final float MIN_SCALE = 0.01f;
private static final float MAX_SCALE = 10.0f;
private boolean mouseDown = false;
public float scale = 1.0f;
public float offsetX = 0.0f;
public float offsetY = 0.0f;
private int lastX;
private int lastY;
@Override public boolean touchDown(int screenX, int screenY, int pointer, int button) {
if( button == Buttons.LEFT ) {
mouseDown = true;
lastX = screenX;
lastY = screenY;
}
return false;
}
@Override public boolean touchUp(int screenX, int screenY, int pointer, int button) {
if( button == Buttons.LEFT ) {
mouseDown = false;
}
return false;
}
@Override public boolean touchDragged(int screenX, int screenY, int pointer) {
if( mouseDown ) {
offsetX -= (screenX - lastX) * scale;
offsetY += (screenY - lastY) * scale;
lastX = screenX;
lastY = screenY;
}
return false;
}
@Override public boolean scrolled(int amount) {
updateScale(scale * (1.0f + amount/10.0f));
return false;
}
public void updateScale(float newScale) {
if( newScale > MAX_SCALE ) { newScale = MAX_SCALE; }
if( newScale < MIN_SCALE ) { newScale = MIN_SCALE; }
scale = newScale;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment