When creating a game, most of the times you will be required to detect touch or a click on an object.
By default, if you use Gdx.input.justTouched() and if you then try to get the coordinates touched by using Gdx.input.getX() and Gdx.input.getY(), then you will see that the touched points are different than the actual coordinate of the object. The same thing happens if we use the following method to detect a touch:
Gdx.input.setInputProcessor(new InputProcessor() {
public boolean touchDown(int x, int y, int point, int button) {
return true;
}
});
To resolve this issue and be able to detect the touch correctly, we have to unproject the device coordinates using the camera. Below is an example with touching a Rectangle called “drawer”:
Create an instance variable in your class:
Vector3 touchPoint;
Initialize this variable in your constructor:
touchPoint = new Vector3();
Let’s assume we have a Rectangle object called “drawer” defined as follows:
drawer = new Rectangle(1614, -88, 100, 100);
Then in the render(float delta) method, we will unproject and detect the touch as follows:
if (Gdx.input.justTouched()) {
camera.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0));
if (drawer.contains(touchPoint.x, touchPoint.y)) {
// A touch was successfully detected!
return true;
}
return false;
}
0 Comments