Reputation: 25
I am currently working on an extension for an online game in Java. I am currently handling teleportation to know whether a player has teleported a certain distance that can be from the distance
parameter.
The thing is, I know this is a super intensive task on the CPU, even if I did attempt to offload it from the main thread.
Would there be any more efficient way of handling this, or would I basically have to restructure the entire thing?
this.square
is just Math.pow();, this.sqrt
is Math.sqrt();,
this.hypot
is as following:
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);
}
This is how I am checking whether the player teleported
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;
}
}
Upvotes: 0
Views: 63
Reputation: 112
I agree with David Zimmerman, you should probably not use the square root in your computation.
Instead of doing
sqrt(dx^2 + dy^2 + dz^2) < sqrt(distance^2),
you can use:
dx^2 + dy^2 + dz^2 < distance^2
which is much more cpu friendly. The name of your auxiliary function for the hypothenuse wouldn't fit anymore though...
Upvotes: 1