Shorten a path, endpath condition question

Hey hey,

okay so here’s a question i can’t seem to figure out the answer to. Let’s say your character or an AI character can walk a distance of 8, but the target is 10 away. When you call StartPath() you of course, get the full path that is too long.

Now, even though i’m using a gridgraph, I don’t use nodes as the walk length, i use actual distance instead of # of nodes. So just reducing the # of nodes in vectorPath wouldn’t be good enough because of 8-way movement, reducing 1 node could equal 1.4 in distance.

So, is the question is: Is there an elegant way to take a path of length (distance, not nodes) x, and just grab the same path, but up to length y? (Where Y is always less than X) Or do i need to make a custom function that will go backwards Vector by vector, and reduce the distance between those two nodes until i reach the appropriate path length?

Can this somehow be accomplished with an EndPathCondirion?


Here is some code to do what you want.

public void Trim (List<Vector3> pts, float totalLength) {
    // Sum of the segment lengths so far
    var acc = 0f;
    // Walk through all segments in the path
    for (int i = 0; i < pts.Count - 1; i++) {
        // Length of this segment
        var length = Vector3.Distance(pts[i], pts[i+1]);
        // Will adding this segment increase the length
        // above the allowed total length?
        if (acc + length > totalLength) {
            // Fraction of this segment that should be included
            float fraction = (totalLength - acc)/length;
            // Adjust the segment to only keep a part of it
            pts[i+1] = Vector3.Lerp(pts[i], pts[i+1], fraction);
            // Remove the points that come after this segment
            pts.RemoveRange(i+2, pts.Count - (i+2));
        acc += length;

You cannot do it with an EndPathCondition because when that is called, it doesn’t know which path is the best path to the target, so you need to calculate the whole path and then trim it to the desired length.

yeah that’s basically what i came up with as well

1 Like