我有一个Vector2的ArrayList(Vector2是一个包含x和y坐标的对象),它包含一组在绘制时形成形状的顶点。但是,它们放入ArrayList的方式是乱序的。例如,起始Vector2点是索引0但是最接近的下一个点是索引4.我的目标是使另一个Vector2的ArrayList以某种方式对Vector2进行排序,使得起点为索引0,下一个最近的点是索引1,接下来是索引2,等等。这是正在发生的事情的图像。
图像显示正在发生的事情,但绿色箭头显示我想要发生的事情。绿点是起点。
所以我需要的是一旦创建并订购了新的ArrayList,它应该如下所示:
所以这里是我认为可以做到的代码:
public Array<Vector2> orderedVertices;
private void cleanVertices(Array<Vector2> originalVertices){
//This will be the Array containing ordered vertices
orderedVertices = new Array<Vector2>();
//Copy vertices of unsorted Array in a new Array
Array<Vector2> verticesOfImage = originalVertices;
//Add a random vertice to begin with (starting point)
orderedVertices.add(verticesOfImage.get(1));
//For breaking loop
int originalArraySize = originalVertices.size;
for(int i = 0; i < orderedVertices.size; i++){
//Index to be compared, meaning to find closest vertice around this vertice
int indexOfCompare = i;
//Get a distance for reference //Random point to check
double currentDistance = MathFactory.distance(orderedVertices.get(indexOfCompare), verticesOfImage.get(0));
//If we found a closest vertice, add to ordered pair and remove from original
// So we don't go backwards
if(getClosest(verticesOfImage, indexOfCompare, currentDistance) != -1){
orderedVertices.add(verticesOfImage.removeIndex(getClosest(verticesOfImage, indexOfCompare, currentDistance)));
}
//If not, then the original 'currentDistance' check was the closest vertice
else
orderedVertices.add(verticesOfImage.removeIndex(0));
//Stop checks, ordered pair fully populated
if(orderedVertices.size == originalArraySize)
break;
}
}
public int getClosest(Array<Vector2> vertices, int checkedIndex, double currentDistance){
//This is used to find the closest vertice, defaulted to -1 for condition statements
int correctIndex = -1;
for(int k = 0; k < vertices.size; k++){
//Make sure to not check same Vector2
if(vertices.get(k).x == orderedVertices.get(checkedIndex).x && vertices.get(k).y == orderedVertices.get(checkedIndex).y){
continue;
}
if(MathFactory.distance(orderedVertices.get(checkedIndex), vertices.get(k)) < currentDistance){
correctIndex = k;
currentDistance = MathFactory.distance(orderedVertices.get(checkedIndex), vertices.get(k));
}
}
return correctIndex;
}
此代码非常接近工作,这是一个解释出错的图像。
我理解那个不起作用的那个看起来不那么顺利,但唯一真正的问题是这些线条在最后发出并经过身体的事实。我似乎无法弄清楚为什么会发生这种情况或如何解决它。任何有关这方面的帮助都非常感谢!谢谢!