如何将 Mesh 转换为 Object3D - three.js

问题描述 投票:0回答:0

我正在使用

Typescript
Webpack
。为了在
three.js
中创建 3D 地板,我使用了几个平面对象(100 个中有 100 个),并以无缝图像作为背景:

import {
    Scene,
    PerspectiveCamera,
    WebGLRenderer,
    TextureLoader,
    PlaneGeometry,
    MeshBasicMaterial,
    Mesh,
} from 'three'
import ground from './ground.jpg'


class Game {
    private readonly scene: Scene = new Scene()
    private readonly camera: PerspectiveCamera = new PerspectiveCamera()
    private readonly renderer: WebGLRenderer = new WebGLRenderer()

    constructor() {
        document.body.style.margin = "0"
        document.body.style.overflow = "hidden"
        document.body.appendChild(this.renderer.domElement)
        this.resizeCanvas()
        window.addEventListener("resize", this.resizeCanvas.bind(this))
        this.setupCamera()
        this.initiateGround()
        this.render()
    }

    private initiateGround() {
        const texture = new TextureLoader().load(ground);
        const geometry = new PlaneGeometry(1, 1);
        const material = new MeshBasicMaterial({map: texture});


        for (let i = 0; i < 100; i++) {
            for (let j = 0; j < 100; j++) {
                const plane = new Mesh(geometry, material);
                this.scene.add(plane);
                plane.position.set(i - 50, j - 50, 1);
            }
        }

        this.camera.position.z = 5;
        this.camera.rotation.x = .6;
    }


    private resizeCanvas(): void {
        this.renderer.setSize(window.innerWidth, window.innerHeight)
        this.camera.aspect = window.innerWidth / window.innerHeight
        this.camera.updateProjectionMatrix()
    }


    private setupCamera() {
        this.camera.fov = 75
        this.camera.near = .001
        this.camera.far = 100
        this.camera.updateProjectionMatrix()
    }


    private render() {
        requestAnimationFrame(this.render.bind(this))
        this.renderer.render(this.scene, this.camera)
    }
}

new Game()

为了更好的性能,我想到了只显示用户可以看到的平面。所以,我搜索了一下,发现了这个:

const intersects = new Raycaster().intersectObjects(theObject);
if ( intersects.length > 0 ) {
     // Hidden if index > 0
}

但这就是问题所在:当我想检查飞机是否对用户的相机可见时,出现此错误:

Argument of type 'Mesh<PlaneGeometry, MeshBasicMaterial>' is not assignable to parameter of type 'Object3D<Event>[]'.

这意味着我需要将网格转换为 Object3D。虽然我没有在互联网上找到任何东西。所以,我发布了这个问题。

我也非常感谢您对我代码其他部分的评论,因为它并不完美。

typescript three.js
© www.soinside.com 2019 - 2024. All rights reserved.