Java游戏的浮点计算没有返回正确的值

时间:2017-09-05 15:18:46

标签: java floating-point game-physics

我正在使用Java开发游戏,但计算中存在一些问题。我有velX和vely。当我按下' W'时会发生这种情况:

if(currentKeys[i] == "W") {
    velX += accel * Math.cos(angle);
    velY += accel * Math.sin(angle);
}

应该以正确的方向加速玩家。然后,当我调用updateVelocity时,我试着像这样衰减速度:

private void updateVelocity() {
    x += velX;
    y += velY;
    System.out.println("Velocity X = " + velX + " | Velocity Y = " + velY);
    velX = velX * deccel;
    velY = velY * deccel;
    System.out.println("Velocity X now = " + velX + " | Velocity Y now = " + velY);
}

accel = 2.5f;

deccel = 0.98f;

velX,velY,x,y都是花车。

然而System.out.println打印出来:

Velocity X = 1.8965478 | Velocity Y = 1.8243668
Velocity X now = 0.09482739 | Velocity Y now = 0.091218345
Velocity X = 1.8965478 | Velocity Y = 1.8243668
Velocity X now = 0.09482739 | Velocity Y now = 0.091218345
Velocity X = 1.8965478 | Velocity Y = 1.8243668
Velocity X now = 0.09482739 | Velocity Y now = 0.091218345
Velocity X = 1.8965478 | Velocity Y = 1.8243668
Velocity X now = 0.09482739 | Velocity Y now = 0.091218345

应该发生的是: 2.5 * 0.98 = 2.45 ,它会使速度衰减一点,然后再次加速,然后衰减 < / em>速度。我确保所涉及的所有变量都是浮点数,但没有任何变化。 System.out.println不是一个返回准确数字的函数吗?

编辑:我已经写出了一段应该重现问题的代码片段。使用它来保持简洁:

float accel, deccel;
float x, y, velX, velY;
float angle;

public Player(float x, float y) {
    this.x = x;     // the player's x position
    this.y = y;     // the player's y position
    velX = 0.0f;    // how much the player's x position will change this frame
    velY = 0.0f;    // how much the player's y position will change this frame
    accel = 2.5f;   // accel is a value that multiplies against the cos and sin of the angle in order to provide a directional increase in velX and velY.
    deccel = 0.98f; // deccel is a percentage value used to decay the player's velocity
    angle = 0.0f;   // set angle to a radians value between 0 and (2 * PI)
}

// update is kept barebones, since we only care about updating the velocity every frame in this example
void update(){
    updateControls();
    updateVelocity();
}

void updateVelocity(){
    x += velX;
    y += velY;
    velX = velX * deccel; // you can also use velX (or velY) *= deccel, I used the long version for a sanity check
    velY = velY * deccel;
}

// normally, update controls would be passed a series of strings, representing keystrokes, to process input logic with. However, for simplicity's sake, I've left out the controls, and have slotted in what happens when the player presses 'W'
void updateControls(){
    velX += accel * Math.cos(angle);
    velY += accel * Math.sin(angle);
}

如果您需要更多资料,请告诉我。

1 个答案:

答案 0 :(得分:0)

经过大量的实验,步骤追踪和头部刮擦,我找到了原因。我的游戏有一个功能,当玩家按下“S&#39”时,船速会更快地降低速度。因此,当玩家没有按下&#39; S&#39;时会发生这种情况:

if(!breaking) {
    deccel = 0.05f;
}

由于deccel的默认值已更改为0.98f,因此该代码片段现在应为:

if(!breaking) {
    deccel = 0.98f;
}

感谢所有人的帮助。我在编码和调试方面仍然变得越来越好,所以非常感谢。