如何删除二维数组的角索引?

时间:2019-03-02 16:51:03

标签: javascript for-loop multidimensional-array three.js 2d

使用Three.js研究正向光线跟踪算法。刚刚使用2D数组创建了此示例。请注意,除了解析聚光灯的位置以外,此处不涉及聚光灯。

所以为了拍摄线条,我宣布:

startPoint = position of SpotLight
endPoint   = hard code for the first value

enter image description here

然后,我创建一个嵌套的for循环(17x17),并使用以下常规方法在每次迭代中创建ray:

forward_RT(){

    //Declare the start and end points of the first ray (startPoint never changes )
    var f_ray_startPoint = new THREE.Vector3(spotLight.position.x, spotLight.position.y, spotLight.position.z);
    var f_ray_endPoint = new THREE.Vector3(-490, 0, 495); //Hard Coding for 1st position of ray endPoint

    //Declare material of rays
    var ray_material_red = new THREE.LineBasicMaterial( { color: 0xff0000, opacity: 10} );
    var ray_material_yellow = new THREE.LineBasicMaterial( { color: 0xffff00 } );
    var ray_material_green = new THREE.LineBasicMaterial( { color: 0x00ff00 } );

    //Declare ray geometry
    var ray_geometry = new THREE.Geometry();
    ray_geometry.vertices.push( f_ray_startPoint );
    ray_geometry.vertices.push( f_ray_endPoint );

    //Declare values for 2d array grid
    var rows = 17;
    var cols = 17;
    var rayOffset = 60; //Offset of ray every X iteration

    for(var x=0; x<rows; x++){
        for(var z=0; z<cols; z++){
            //Declare a ray
            var f_ray = new THREE.Line(ray_geometry.clone(), ray_material_red);
            f_ray.geometry.vertices[1].x = f_ray_endPoint.x;

            scene_Main.add(f_ray); //Add ray into the scene
            f_ray_endPoint.x += rayOffset; //Add offset every new ray

            if(f_ray_endPoint.x >= 490){
                f_ray_endPoint.x -= (cols * rayOffset);
            }
        }
        f_ray_endPoint.z -= rayOffset;
    }
}

对于图形人员来说,我注意到Three.Line的材质上不透明。

有没有办法增加透明度?


主要问题

如何阻止迭代以便不绘制SpotLight的角?换句话说,我只想访问白色圆圈内的光线(SpotLights)。


1 个答案:

答案 0 :(得分:1)

如果要保持X,Y射线的谨慎网格并将其丢弃在圆之外,可以使用built-in method Vector2.distanceTo()。只需保持循环不变即可,但是要计算到圆心的距离,如果距离大于半径,请跳到下一个循环:

// Find the center of your circle
var center = new THREE.Vector2(centerX, centerZ);
// Assign radius of your circle
var radius = 17 / 2;
// Temp vector to calculate distance per iteration
var rayEnd = new THREE.Vector2();
// Result of distance
var distance = 0;

for (var x = 0; x < rows; x++) {
    for (var z = 0; z < cols; z++) {
        // Set this ray's end position
        rayEnd.set(x, z);
        // Calculate distance to center
        distance = rayEnd.distanceTo(center);

        // Skip loop if distance to center is bigger than radius
        if (distance > radius) {
            continue;
        } else {
            // Draw ray to x, z
        }
    }
}

一些建议:

  1. 我将使用单个LineSegments对象,而不是多个Line对象,以实现更快的渲染速度(Three.js在渲染一个具有多个顶点的对象时比在多个顶点很少的对象中更快)。
  2. li>
  3. 您可以围绕原点生成几何体(从-8到8),并计算到(0,0)的距离,然后然后position.x = 60将其位移60个单位,为简单起见。