对象不在目标位置停止

时间:2017-06-06 22:20:25

标签: java swing mouselistener

我有一个游戏,你点击它,对象移动到它。它有时会停在目标上,但其他时间继续......我真的很困惑可能导致这个问题的原因。希望它不是简单的xD,因为我已经编写了一段时间了。任何想法/提示都可以随意留在评论中。 ;)

鼠标

@Override
public void mousePressed(MouseEvent e) {
    c.x = e.getX();
    c.y = e.getY();

    if (unit == false) {
        if (s == false) {
            for (Hazmat h1 : outbreak.hazmat) {
                if (c.getBounds().intersects(h1.bounds) || c.contains(h1.bounds)) {
                    selected = h1;
                    s = true;
                    unit = true;
                    Info.log("Selected unit. (First)");

                }
            }
        }
    } else {
        selected.re = true;

        Info.log("Sending unit to location!");
        targetX = e.getX();
        targetY = e.getY();
        selected.targetX = e.getX();
        selected.targetY = e.getY();

        float xSpeed = (targetX - (float) selected.x) / .1f;
        float ySpeed = (targetY - (float) selected.y) / .1f;
        float factor = (float) (1.0f / Math.sqrt(xSpeed * xSpeed + ySpeed * ySpeed));
        xSpeed *= factor;
        ySpeed *= factor;
        selected.velx = xSpeed;
        selected.vely = ySpeed;
        s = false;
        unit = false;
        Info.log("-----------------");
        Info.log("xSpeed: " + xSpeed);
        Info.log("ySpeed: " + ySpeed);
        Info.log("Factor: " + factor);
        Info.log("TargetX: " + targetX);
        Info.log("TargetY: " + targetY);
        Info.log("-----------------");
    }
}

对象

x += velx;
y += vely;
bounds.x = (int) x;
bounds.y = (int) y;

if (re == true) {
    if (bounds.x == targetX && bounds.y == targetY) {
        velx = 0;
        vely = 0;
        Info.log("[!] Target Point Reached [!]");
        re = false;
    }
}

1 个答案:

答案 0 :(得分:3)

检查两个浮点值是否相等通常会遇到非常小的精度误差问题。值bounds.xtargetX可能相隔0.00000001分,但您的支票bounds.x == targetX会失败。

相反,尝试这样的事情:

if ((bounds.x - targetX) < 0.0001 && (bounds.y - targetY) < 0.0001)