2D光线追踪 - 填充视图

3
我的二维光线追踪器一直运行良好,直到我按角度(具体来说是弧度)对计算出的光线进行排序。我认为问题可能与 tan 函数的作用方式有关,但我不确定。如何以已知 x、y 的碰撞点和起始点对角度进行排序?我已经断断续续地在解决同样的问题两周了,几乎尝试了所有方法。
我现在可以在这里上传图片: This is when it works Thus When it doesnt(ignore the red box that got cut when screen capturing it works fine) 如果你想要尝试修改代码,这是有问题的代码:
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的谷歌文档(HTML代码在JS代码之后)。请点击以下链接查看:https://docs.google.com/document/d/12chxLiaj9gz-irlM0VdZs-BNoNqoMbz5AS0Dm0CpXfI/edit?usp=sharing
1个回答

2

首先要做的是澄清你的代码。
1)不需要按相反的顺序填充数组。
2)使用 atan2 - 我没有理解你处理弧度的方式...
3)缓存你将要重复使用的数组元素。
4)不要在每次排序时创建一个排序函数。
5)如果你按正确的顺序排序,就不需要倒序显示。

一旦情况更清晰了,我发现你在使用字段 3、5 或 6 作为点的 y 值有些奇怪。我认为只需要一个 y 数据的偏移量就足够了 ;-)

function sortByAngle(center) {
    for (var i = 0 ; i<viewFeild.length ; i++) {
        var thisField = viewFeild[i] ; 
        thisField[2] = Math.atan2( thisField[3] - center.y) 
                                    , (thisField[0] - center.x));
    };
    viewFeild.sort(sortOnSecondItem);
}

function fillView(pos) {
    for (var i = 0 ; i<viewFeild.length ; i++) {
        var thisField = viewFeild[i] ; 
        var nextField = (i==viewFeild.length-1) ?
                            viewFeild[0] 
                          : viewFeild[i+1] ;
        ctx.beginPath();
        ctx.moveTo(pos.x, pos.y);
        ctx.lineTo(thisField[0] + pos.x, thisField[5] + pos.y);
        ctx.lineTo(nextField[0] + pos.x, nextField[6] + pos.y);
        ctx.closePath();
        ctx.fillStyle = "rgba(100, " + 35 * i + ", 100, .6)";
        ctx.fill();
    };
}

function sortOnSecondItem(a,b) { return a[2] - b[2] }

嗯,这很奇怪,因为原始代码在y点使用了[1],如Google文档中所示,可能只是误写了,谢谢 :) - egg
那么上面的代码是否解决了问题呢(当我尝试时,仍然存在相同的问题,我认为这是因为我们仍在使用Math.atan2())? - egg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接