Skip to content

Instantly share code, notes, and snippets.

@antonkudin
Created December 14, 2022 16:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antonkudin/6824f764169a8eca257d859baf8468bf to your computer and use it in GitHub Desktop.
Save antonkudin/6824f764169a8eca257d859baf8468bf to your computer and use it in GitHub Desktop.
Adjust path so segments of path are more or less the same length
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mathfx
{
public static void normalizePoints(ref List<Vector2> path) {
float length = 0;
List<float> lengths = UnityEngine.Pool.GenericPool<List<float>>.Get();
lengths.Add(0);
for (int p = 1; p < path.Count; p++) {
length += (path[p] - path[p-1]).magnitude;
lengths.Add(length);
}
List<Vector2> newPath = UnityEngine.Pool.GenericPool<List<Vector2>>.Get();
int startI = 1;
newPath.Add(path[0]);
for (int i = 1; i < path.Count; i++) {
float value = length * ((float) i / (path.Count - 1));
Vector2 pt = Vector2.zero;
for (int p = startI; p < path.Count; p++) {
var l = lengths[p];
if (l > value) {
l -= value;
pt = path[p] - (path[p]-path[p-1]).normalized * l;
startI = p-1;
break;
}
else
pt = path[p];
}
newPath.Add(pt);
}
path.Clear();
path.AddRange(newPath);
newPath.Clear();
lengths.Clear();
UnityEngine.Pool.GenericPool<List<Vector2>>.Release(newPath);
UnityEngine.Pool.GenericPool<List<float>>.Release(lengths);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment