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 转换转换为整数,但我不太确定如何修复它。

解决方法

您应该直接使用图形和翻译图像,而不是尝试使用滚动条,但是,问题是滚动条的范围通常为 0-100。如果您想要更高精度的滚动条,则只需更改范围,但请注意,对于小的/精细调整,它们实际上无法在屏幕上显示/渲染,因为像素数量有限,因此它可能看起来好像什么都没有直到滚动条移动到足够远以使图像移动一个像素为止。

增加滚动精度的例子:

//If you created the scroll bars yourself then you can set the range as follows:
javax.swing.JScrollBar myBar = new JScrollBar(HORIZONTAL,startValue,extent,minValue,maxValue);

//Or to edit a scroll bars inside an existing jScrollPane then you can change the max value:
yourScrollPane.getHorizontalScrollBar().setMaximum(maxValue);

如果您希望精度达到小数点的一半,则滚动条范围需要是地图/图像大小的两倍。如果您希望精确到小数点后一位,那么您的滚动条范围需要是地图大小的 10 倍:

//Map size in pixels,for example 400x400
int mapSize = 400;
//Scale factor of 10 for 0.1 decimal place precision,or scale factor of 2 for 0.5 precision
int scaleFactor = 10;
//Scroll bars with 1 decimal place precision (400 x 10 = 4000)
vScrollBar.setMaximum(mapSize * scaleFactor);
hScrollBar.setMaximum(mapSize * scaleFactor);

//Then to scroll to 200.1,200.5 you can use (Note everything has a scale of 10 so 200 needs to be 2000)
vScrollBar.setValue((int)200.1 * scaleFactor);
hScrollBar.setValue((int)200.5 * scaleFactor);

再说一次,我不推荐这个解决方案,它可能不会改变任何东西,因为小增量不会显示在屏幕上或者它可能会出现断断续续的现象。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...