1
\$\begingroup\$

I am making a game, where if you go through the right wall, you pop up on the left. I want to have a function that calculates the distance between two objects, where we can have a line that goes through the wall. For example, if the screen width is 100 and one object was at (0, 90) and another at (0, 10), the distance between them would be 20.

\$\endgroup\$
6
  • 1
    \$\begingroup\$ Maybe adding what you intend to do with that functionality, and what you have tried so far would help us give you better answers. \$\endgroup\$
    – Vaillancourt
    Feb 28, 2019 at 16:07
  • \$\begingroup\$ I tried have the positions go above the screen height/width and then use modulo when I write them on the screen, but then the distance function was way of. I don't see how I can have a distance function that works both on the edges of the screen, and when the objects are on the same place on the screen but have vastly different positions. \$\endgroup\$ Feb 28, 2019 at 16:12
  • 1
    \$\begingroup\$ Why do you need this distance? Is that for your AI? Do you have some kind of graph of places where the characters can go? \$\endgroup\$
    – Vaillancourt
    Feb 28, 2019 at 16:19
  • \$\begingroup\$ I am making boids (with some extra stuff), and I want them to flow from one side of the screen to the other. If I do this by changing their positions when they hit an edge, the normal distance function, wont find the old flock when it has gone throught the edge. The boid might therefore go in the wrong direction. \$\endgroup\$ Feb 28, 2019 at 16:25
  • 1
    \$\begingroup\$ And how are they navigating the maze otherwise? Because you could rely on this other infrastructure to get the value you want. \$\endgroup\$
    – Vaillancourt
    Feb 28, 2019 at 16:36

1 Answer 1

2
\$\begingroup\$

Basically, you need to check if the absolute distance on either plane is larger than half that screen dimension - if so, wrapping across the screen is faster than the standard distance on that axis:

dx = abs(x1 - x2);
if (dx > width/2)
   dx = width - dx;
dy = abs(y1 - y2);
if (dy > height/2)
   dy = height - dy;
dist = sqrt(dx*dx + dy*dy);
\$\endgroup\$

You must log in to answer this question.

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