Search code examples
javaandroidlibgdx

touch position not correct after resizing libGDX


I have a button that I want to use on my screen. However when I resize my desktop window, the touch coordinates messes up itself. I have no idea how to solve this.

So first of all I'm using

cam = new PerspectiveCamera();
viewport = new FitViewport(screenWidth, screenHeight, cam);

and called

viewport.update(width, height, true);

in my resize method so that my screen would always look scaled proportional to its original size.

For my input

Gdx.input.setInputProcessor(new InputHandler((float) scaleX, (float) scaleY, world));

Now after resizing my window, the images are at correct places but the touch coordinates are not. It's kind of hard to explain but I will try my best. The scale is working properly. However, since I am using Fitviewport, when I call Gdx.graphics.getHeights() or .getWidth(), it's getting the height and width of the entire screen (including the black areas when I increase one side only). Thus, this makes my scale for my input proportional to the entire screen. While the images are being illustrated via Fitviewport and being resized proportional to it's original size. This makes my input position where the button responses to be too far left or right or up or down compared to the images that are drawn. I have also tried cam.unproject. How do I solve this?

I have some log provided in hopes that it will help you understand my situation better.

---not resized(original) ---

resize called
Resizing x : 480 y : 800
Scales x : 1.0 y : 1.0

(coordinates where the button originally is and where the button response to input)
Before Scaled X : 398 Y : 75
After Scaled X : 398 Y : 75
Gdx input X : 398 Y : 75
cam unproject X : 240.26144 Y : 400.53613

---after resizing---

resize called
Resizing x : 807 y : 743
Scales x : 1.68125 y : 0.92875

-where button appears on screen-

Before Scaled X : 542 Y : 38
After Scaled X : 322 Y : 40
Gdx input X : 542 Y : 38
cam unproject X : 240.13632 Y : 400.5924

-touch coordinate at which button response to-

Before Scaled X : 677 Y : 36
After Scaled X : 402 Y : 38
Gdx input X : 677 Y : 36
cam unproject X : 240.2692 Y : 400.59595

Thank you!


Solution

  • I finally found my solutions to my question. The problem was that I did not know about float division.

    link. I need to divide float/int. This float division explains well

    thx for all the help tho