Java JScrollBar 使用 double

问题描述

所以我正在用 Java 制作一个简单的游戏,其中瓷砖地图中有一个小坦克。虽然我遇到了一个关于 JScrollBars 的问题:当我将坦克的身体旋转到北方以东一定角度(特别是 14 或更少)并且我向前移动坦克(使用“W”键)时,坦克不会移动按预期在 x 和 y 方向上,仅在 y 方向上。以下图片有助于理解我的意思:

向北以东 14 度旋转的坦克图片未向上平移:

https://i.stack.imgur.com/7oexE.png

向北以东 14 度旋转的坦克图片向上平移:

https://i.stack.imgur.com/Q1oTz.png

澄清:当我用“A”和“D”键旋转坦克的身体时,不会有 x 或 y 平移。当我按下“W”或“S”键时,坦克向前或向后移动(向前或向后移动的方向取决于坦克身体所在的角度),那么将有 x和 y 个翻译

发生这种情况是因为我在 x 方向上移动的值比 double 值太小,并且当转换为 int 时变为 0,从而导致 x 没有变化。 (我必须转换为 int 因为 JScrollBar.setValue() 只接受整数)。这是我的代码,可以更好地解释这种情况:

int bodyAngle = 0; //the angle of the tank's body (it will face north as inital direction)
int d_angle = 2; //the change in angle when I click the rotate (see below)

//when I press the "D" key,the tank's body will rotate to the right by d_angle (and will keep rotating until I release "D")
case KeyEvent.VK_D:
    bodyAngle += D_ANGLE;
    ROTATE_TANK_BODY = ImageTool.rotateImage(TANK_BODY,bodyAngle,"body",0);
    break;

//When the tank's angle is rotated and I press the forward key ("W"),there needs to be some math to calculate the correct x and y translations
case KeyEvent.VK_W:
    moveX = (int) Math.round(Math.sin(Math.toRadians(bodyAngle)));
    moveY = (int) Math.round(Math.cos(Math.toRadians(bodyAngle)));
    vScrollBar.setValue(vScrollBar.getValue() - moveY); //set new scrollbar values
    hScrollBar.setValue(hScrollBar.getValue() + moveX);
    break;

我的问题是,如何提高滚动条位置变化的准确性?准确性的损失显然来自将我预测的 x 转换转换为整数,但我不太确定如何修复它。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)