wrapf difference operations

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ERGMANJr

I am trying to come up with a way to make the high range of numbers interact with the low range of numbers in a wrapf function. For more context, I am developing a game that has a wrapping world.

This world goes from 0-10240 pixels on the x axis. A distance between 10230 and 10 is normally 10220. In my wrapping world, the distance is actually only 20.

Does anyone know how to do this using math?

:bust_in_silhouette: Reply From: ERGMANJr

As I was writing the question it actually came to me. But I thought I would post the question and the answer anyway for anyone else who is doing this:

Description: I had a use for knowing the actual distance from the player to the asteroids in a wrapping world. Distance gets weird at the edges.

ie | The x-axis is 0-10240. The difference between 10230 and 10 should be 20, not 10220. ‘min(x2-x1, x1 + (xwrap-x2))’ is a function I came with to solve this problem. x1 and x2 are the 2 x-coordinates. xwrap is the x size of the world. It is important for x1 and y1 to always be the smaller number!!!

INPUT:

  1. playerPos (Vector2) - the players position in the world
  2. pos2 (Vector2) - the thing we are checking distance to from the palyer
  3. xwrap: x-size of the world (10240 in the above scenario)
  4. ywrap: y-size of the world

Output:

  1. Vector2 containing the distance on the x axis and the y axis from the player to the thing in question.

NOTE: More can be done to make this a radial distance, but I prefer the rectangular coordinates here.

Here is the code in gdscript:

func check_distance_in_wrapping_world(playerPos, pos2, xwrap, ywrap):
	var x1 = min(playerPos.x, pos2.x)
	var x2 = max(playerPos.x, pos2.x)
	var y1 = min(playerPos.y, pos2.y)
	var y2 = max(playerPos.y, pos2.y)
	var xdif = min( x2-x1 , x1 + (xwrap-x2) )
	var ydif = min( x2-x1 , y1 + (ywrap-y2) )
	return Vector2(xdif, ydif)

Math explained: Distance can be calculated one of two ways in a wrapped world, normally or across zero. To calculate normally, subtract the bigger number from the smaller number. To calculate across zero, you add the small number with the difference of x-world-size to the big number. The minimum of these two is the actual distance.
NOTE: In this calculation, the smaller number always has to be assigned to x1 & y1.