游戏中判断一群点可否构成凸多边形
下面的代码需要box2d!!!!!!!!!!!
import org.jbox2d.common.vec2;
public class polyonutil {<br>?private static polyonutil instance;<br>?private float a;<br>?private float b;<br>?private boolean x_axis;<br>?private boolean y_axis;<br>?private float axis;<br>?float i;
?public static polyonutil getinstance() {<br>??if (instance == null) {<br>???instance = new polyonutil();<br>??}<br>??return instance;<br>?}
?public void setab(vec2 point1, vec2 point2) {<br>??if (point1.x == point2.x) {<br>???if (point1.y != point2.y) {<br>????y_axis = true;<br>????axis = point1.x;<br>???}<br>??} else if (point1.y == point2.y) {<br>???if (point1.x != point2.x) {<br>????x_axis = true;<br>????axis = point1.y;<br>???}<br>??} else {<br>???y_axis = false;<br>???x_axis = false;<br>???a = (point1.y - point2.y) / (point1.x - point2.x);<br>???b = point1.y - point1.x * a;<br>??}<br>?}
?public byte getflag(vec2 point) {<br>??if (y_axis) {<br>???if (point.x > axis) {<br>????return 1;<br>???} else if (point.x < axis) {<br>????return -1;<br>???} else {<br>????return 0;<br>???}
??} else if (x_axis) {<br>???if (point.y > axis) {<br>????return 1;<br>???} else if (point.y < axis) {<br>????return -1;<br>???} else {<br>????return 0;<br>???}<br>??} else {<br>??? i = point.y - a * point.x - b;<br>???if ((point.y - a * point.x - b) < 0) {<br>????return -1;<br>???} else if ((point.y - a * point.x - b) > 0) {<br>????return 1;<br>???} else {<br>????return 0;<br>???}<br>??}<br>?}<br>}
//下面的函数判断一群点是否构成凸多边形
public boolean ishull(vec2[] mousestroke){
int mousestrokelength=mousestroke.length;
for (int i = 0; i < mousestrokelength; i+=2) {<br>???polyonutil.getinstance().setab(mousestroke[(i) % mousestrokelength],<br>?????mousestroke[(i + 1) % mousestrokelength]);<br>???for (int j = 0, k = 0; j < mousestrokelength; j++) {<br>????if (j == i || j == (i + 1)) {<br>?????continue;<br>????} else {<br>?????flag[k] = polyonutil.getinstance().getflag(mousestroke[j<br>???????% mousestrokelength]);<br>?????k++;<br>????}<br>???}<br>???for (int l = 0; l < flag.length - 1; l++) {<br>????if (flag[l] * flag[l + 1] < 0) {<br>?????// ao 当是凹多边形时候<br>??????????return false;<br>????}<br>???}<br>??}
return true;
}