How to divide Vector2 to Vector2 Arrays?

445 views Asked by At

Today i am have a little question about Vector2. How i can devide them by int number, and store results as array. For easy imagine this task, for example we become to Positions and Waypoints.

public class Waypoint
{
  public int WaypointID {get; set;}
  public Vector2 position {get; set;}
}

For example, we have a StartX:100 StartY:100 and we need become to EndX:1500 EndY:1500 (2 Vectors here). So, for this cause, total numbers of waypoints should be hmm 3. Well:

public List<Waypoint> calculateWaypoints(Vector2 start, Vector2 end, int WaypointAmount)
{
 //they should return a list with 3 Waypoints in this cause
 List<Waypoint> points = new List<Waypoint>();
 //
 //what code should be here?
 //
 return points
}

I am looking for that, but tired to find any good solution. How i can solve this task?

1

There are 1 answers

0
Prescott On BEST ANSWER

How about something like this:

// For N waypoints between a start and end, we need N+1 segments

segments = WaypointAmount + 1;
xSeg = (end.x - start.x) / segments;
ySeg = (end.y - start.y) / segments;

// even though we have N+1 segments, adding the last segment would take
// us to the endpoint, not another waypoint, so stop when we have all
// our waypoints
for(var i = 1; i<=waypoints, i++)
{
    points.Add(new WayPoint { 
        WaypointId = i, 
        Vector2 = new Vector2(  
                            x = start.x+(xSeg*i),
                            y = start.y+(ySeg*i)});
}