如何在改变分辨率的同时计算鼠标坐标到世界坐标

问题描述 投票:0回答:1

我正在开发一个Java游戏,我需要计算世界空间中的鼠标坐标,同时更改游戏窗口的分辨率。我目前正在使用以下代码来执行计算:

Game.s2wX = (int)(((mouseX - (Window.REAL_WIDTH() / 2 - Window.SCALED_WIDTH() / 2)) / s) - (-x - width/2 + (Window.SCALED_WIDTH() / s) / 2));
Game.s2wY = (int)(((mouseY - (Window.REAL_HEIGHT() / 2 - Window.SCALED_HEIGHT() / 2)) / s) - (-y - height / 2 + (Window.SCALED_HEIGHT() / s) / 2));

使用以下代码将游戏绘制在屏幕中央:

g.drawImage(image,
    Window.REAL_WIDTH()/2-Window.SCALED_WIDTH()/2,
    Window.REAL_HEIGHT()/2-Window.SCALED_HEIGHT()/2,
    Window.SCALED_WIDTH(), Window.SCALED_HEIGHT(),null);

我怀疑当分辨率改变时,s2wX和s2wY变量中鼠标坐标的计算不正确。有人可以帮助我了解如何在适应分辨率变化的同时正确计算世界空间中的鼠标坐标吗?

它在 720x480 窗口和全屏上工作得非常好,因为它指向 0, 0 到左上角。但是当我尝试提高分辨率时,我遇到了偏移。红色标记指向鼠标光标。

java awt
1个回答
0
投票

试试这个:

int mouseX; // Current mouse X position in screen space
int mouseY; // Current mouse Y position in screen space

double scalingFactorX = (double) Window.SCALED_WIDTH() / Window.REAL_WIDTH();
double scalingFactorY = (double) Window.SCALED_HEIGHT() / Window.REAL_HEIGHT();

int translationX = (Window.REAL_WIDTH() - Window.SCALED_WIDTH()) / 2;
int translationY = (Window.REAL_HEIGHT() - Window.SCALED_HEIGHT()) / 2;

Game.s2wX = (int) (((mouseX - translationX) / scalingFactorX) - (-x - width / 2 + (Window.SCALED_WIDTH() / (scalingFactorX * s)) / 2));
Game.s2wY = (int) (((mouseY - translationY) / scalingFactorY) - (-y - height / 2 + (Window.SCALED_HEIGHT() / (scalingFactorY * s)) / 2));

更新代码:

double scalingFactorX = (double) Window.SCALED_WIDTH() / Window.REAL_WIDTH();
double scalingFactorY = (double) Window.SCALED_HEIGHT() / Window.REAL_HEIGHT();

int translationX = (Window.REAL_WIDTH() - Window.SCALED_WIDTH()) / 2;
int translationY = (Window.REAL_HEIGHT() - Window.SCALED_HEIGHT()) / 2;

int screenX = mouseX - translationX;
int screenY = mouseY - translationY;

Game.s2wX = (int) (screenX / scalingFactorX);
Game.s2wY = (int) (screenY / scalingFactorY);

在这段代码中,当分辨率改变时,我根据世界空间调整鼠标坐标。

© www.soinside.com 2019 - 2024. All rights reserved.