[SOLVED] Distance calculation


#1

is there a Math.Distance or Vec3.Distance or any other method to check the distance between 2 points?


#2

There is a length method in the pc.Vec3 class.

Here is an example on how to use it:


#3

I would rather not suggest sub/length as polyfill for a distance function/method, since it modifies the vector itself, but distance is purely functional. It just happens to not mess anything up in the example because getTranslation allocates a new vector every time.

Something like that should be in PC itself:

// As static functions:

pc.Vec3.Distance = function(a, b) {
	var dx = b.x - a.x;
	var dy = b.y - a.y;
	var dz = b.z - a.z;
	return Math.sqrt(dx * dx + dy * dy + dz * dz);
}

pc.Vec3.DistanceSquared = function(a, b) {
	var dx = b.x - a.x;
	var dy = b.y - a.y;
	var dz = b.z - a.z;
	return dx * dx + dy * dy + dz * dz;
}

// As methods:

pc.Vec3.prototype.distanceTo = function(b) {
	var dx = b.x - this.x;
	var dy = b.y - this.y;
	var dz = b.z - this.z;
	return Math.sqrt(dx * dx + dy * dy + dz * dz);
}

pc.Vec3.prototype.distanceToSquared = function(b) {
	var dx = b.x - this.x;
	var dy = b.y - this.y;
	var dz = b.z - this.z;
	return dx * dx + dy * dy + dz * dz;
}

console.log("a", a, "b", b)
console.log("pc.Vec3.Distance(a, b) = ", pc.Vec3.Distance(a, b));
console.log("pc.Vec3.DistanceSquared(a, b) = ", pc.Vec3.DistanceSquared(a, b));
console.log("a.distanceTo(b) = ", a.distanceTo(b));
console.log("a.distanceToSquared(b) = ", a.distanceToSquared(b));

Often you don’t need the real distance, just the squared number is enough for e.g. distance checking, that avoids the slow Math.sqrt: a.distanceToSquared(b) < minDistance * minDistance


#4

Thanks for sharing these methods @kungfooman.

To add on that, for any time sensitive method, especially those running every frame you should avoid allocating new objects.

For math operations what you usually would do is allocate some temp vector objects on init time and reuse them by setting them to the new value before any math operation.


#5

#6

OK, fixed. :smile: