The problem is that the website is laggy, becuase I am rendering thousands of objects. I am trying to solve this problem to get better UX.
I am importing 1 GLTF object (myModel). I also have a json file (myJson), which contains how much object and where should I place them. It also contains if the object needs to be rotated.
I think if i could merge all objects into 1, then the website would be not laggy.
How could I do that?
The whole js code:
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import myJson from './output.json';
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
0.1,
1000
);
camera.position.set(10, 10, 10);
const orbit = new OrbitControls(camera, renderer.domElement);
orbit.update();
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const assetLoader = new GLTFLoader();
let model = null
assetLoader.load("./myModel.gltf", function (gltf) {
model = gltf.scene;
let objects = []
if (model) {
for (let i = 0; i < myJson.length; i++) {
let XCoordinate = myJson[i].XCoordinate
let YCoordinate = myJson[i].YCoordinate
let myModel = model.clone()
objects.push(myModel)
objects[objects.length - 1].position.set(XCoordinate, 0, YCoordinate);
scene.add(objects[objects.length - 1]);
}
for (let i = 0; i < objects.length; i++) {
if (myJson[i].needRotate) {
objects[i].rotateX(Math.PI / 2)
} else {
objects[i].rotateX(-Math.PI / 2)
}
}
}
}, undefined, function (error) {
console.error(error);
});
function animate() {
renderer.render(scene, camera);
requestAnimationFrame(animate);
};
animate();
window.addEventListener('resize', function () {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});