gpt4 book ai didi

java - 物体没有停在目标位置

转载 作者:行者123 更新时间:2023-11-29 04:29:29 25 4
gpt4 key购买 nike

我有一个游戏,你点击它,物体就会移动到它上面。它有时会停在目标处,但有时会继续前进……我真的很困惑可能导致此问题的原因。希望这不是一件容易的事 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;
}
}

最佳答案

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

相反,尝试这样的事情:

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

关于java - 物体没有停在目标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44400618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com