/// <summary> /// from a given path (sets of points), get the closest position of pos from this path, and return the /// current percentage inside /// </summary> /// <param name="pos"></param> /// <param name="chunkPath"></param> /// <param name="precision"></param> /// <returns></returns> public static float GetPercentageFromPosToChunkPath(Vector3 pos, Vector3[] chunkPath, float precision = 1f) { if (chunkPath == null || chunkPath.Length == 0) { //Debug.LogWarning("out of bounds"); return(0); } float percent = 0f; float lenghtPath = ExtMathf.GetLenghtOfPath(chunkPath); Vector3[] closestPointInLines = new Vector3[chunkPath.Length]; float[] lenghtAllLine = new float[chunkPath.Length]; for (int i = 0; i < closestPointInLines.Length - 1; i++) { ExtLine line = new ExtLine(chunkPath[i], chunkPath[i + 1]); closestPointInLines[i] = line.ClosestPointTo(pos); lenghtAllLine[i] = (float)line.GetLenght(); } int indexFound = -1; Vector3 closestPoint = ExtMathf.GetClosestPoint(pos, closestPointInLines, ref indexFound); if (indexFound >= lenghtAllLine.Length) { //Debug.LogWarning("out of bounds"); return(0); } float lenghtLineClose = lenghtAllLine[indexFound]; Vector3 veccA = chunkPath[indexFound]; int indexPlusOne = indexFound + 1; if (indexPlusOne >= chunkPath.Length) { indexPlusOne = 0; } Vector3 veccB = chunkPath[indexPlusOne]; float percentageAlongCLosestLine = ExtMathf.GetPercentageAlong(veccA, veccB, closestPoint); float lenghtTraveledInThisLine = (percentageAlongCLosestLine * lenghtLineClose) / 1f; //add lenght, from start to the line found float lenghtFromZeroToThisPoint = 0f; for (int i = 0; i < indexFound; i++) { lenghtFromZeroToThisPoint += lenghtAllLine[i]; } lenghtFromZeroToThisPoint += lenghtTraveledInThisLine; //then add the additionnal percentage percent = (lenghtFromZeroToThisPoint * 100f) / lenghtPath; //Debug.Log("ChunkLenght: " + lenghtPath + ", lenght closest line: " + lenghtLineClose + ", percent along this line: " + percentageAlongCLosestLine // + "lenght From Zero to this point: " + lenghtFromZeroToThisPoint + ", total percent: " + percent); return(percent); }