# Find alternate shortest paths in Unity

I'm developing a game in Unity. It's a simple game where the rocket has to reach the point where the player touches on the screen. The movement of the rocket is physics based. When the rocket goes off screen on right side, it appears on left side and when it goes off on left side, it appears on right side. Similar for vertical axis. In the picture above, the user touches on the bottom right corner. The rocket could either rotate and go there (Path 1) or it would directly go up left off the screen and appear on bottom right corner and reach there(Path 2). I want to implement the Path 2. How would it calculate the distances and determine the shorter path and then proceed in that direction?

Euclidean distante = sqrt (dx * dx + dy * dy), for your distance you need to define dx as min(abs(x2-x1),screenwidth-abs(x2-x1)) same thing for dy.

Usualy the direction vector is Pt - Pm (Position vector target - Position vector missile). In your case you can define Direction vector x component as

if (x2-x1)>=0
if (abs(x2-x1) < abs((x2-x1)-width))
DirX = x2-x1;
else
DirX = (x2-x1)-width;
else
if (abs(x2-x1) < abs(width + (x2-x1))
DirX=x2-x1;
else
DirX= width + (x2-x1); In the same way (using HEIGTH) you can get DirY.

• What points should i use in it? destination and target? and How would i determine which direction to go in? I'm confused. Aug 22, 2015 at 17:48
• This is what i changed my code to but the behavior is still the same. It won't take the shorter path instead it just takes the obvious path pastebin.com/b0rx1wKa Aug 25, 2015 at 18:25
• Edited , the use of min , max where wrong. Added abs. Aug 26, 2015 at 7:01
• Edit: I changed the code to that but it's still the same. It'll just follow the obvious path. pastebin.com/WigcWQhX Aug 26, 2015 at 8:19
• One thing i want to point out is that 0,0 is the center of the world since all the objects have Pivot point at center in Unity. So, the world width would be -Screen.width/2 to Screen.width/2, not 0 to Screen.width. Aug 26, 2015 at 9:44