Не получается изменить 3D модель по клику на кнопку в реальном времени. Изначально грузится дефолтная модель из массива.
Для этого сделал переменную var counter = 0;
он отвечает за номер модели в массиве.
После написал функцию которая перезаписывает её значение. Предварительно пред загрузил все модельки при загрузке страницы. Подскажите, как можно заменить(перерисовать) модель в realtime без перезагрузки страницы? Т.е, нужно по клику на кнопку менять объект на другой
import * as THREE from './three.module.js';
import { OBJLoader} from './OBJLoader.js';
import { OrbitControls } from './OrbitControls.js';
var container;
var camera, scene, renderer, controls;
var object;
// Object info
const pack_box = {
id: "pack_box",
model: ["pack_box", "15x15", "25x25", "35x35", "40x40"],
minDistance: "13",
perCam: "45",
maxDistance: "13",
posX: "50",
posY: "65",
posZ: "-135",
material: ["white", "grey", "craft"]
};
const pencil_box = {
id: "pencil_box",
model: ["pencil_box", "15x15", "25x25", "35x35", "40x40"],
minDistance: "12",
perCam: "75",
maxDistance: "12",
posX: "45",
posY: "60",
posZ: "100",
material: ["white", "grey", "craft"]
};
const hidden_box = {
id: "hidden_box",
model: ["hidden_box", "20x20", "30x30", "40x40", "45x45", "50x50"],
minDistance: "15",
perCam: "35",
maxDistance: "15",
posX: "50",
posY: "0.6",
posZ: "-135",
material: ["white", "grey", "craft"]
};
const cover_box = {
id: "cover_box",
model: ["cover_box", "25x25", "35x35", "45x45", "45x45", "50x50", "60x60" ],
minDistance: "12",
perCam: "35",
maxDistance: "15",
posX: "50",
posY: "65",
posZ: "-135",
material: ["white", "grey", "craft"]
};
let current_box = [];
let box = document.getElementsByName("size");
// Object URL init
const url = window.location.href;
const splittedUrl = url.split("/");
const id = splittedUrl[splittedUrl.length - 1];
if (id === "") {
current_box = pack_box;
} else if (id === "#pack_box") {
current_box = pack_box;
} else if (id === "#pencil_box") {
current_box = pencil_box;
} else if (id === "#hidden_box") {
current_box = hidden_box;
} else if (id === "#cover_box") {
current_box = cover_box;
}
init();
animate();
function init() {
var basePath = '/models/';
container = document.querySelector('.figure_3d');
// camera
camera = new THREE.PerspectiveCamera(current_box.perCam, window.innerWidth / window.innerHeight, 0.25, 20);
camera.position.x = current_box.posX;
camera.position.y = current_box.posY;
camera.position.z = current_box.posZ;
camera.rotation.y += 1 * (Math.PI / 180);
// control camera
controls = new OrbitControls(camera, container);
controls.enablePan = false;
controls.enableZoom = true;
controls.minDistance = current_box.minDistance;
controls.maxDistance = current_box.maxDistance;
controls.update();
// scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0xFFFFFF);
const ambientLight = new THREE.AmbientLight(0x999999);
scene.add(ambientLight);
const pointLight = new THREE.PointLight(0xffffff, 0.4);
pointLight.position.set(700, 700, 1000);
camera.add(pointLight);
scene.add(camera);
// Object resize
function onWindowResize() {
const maxValue = 550;
var w = window.innerWidth;
var h = window.innerHeight;
w = innerWidth < maxValue ? innerWidth : maxValue;
h = innerWidth < maxValue ? innerWidth : maxValue;
camera.aspect = w / h;
camera.updateProjectionMatrix();
renderer.setSize(w, h);
console.log('Object resized: ' + w + 'x' + h);
}
function loadModel() {
setTexture(counter);
}
// manager
var manager = new THREE.LoadingManager(loadModel);
manager.onProgress = function(item, loaded, total) {
console.log(item, loaded, total);
};
// texture
var textures = [];
var textureLoader = new THREE.TextureLoader(manager);
textures.push(
textureLoader.load(basePath + 'materials/' + current_box.material[0] + '.jpg'),
textureLoader.load(basePath + 'materials/' + current_box.material[1] + '.jpg'),
textureLoader.load(basePath + 'materials/' + current_box.material[2] + '.jpg')
);
material_1.addEventListener("click", function() {
setTexture(0);
});
material_2.addEventListener("click", function() {
setTexture(1);
});
material_3.addEventListener("click", function() {
setTexture(2);
});
function setTexture(texIdx) {
object.traverse(function(child) {
if (child.isMesh) {
child.material.map = textures[texIdx];
}
});
}
//progress load
function onProgress(xhr) {
if (xhr.lengthComputable) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log('Object ' + Math.round(percentComplete, 2) + '% downloaded');
}
}
//error
function onError() {}
// model
var modelsPackArray = [];
var modelObj = [];
// номер дефолтной модели.
var counter = 0;
var loader = new OBJLoader(manager);
current_box.model.forEach((mdl, idx) => {
loader.load(basePath + mdl + ".obj", obj => {
modelObj[idx] = obj;
})
})
function loadModels() {
if (counter > current_box.length) return;
box.forEach(box => {
box.addEventListener('click', e => {
const data_id = e.target.getAttribute('data-id');
counter = data_id;
console.log('перезаписываем counter = ' + data_id);
})
})
loader.load(basePath + current_box.model[counter] + '.obj', function(obj) {
object = obj;
modelsPackArray.push(obj);
scene.add(obj);
loadModel();
}, onProgress, onError);
}
loadModels();
//render
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.append(renderer.domElement);
window.addEventListener('resize', onWindowResize, true);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
renderer.render(scene, camera);
}
<input name="size" id="size_1" data-id="1" type="radio">
<label for="size_1">100x100x50 </label>
<br>
<input name="size" id="size_2" data-id="2" type="radio">
<label for="size_2">120х120х70 </label>
<br>
<input name="size" id="size_3" data-id="3" type="radio">
<label for="size_3">140х140х90 </label>
<br>
<input name="size" id="size_4" data-id="4" type="radio">
<label for="size_4">150х150х100 </label>