变量总是" 0.0"

时间:2015-02-12 20:42:28

标签: java android time

此代码以循环方式运行,但变量d始终为" 0.0" (用断点测试)。

private static float startTime;

private boolean attackCore(Canvas canvas, RectF eCastle, float width, float height) {
    if (startTime == -1) startTime = System.currentTimeMillis();

    randomX = new Random((long) width);
    randomY = new Random((long) height);
    float x2 = randomX.nextFloat() + eCastle.right;
    float y2 = randomY.nextFloat() + eCastle.top;

    double d = ((System.currentTimeMillis() - startTime) / 1000) * 30;

    float[] c = Game.moveTo(x1, y1, x2, y2, d);
    if (d >= sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2))) {
        canvas.drawBitmap(arrow, x2, y2, null);
        startTime = -1;
        return true;
    }
    canvas.drawBitmap(arrow, c[0], c[1], null);
    return false;
}

此处moveTo中的Game

public static float[] moveTo(float xA, float yA, float xB, float yB, double dAC) {
    double dAB = sqrt(pow(xA - xB, 2) + pow(yA - yB, 2));

    float xC = (float) (xA + (xB - xA)*dAC/dAB);
    float yC = (float) (yA + (yB - yA)*dAC/dAB);

    return new float[] {xC, yC};
}

我尝试将变量设为非静态并将其值设置为-1。还必须说代码在另一个类中工作,所以我有点迷失了错误的位置,如果你需要另一部分代码,请问我。

2 个答案:

答案 0 :(得分:1)

System.currentTimeInMillis()很长

(long - long)/ int = int 如果currentTime - startTime / 1000,则currentTime - startTime<1000 = 0始终

你需要将它们转换成花车

(float)(currentTime - startTime)/ 1000.f

答案 1 :(得分:1)

这种情况正在发生,因为当您将System.currentTimeMillis()long转换为float时,您会失去精确度。对于通常返回System.currentTimeMillis()的值,连续float值的间隔比整数要大得多。

您应该startTime作为long。可能d也应该是long。当你进行除法时,请确保在除法之前进行乘法运算,以便尽可能晚地进行舍入。

long startTime;
// ... assign startTime to whatever it's supposed to be
long d = (System.currentTimeMillis() - startTime) * 30 / 1000;