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?


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.

| improve this answer | |
  • \$\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\$ – Jaspreet Singh Aug 22 '15 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\$ – Jaspreet Singh Aug 25 '15 at 18:25
  • \$\begingroup\$ Edited , the use of min , max where wrong. Added abs. \$\endgroup\$ – dnk drone.vs.drones Aug 26 '15 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\$ – Jaspreet Singh Aug 26 '15 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\$ – Jaspreet Singh Aug 26 '15 at 9:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.