如何检查VERTEX ARRAY是顺时针方向?

时间:2012-05-05 08:53:01

标签: java android

解决,使用此代码:

if ( !isClockwise(TempVectArray) ) { Collections.reverse(TempVectArray); }

...

private boolean isClockwise(ArrayList<Vec2> arl){
    Iterator<Vec2> it = arl.iterator();
    Vec2 pt1 = (Vec2)it.next();
    Vec2 firstPt = pt1;
    Vec2 lastPt = null;
    double area = 0.0;
    while(it.hasNext()){
        Vec2 pt2 = (Vec2) it.next();
        area += (((pt2.x - pt1.x) * (pt2.y + pt1.y)) / 2);
        pt1 = pt2;
        lastPt = pt1;
    }
    area += (((firstPt.x - lastPt.x) * (firstPt.y + lastPt.y)) / 2);
    return area < 0;
}

假设我从用户点击屏幕上获得一个顶点数组,但需要它是顺时针方向。

也许您知道一些标准方法来检查它是否是顺时针方向,如果不是,那么顺时针方向?

enter image description here

谢谢!

2 个答案:

答案 0 :(得分:2)

一种方法是首先计算平均点,然后按角度对其周围的所有内容进行排序。应该是这样的:

public static void sortPointsClockwise(ArrayList<PointF> points) {
    float averageX = 0;
    float averageY = 0;

    for (PointF point : points) {
        averageX += point.x;
        averageY += point.y;
    }

    final float finalAverageX = averageX / points.size();
    final float finalAverageY = averageY / points.size();

    Comparator<PointF> comparator = new Comparator<PointF>() {
        public int compare(PointF lhs, PointF rhs) {
            double lhsAngle = Math.atan2(lhs.y - finalAverageY, lhs.x - finalAverageX);
            double rhsAngle = Math.atan2(rhs.y - finalAverageY, rhs.x - finalAverageX);

            // Depending on the coordinate system, you might need to reverse these two conditions
            if (lhsAngle < rhsAngle) return -1;
            if (lhsAngle > rhsAngle) return 1;

            return 0;
        }
    };

    Collections.sort(points, comparator);
}

public static void sortPointsCounterClockwise(ArrayList<PointF> points) {
    sortPointsClockwise(points);
    Collections.reverse(points);
}

答案 1 :(得分:0)

您拥有节点的序列号和位置。获取在移动中保持x和y变化的运动。剩下要做的就是定义一个控制结构,例如:

if(movement_before is "up")
    movement should-be "up" or "up-right"
if(movement_before is "up-left")
    movement should-be "up" or "up-left" or "up-right"
etc..