unity – Moving object parallel to another on path on 2d space


You are missing a lot of critical information…

If you want the black ball to follow the red ball in real time along its parallel path, you have a few options:

  1. If the red ball is always facing the direction of travel, you can set the black ball as a child of the red ball, but this will have noticeable incorrect black paths if the red path has sharp turns

  2. If the red ball is not always facing forward, you can use trigonometry to calculate calculate a position relative to the red ball position, i.e. left/right/above/below. This has the same problem as one that the black ball will move slightly backwards on tight turns.

If you are not “tracking” the red ball in real time and rather just have a set of points and you want to generate the black path from the red path data, you again have a few options:

  1. Copy the red path and translate it along the X/Y axes to get your black path. This won’t work for complex paths (imagine using this method on a U-turn shape).
  2. The most general (and most complicated) method is to have your path points saved as relative to either the previous point or a common origin. Consider these paths:

paths

Notice how different the “parallel”* black baths are from the red paths, depending on if the black paths are right or left of the red paths. What you need to to is for each point, calculate the angle of the turn. Of course, the angle will be different depending on if you are calculating a path that is on the right or left of the original. Find the bisection of the angle of each turn, calculate some distance along that line using trig (how ever “far” your new path is from your old path), and that’s your new point. Something like this:

public List<Vector2> calculateParallelPathRight(List<Vector2> originalPath, float distance){
    //trig magic here
} 

public List<Vector2> calculateParallelPathLeft(List<Vector2> originalPath, float distance){
    //trig magic here
} 

I’ll leave working through the trigonometry to you, as it is definitely not my strong suite and would take me a lot of trial and error. But this is how I would tackle the problem.

*P.S. Note that these lines aren’t technically mathematically parallel since the definition of parallel lines is two lines that are always the same distance apart, and that does not hold true at the corners. But I suspect this is what you want.