首页 > 解决方案 > 更有效的处理方法?

问题描述

我目前正在开发 Java 在线游戏的扩展。我目前正在处理传送,以了解玩家是否已经传送了一定距离,该距离可能来自distance参数。

问题是,我知道这是 CPU 上的一项超级密集的任务,即使我确实尝试从主线程中卸载它。

是否有更有效的方法来处理这个问题,或者我基本上必须重组整个事情?

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;
    }

}

标签: javamath

解决方案


我同意大卫齐默尔曼的观点,你可能不应该在计算中使用平方根。

而不是做

sqrt(dx^2 + dy^2 + dz^2) < sqrt(distance^2),

您可以使用:

dx^2 + dy^2 + dz^2 < distance^2

这对 CPU 更友好。但是,假设的辅助函数的名称不再适合了...


推荐阅读