Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/417.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 求近似相等点(一种IndexOfPoint方法)_Javascript_Three.js - Fatal编程技术网

Javascript 求近似相等点(一种IndexOfPoint方法)

Javascript 求近似相等点(一种IndexOfPoint方法),javascript,three.js,Javascript,Three.js,使用three.js,我需要得到网格点,它在一个“fuzz”内几乎等于一个计算点。此计算点不是3.Vector2/3,它是具有x和y属性的常规对象。 该函数/方法用于递归函数和“实时”过程,因此必须对其进行优化 我发现的最简单的表达式如下。假设它是一个2D点,我提供了一个数组geometry.vertices,不需要计算距离: function IndexOfPoint ( pt, lst ) { var i = -1; var test = lst.some( function

使用three.js,我需要得到网格点,它在一个“fuzz”内几乎等于一个计算点。此计算点不是3.Vector2/3,它是具有x和y属性的常规对象。 该函数/方法用于递归函数和“实时”过程,因此必须对其进行优化

我发现的最简单的表达式如下。假设它是一个2D点,我提供了一个数组geometry.vertices,不需要计算距离:

function IndexOfPoint ( pt, lst ) {
    var i = -1;
    var test = lst.some( function ( p ) {
        i++;
        return ( Math.abs( p.x - pt.x ) < 1E-12 ) && ( Math.abs( p.y - pt.y ) < 1E-12 );
    });
    return test? i: -1;
}
这是可行的,但我很快就做到了,我想知道是否有一个最好最快的方法。。。请不要额外的库,只有纯js


提前谢谢

看起来很适合我。您可能可以跳过索引变量i的增量,因为当前索引已作为第二个参数提供给回调,如Array.prototype中所示。一些functionelement,index,Array{…}:

function IndexOfPoint ( pt, lst ) {
    var i = -1;
    lst.some( function ( p, idx ) {
        if ( ( Math.abs( p.x - pt.x ) < 1E-12 ) && ( Math.abs( p.y - pt.y ) < 1E-12 ) ) {
            i = idx;
            return true;
        }
        else {
            return false;
        }
    });
    return i;
}

我不熟悉three.js,但是如果列表被排序,并且网格是统一的,那么您可能能够立即获得最近向量的索引,并简单地测试该索引。例如:

function IndexOfPoint (pt, list) {
    // assuming the list of points is sorted going from left to right, top to bottom
    var index = Math.floor((pt.x - offsetX) * scaleX) + gridWidth * Math.floor((pt.y - offsetY) * scaleY);

    var candidatePoint = list[index];

    if (candidatePoint && (Math.abs(pt.x - candidatePoint.x) < 1E-12) && (Math.abs(pt.y - candidatePoint.y) < 1E-12) {
      return index;
    } else {
      return -1;
    }
}