以下是一些代码:
function polygon(x,y,r) {
var a = Math.PI*3/2;
var points = [];
var sides = []; // [[{x,y},{x,y}], ...]
var max = {x:0,y:0};
var min = {x:Infinity,y:Infinity};
ctx.beginPath();
for(var i = 0; i <= r.length; i++) {
var px = x + r[i]*Math.cos(a), py = y + r[i]*Math.sin(a);
if(i === 0) {
ctx.moveTo(px,py);
}
else {
ctx.lineTo(px,py);
sides.push([{x: points[i-1].x, y: points[i-1].y},{x: px, y: py}]);
}
if(px > max.x) {max.x = px;}
if(py > max.y) {max.y = py;}
if(px < min.x) {min.x = px;}
if(py < min.y) {min.y = py;}
points.push({x: px,y:py});
a += Math.PI*2/r.length;
}
points.pop();
ctx.strokeStyle = color;
ctx.lineWidth = 2;
ctx.stroke();
return {p:points, s:sides,max,min};
}
function collide(p1,p2) {
for(var i in p1.s) {
for(var j in p2.s) {
var t = intersect(p1.s[i],p2.s[j]);
if(t === 'collinear') {continue;}
if(t[0] <= 1 && t[0] >= 0 && t[1] <= 1 && t[1] >= 0) {
return true;
}
}
}
return false;
}
function intersect(s1,s2) {
if(((s2[1].x - s2[0].x)*(s1[0].y - s1[1].y) - (s1[0].x - s1[1].x)*(s2[1].y - s2[0].y)) === 0) {
return 'collinear';
}
var tA = ((s2[0].y - s2[1].y)*(s1[0].x - s2[0].x) + (s2[1].x - s2[0].x)*(s1[0].y - s2[0].y))/
((s2[1].x - s2[0].x)*(s1[0].y - s1[1].y) - (s1[0].x - s1[1].x)*(s2[1].y - s2[0].y)),
tB = ((s1[0].y - s1[1].y)*(s1[0].x - s2[0].x) + (s1[1].x - s1[0].x)*(s1[0].y - s2[0].y))/
((s2[1].x - s2[0].x)*(s1[0].y - s1[1].y) - (s1[0].x - s1[1].x)*(s2[1].y - s2[0].y));
return [tA, tB];
}
该代码用于碰撞两个多边形时,不适用于第四面。我不知道为什么会这样!
请帮忙...
我认为polygon for()
出了点问题。它没有添加第四个“边”,因为没有第五个点(或迭代)...