[SOLVED] Distance calculation

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

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

Here is an example on how to use it:

1 Like

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

2 Likes

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.

2 Likes
2 Likes

OK, fixed. :smile:

4 Likes

thanks for adding this will but im getting a ā€˜distance is not a function errorā€™.

When i debug it doesnt show distance() as a function available top use, even though intellisense in the editor shows this and the api docs too.

This is because a new release of the engine has not been made since the function was added to the engine API. See here for commit history.

I expect weā€™ll do a release within the next week.

1 Like

okay that makes sense thanks :smiley:

1 Like