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.

alt text 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?


1 Answer 1


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;   
    DirX = (x2-x1)-width;
  if (abs(x2-x1) < abs(width + (x2-x1))
    DirX= width + (x2-x1);

enter image description here

In the same way (using HEIGTH) you can get DirY.

  • \$\begingroup\$ What points should i use in it? destination and target? and How would i determine which direction to go in? I'm confused. \$\endgroup\$ Aug 22, 2015 at 17:48
  • \$\begingroup\$ 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 \$\endgroup\$ Aug 25, 2015 at 18:25
  • \$\begingroup\$ Edited , the use of min , max where wrong. Added abs. \$\endgroup\$ Aug 26, 2015 at 7:01
  • \$\begingroup\$ Edit: I changed the code to that but it's still the same. It'll just follow the obvious path. pastebin.com/WigcWQhX \$\endgroup\$ Aug 26, 2015 at 8:19
  • \$\begingroup\$ 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. \$\endgroup\$ Aug 26, 2015 at 9:44

You must log in to answer this question.

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