Java – Incorrect touch position after resizing libGDX

Incorrect touch position after resizing libGDX… here is a solution to the problem.

Incorrect touch position after resizing libGDX

I have a button to use on the screen. However, when I resize the desktop window, the touch coordinates confuse themselves. I don’t know how to fix this.

So first I’m using

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

and called

viewport.update(width, height, true);

In my resizing method, this way my screen always looks proportional to its original size.

My opinion

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

Now after resizing the window, the image is in the correct position, but the touch coordinates are incorrect. It’s a bit hard to explain, but I’ll do my best. The scale is working properly. However, since I’m using Fitviewport, when I call Gdx.graphics.getHeights() or .getWidth(), it gets the height and width of the entire screen (including the black area when only one side is added). So this makes my input proportional to the entire screen. While the image is being illustrated through the Fitviewport and resized proportionally to its original size. This makes my input position respond too left or too right or too up or too down compared to the drawn image.
I’ve also tried cam.unproject. How do I fix this?

I’ve provided some logs that I hope will help you better understand my situation.

— unresized (raw) —

Resize call
Resize x : 480 y : 800
Scale x:1.0 y:1.0

(the original position of the coordinate button and the position where the button responds to input).
X:398 Y:75
before zooming
X:398 Y:75
after zooming
GDX input X : 398 Y : 75
Cam cancellation item X:240.26144 Y:400.53613

— adjusted —

Resize
Resize x : 807 y : 743
Scale x: 1.68125 y: 0.92875

Where the button appears on the screen –

X:542 Y:38
before zooming
X:322 Y:40
after scaling
GDX input X : 542 Y : 38
Cam cancellation item X: 240.13632 Y: 400.5924

– Touch coordinates of the button response-

X:677 Y:36
before zooming
X:402 Y:38
after zooming
GDX input X:677 Y:36
Cam cancellation item X: 240.2692 Y: 400.59595

Thanks!

Solution

I finally found a solution to my problem.
The problem is that I don’t know float division.

link. This float explains it well

Thank you all for your help

Related Problems and Solutions