游戏中判断一群点可否构成凸多边形

下面的代码需要box2d!!!!!!!!!!!

import org.jbox2d.common.Vec2;

public class PolyonUtil {
 private static PolyonUtil instance;
 private float a;
 private float b;
 private boolean x_axis;
 private boolean y_axis;
 private float axis;
 float i;

 public static PolyonUtil getInstance() {
  if (instance == null) {
   instance = new PolyonUtil();
  }
  return instance;
 }

 public void setAB(Vec2 point1, Vec2 point2) {
  if (point1.x == point2.x) {
   if (point1.y != point2.y) {
    y_axis = true;
    axis = point1.x;
   }
  } else if (point1.y == point2.y) {
   if (point1.x != point2.x) {
    x_axis = true;
    axis = point1.y;
   }
  } else {
   y_axis = false;
   x_axis = false;
   a = (point1.y - point2.y) / (point1.x - point2.x);
   b = point1.y - point1.x * a;
  }
 }

 public byte getFlag(Vec2 point) {
  if (y_axis) {
   if (point.x > axis) {
    return 1;
   } else if (point.x < axis) {
    return -1;
   } else {
    return 0;
   }

  } else if (x_axis) {
   if (point.y > axis) {
    return 1;
   } else if (point.y < axis) {
    return -1;
   } else {
    return 0;
   }
  } else {
    i = point.y - a * point.x - b;
   if ((point.y - a * point.x - b) < 0) {
    return -1;
   } else if ((point.y - a * point.x - b) > 0) {
    return 1;
   } else {
    return 0;
   }
  }
 }
}

//下面的函数判断一群点是否构成凸多边形

public boolean isHull(Vec2[] mouseStroke){

int mouseStrokeLength=mouseStroke.length;

for (int i = 0; i < mouseStrokeLength; i+=2) {
   PolyonUtil.getInstance().setAB(mouseStroke[(i) % mouseStrokeLength],
     mouseStroke[(i + 1) % mouseStrokeLength]);
   for (int j = 0, k = 0; j < mouseStrokeLength; j++) {
    if (j == i || j == (i + 1)) {
     continue;
    } else {
     flag[k] = PolyonUtil.getInstance().getFlag(mouseStroke[j
       % mouseStrokeLength]);
     k++;
    }
   }
   for (int l = 0; l < flag.length - 1; l++) {
    if (flag[l] * flag[l + 1] < 0) {
     // ao 当是凹多边形时候
          return false;
    }
   }
  }

return true;

}

你可能感兴趣的:(游戏,J#)