我目前正在开发 Java 在线游戏的扩展。我目前正在处理传送,以了解玩家是否传送了可以从 distance
参数得出的特定距离。
问题是,我知道这是 CPU 上的 super 密集任务,即使我确实尝试从主线程卸载它。
是否有更有效的方法来处理这个问题,或者我基本上必须重组整个事情?
this.square
只是 Math.pow();, this.sqrt
就是 Math.sqrt();,
this.hypot
如下:
default double hypot(double... numbers) {
double squaredSum = 0.0;
int length = numbers.length;
int count = 0;
while (count < length) {
double number = numbers[count];
squaredSum += Math.pow(number, 2.0);
++count;
}
return this.sqrt(squaredSum);
}
这就是我检查玩家是否传送的方式
public boolean anyNear(CustomLocation location, double distance) {
if (!this.locations.isEmpty()) {
Iterator<TeleportSnapshot> iterator = this.locations.iterator();
if (iterator.hasNext()) {
TeleportSnapshot teleport = iterator.next();
double deltaX = location.getX() - teleport.x;
double deltaY = location.getY() - teleport.y;
double deltaZ = location.getZ() - teleport.z;
while (!(this.hypot(deltaX, deltaY, deltaZ) < this.sqrt(this.square(distance)))) {
if (iterator.hasNext()) {
teleport = iterator.next();
deltaX = location.getX() - teleport.x;
deltaY = location.getY() - teleport.y;
deltaZ = location.getZ() - teleport.z;
} else {
return false;
}
}
return true;
} else {
return false;
}
} else {
return false;
}
}
最佳答案
我同意 David Zimmerman 的观点,你可能不应该在计算中使用平方根。
而不是做
sqrt(dx^2 + dy^2 + dz^2) < sqrt(distance^2),
您可以使用:
dx^2 + dy^2 + dz^2 < distance^2
这对 CPU 更友好。不过,假设的辅助函数的名称不再合适了......
关于java - 有更有效的方法来处理这个问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59993370/