浮动不能超过256?

时间:2017-01-25 18:55:52

标签: java lwjgl

我正在制作一个游戏,我正在设置一个带浮动的位置,问题是浮动是不是要高于它们255? 这就是我让浮动更高的方式: 1.添加方法:

public Location add(float x, float y, float z){
    this.x += x; this.y += y; this.z += z;
    return this;
}

2。更新方法

public void update(){
        float speed = 0.00001f;
        float rotspeed = 0.00001f;
        if (Keyboard.isKeyDown(Keyboard.KEY_UP)) Main.renderer.rotate(-rotspeed, 0, 0);
        if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) Main.renderer.rotate(rotspeed, 0, 0);
        if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) Main.renderer.rotate(0, rotspeed, 0);
        if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)) Main.renderer.rotate(0, -rotspeed, 0);

        if (Keyboard.isKeyDown(Keyboard.KEY_W)) Main.renderer.renderLocation.add(0, 0, speed);
        if (Keyboard.isKeyDown(Keyboard.KEY_S)) Main.renderer.renderLocation.add(0, 0, -speed);
        if (Keyboard.isKeyDown(Keyboard.KEY_D)) Main.renderer.renderLocation.add(-speed, 0, 0);
        if (Keyboard.isKeyDown(Keyboard.KEY_A)) Main.renderer.renderLocation.add(speed, 0, 0);

        if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) Main.renderer.renderLocation.add(0, -speed, 0);
        if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) Main.renderer.renderLocation.add(0, speed, 0);
        fixRenderRotation();
    }

在子线程中的while循环中调用更新。

这就是我使用浮动

的原因
public void update(){
    System.out.println("render_location "+renderLocation.x+" "+renderLocation.y+" "+renderLocation.z+" rotation "+rotation.x+" "+rotation.y+" "+rotation.z);
    GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
    GL11.glLoadIdentity();
    GL11.glTranslatef(renderLocation.x, renderLocation.y, renderLocation.z);
    //GL11.glTranslatef(renderLocation.x, renderLocation.y, renderLocation.z);
    GL11.glRotatef(rotation.x, 1F, 0F, 0F);
    GL11.glRotatef(rotation.y, 0F, 1F, 0F);
    GL11.glRotatef(rotation.z, 0F, 0F, 1F);
    ((RenderObject.UnknownRenderInformation) collection.getRenderInformation()).act();
}

它是renderLocaiton变量。 我并没有阻止它走得更高。

2 个答案:

答案 0 :(得分:3)

float只有约6位数的准确度。我建议使用int并除以100,000或使用double

当您将1e-5f添加到256f时,答案为256f,因为这是最接近的可表示值。你有双重同样的问题,但在更高的点。如果您将1e-5添加到137438953472,那么当您超出double的精度时,会发生同样的事情。

如果使用int,则会出现其他问题。将1添加到2147483647int将溢出到-2147483648

BTW你在浮点数达到256之前遇到问题。由于表示错误128f + 1e-5f == 128.00002,我怀疑这不是你想要的。

事实上,如果你不断添加1e-5f,在整数值/整数之间增加只需要65536次,而不是你可能预期的100,000次。

了解类型的限制非常有用。

答案 1 :(得分:1)

除了彼得的答案之外,这是一本必修课:What every computer scientist should know about floating-point arithmetic

基本上256.00001f会向下舍入到256f(255.00001f,在另一边,向上舍入到255.00002f)。您可以存储256.00002f,但它将向上舍入到256.00003f。第一次舍入 down 发生在256.00001f,这是你达到限制的地方,所以任何其他0.00001的添加都没有效果(每次添加它时,它将因舍入而被丢弃)。您可能已经注意到,由于指数和尾数的工作方式浮点数的第五个小数点并不是特别可靠,因此如果您想要更好的精度,请使用双精度数,但不要期望它们具有完美的准确性。