1
\$\begingroup\$

I've got the following code snipped :

 var distanceFromDestinationSquared = (
                    Math.pow(this.orders.to.x - this.x, 2) +
                    Math.pow(this.orders.to.y - this.y, 2));
                if (distanceFromDestinationSquared < Math.pow(this.radius / game.gridSize, 2)) {
                    this.orders = { type: "float" };
                } else {
                    this.moveTo(this.orders.to);
                }

Summary :

  • x and y are always integers (-1, 0, 1, 2, .. )

  • The x and y coordinates of the destination and starting point get subtracted from each other, then the square number is taken and eventually those results are added to each other.

  • this.radius / game.gridSize gives you the equalent size related the coordinate system.

e.g game.gridSize = 20px - thus one field in the coordinate system is equalent to 20x20px

I've used this formula with the example of (2/2) as destination and (4/4) as starting point. As result I end up at the line if (distanceFromDestinationSquared < Math.pow(this.radius / game.gridSize, 2)) with 8 < (18 / 20)² = 8 < 0.81

What's the reason behind this apperently trivial formula of movement? Why is it important to take square number of the delta of x and y and add it together?

On one hand it avoides negative values but there would be other ways to deal more efficient with that issue.

Can someone point me to an explanation of this mathematical formula?

\$\endgroup\$
0

1 Answer 1

-1
\$\begingroup\$

This code snippet appears to simply compare two euclidean distances; the ordered distance and (what I'm assuming) is the maximum distance allowed (based on a movement radius?).

Euclidean distance is normally calculated as: sqrt(dx^2 + dy^2) ;(where dx is delta x and dy is delta y)

If you just want to compare two distances, to see which is greater, you would have this inequality:

sqrt(dx1^2 + dy1^2) > sqrt(dx2^2 + dy2^2)

Rather than performing the sqrt operation on both sides (which can be considered to be an expensive operation), you can skip it as sqrt(a) will always be greater than sqrt(b) if a>b (a, b > 0). Which results in:

dx1^2 + dy1^2 > dx2^2 + dy2^2

For a fast euclidean distance comparison.

\$\endgroup\$
1
  • \$\begingroup\$ euclidean distances, that's what I was looking for - thank you very much! The part with the radius is important, because the object which moves from A to B has a given radius which needs to be taken into consideration. \$\endgroup\$ Commented May 15, 2015 at 13:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .