Chamila Wijayarathna Chamila Wijayarathna - 1 year ago 74
Android Question

Android libgdx - check if touched on image

I am trying to create a simple android game using libgdx. I have image in screen and I need to identify if I touched on the image. Following is the code I wrote so far.

public final static float VP_WIDTH = 480 * INV_SCALE;
public final static float VP_HEIGHT = 800 * INV_SCALE;

private OrthographicCamera camera;
private ExtendViewport viewport;
SpriteBatch batch;
Texture texture;
private int screenHeight, screenWidth;
Sprite playImage;

public void create() {
batch = new SpriteBatch();
screenWidth =;
screenHeight =;
camera = new OrthographicCamera();

// pick a viewport that suits your thing, ExtendViewport is a good start
viewport = new ExtendViewport(VP_WIDTH, VP_HEIGHT, camera);
texture = new Texture("play.png");
playImage = new Sprite(texture);
playImage.setSize(texture.getWidth(), texture.getHeight());

public void render() {

camera.update();, 1, 1, 1);;
batch.draw(playImage, 240 - texture.getWidth() / 2, 200 - texture
.getHeight() / 2);


public void dispose() {

public void resize(int width, int height) {
viewport.update(width, height, true);

public boolean touchDown(int screenX, int screenY, int pointer, int button) {
camera.unproject(tp.set(screenX, screenY, 0));
if (state.equals(States.STARTED)) {
if (screenX >= screenWidth / 2 - texture.getWidth() / 2 && screenX <= screenWidth / 2 + texture
.getWidth() / 2 && screenY <= 3 * screenHeight / 4 + texture.getHeight() / 2 && screenY
>= 3 * screenHeight / 4 - texture.getHeight() / 2)
playButtonClicked = true;

return true;

In the screen I see my image positioned properly, but when I click it, it only goes in to the for loop when I click on the middle part of the image.

It seems like screenX and screenY are ranging from something different than 480,800. Can someone point me if I am doing something wrong here?

Answer Source

After you unproject with the camera, the unprojected x and y are contained in the tp vector you used. Java methods cannot modify the values of passed-in parameters (like can be done with pointers in C).

Other than that, your code looks highly un-maintainable. You are drawing the image with one set of equations and calculating its touch boundary with a different set of complicated equations. You should define its boundary in one place (maybe a Rectangle member variable) and use that both for drawing and hit detection.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download