光线投射器的三个 js 性能不好

bad three js performance with raycasters

所以我一直在尝试在三个 js 中进行光线投射,但我 运行 在 Firefox 和 chrome 中遇到了可怕的性能问题(但其他原因导致 chrome 相机无法正常工作乐队,尽管它是一个小型本地游戏)无论如何,当我将这段代码添加到动画循环时

                var intersects = raycaster.intersectObjects(sceneObjects);

                if (intersects.length > 0) {
                       var firstIntersectedObject  = intersects[0];
                       console.log(intersects[0].object.userData)
                       console.log(intersects[0].object.userData.glow )
                       if (intersects[0].object.userData.glow === 'true'){
                           console.log("GLOW")
                       }else{
                           console.log("NO!")
                       }
                       //intersects[0].object.material.wireframe = true
                       // this will give you the first intersected Object if there are multiple.
                    }

我的游戏开始变得卡顿,我不知道为什么有任何指示

不要在 每个 帧上进行光线投射,相反,您应该每隔一段时间进行光线投射。您可以使用 setTimeoutsetInterval 或检查更新循环中的时间。

onUpdate() {
    // Code that runs once per frame

    // Check that we've waited long enough to raycast
    if (Date.now() - this.lastRaycast > this.raycastInterval && this.qRaycast) {
        this.handleRaycast();
        this.lastRaycast = Date.now();
        this.qRaycast = false;
    }
    requestAnimationFrame( () => this.onUpdate() );
}

我也只在鼠标移动时排队光线投射(如果鼠标不移动则没有理由保持光线投射)并且因为我在我的项目中有平移,我在平移移动期间禁用光线投射以防止移动期间的任何抖动.

// Event Handlers
// Record mouse position for raycast
onMouseMove(e) {
    this.mouse.x = (e.clientX / window.innerWidth ) * 2 - 1;
    this.mouse.y = -((e.clientY - 50) / window.innerHeight ) * 2 + 1;

    // If we are panning, don't queue a raycast
    this.qRaycast = !this.mouseState.held;
}

// My app has panning, and we don't wanna keep raycasting during pan
onMouseDown(e) {
    this.mouseState.lastClick = Date.now();
    this.mouseState.clicked = false;
    this.mouseState.held = true;
}

onMouseUp(e) {
    this.mouseState.held = false;
}

然后我们处理光线投射:

// Like lasers, but virtual.
handleRaycast() {
    let hits = null;
    let hitcount = 0;
    if (UI.raycast && meshObj) {
        this.raygun.setFromCamera(this.mouse, this.camera);
        hits = this.raygun.intersectObject(meshObj, false);
        hitcount = hits.length;
    }

    if (hitcount > 0) {
        // Do stuff with the raycast here
    }
}

如果您仍然遇到性能问题,那么您可能想研究分解该循环函数,以便在 XXms 后它会中断以让 UI 更新,然后在下一帧继续更新:

比如我把所有的命中排序,找到离鼠标最近的点:

// Optimization
let startTime = 0;
let maxTime = 75; // max time in ms
let dist = 1;
let hitIndex;
let i = 0;

function findClosest() {
    return new Promise((resolve) => {
        function loop() {
            startTime = performance.now();
            while (i < hitcount) {
                // Break loop after maxTime
                let currentTime = performance.now();
                if ((currentTime - startTime) > maxTime) {
                    console.log('Loop exceeded max time: ' + 
                        (currentTime - startTime).toFixed(3) );
                    startTime = currentTime;
                    break;
                }

                // I am finding the raycast point that is closest to the cursor
                dist = hits[i].distanceToRay;
                if (dist < smallestDist) {
                    smallestDist = dist;
                    smallestPointIndex = hits[i].index;
                }
                i++;
            }

            if (i < hitcount) {
                // Allow the UI to update, then loop
                setTimeout(loop, 1);
            } else {
                resolve(smallestPointIndex);
            }
        }
        loop();
    });
}

findClosest().then(result => {
    // do something with the result here
}

此外,这些评论也是减少光线投射对象数量的好建议。