Currently utilizing Typescript
alongside Webpack
. To create a 3D floor using three.js
, I have integrated multiple plane objects (100 in total) with a seamless image serving as their background:
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()
To optimize performance, my aim was to only display the planes visible to users. Upon researching, I came across this solution:
const intersects = new Raycaster().intersectObjects(theObject);
if ( intersects.length > 0 ) {
// Hide if index > 0
}
However, when attempting to determine if the plane is within view of the user's camera, I encountered this error:
Argument of type 'Mesh<PlaneGeometry, MeshBasicMaterial>' is not assignable to parameter of type 'Object3D<Event>[]'.
This indicates the need to convert the mesh to Object3D. Despite searching online, I couldn't find a suitable solution. Hence, I am reaching out to ask this question.
I welcome any feedback on other sections of my code, as it may not be flawless.