我的 2d 光线追踪器一直运行良好,直到我按角度(特别是弧度)对计算出的光线进行排序。我认为这与 tan 的行为方式有关,但我不确定。用已知的 x,y 对碰撞和原点的角度进行排序的最佳方法是什么?我已经断断续续地解决同一个问题 2 周,并且几乎尝试了所有方法。
我现在可以在这里上传图片:
如果你想摆弄它,这是有罪的代码:
function sortByAngle(pos){
for (var i = viewFeild.length - 1; i >= 0; i --) {
viewFeild[i][3] = Math.atan((viewFeild[i][4]-pos.y)/(viewFeild[i][0]-pos.x));
if(viewFeild[i][5]<pos.y)
viewFeild[i][6] = viewFeild[i][7]*-1-4;
if (viewFeild[i][8]<0) {viewFeild[i][9]+=2};
};
viewFeild.sort(function(a,b){return a[2]-b[2]});
}
function fillView(pos) {
for (var i = viewFeild.length - 1; i >= 0; i--) {
//console.log(i+" "+viewFeild[i][10] + " " + viewFeild[(i+1)%viewFeild.length][11])
//console.log(viewFeild.length)
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
ctx.lineTo(viewFeild[i][0]+pos.x, viewFeild[i][12]+pos.y);
ctx.lineTo(viewFeild[(i+1)%viewFeild.length][0]+pos.x, viewFeild[(i+1)%viewFeild.length][13]+pos.y);
ctx.closePath();
ctx.fillStyle = "rgba(100, " + 35*i + ", 100, .6)";
ctx.fill();
};
}
这是带有整个js代码和html的google doc(html在js之后) https://docs.google.com/document/d/12chxLiaj9gz-irlM0VdZs-BNoNqoMbz5AS0Dm0CpXfI/edit?usp=sharing