объект planeMesh должен находиться в направлении камеры всегда (и при повороте камеры),…
- User
объект planeMesh должен находиться в направлении камеры всегда (и при повороте камеры), на определенном расстоянии от нее, сейчас planeMesh находится в одном месте все время и не поворачивается не переписывай весь код, только то, что нужно изменить
import * as THREE from ‘three’; import { GLTFLoader } from ‘three/examples/jsm/loaders/GLTFLoader’; import { OrbitControls } from ‘three/examples/jsm/controls/OrbitControls’
const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 5;
const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement);
const controls = new OrbitControls( camera, renderer.domElement ); controls.enableZoom = false;
controls.enableDamping = true; controls.dampingFactor = 0.05;
const shaderCode = document.getElementById(“fragShader”).innerHTML; THREE.ImageUtils.crossOrigin = ‘’; const texture = new THREE.TextureLoader().load(‘gradient-2.png’);
const loader = new GLTFLoader(); const url = ‘GRAF_3_23.glb’;
loader.load(url, function (gltf) { const model = gltf.scene;
model.traverse((child) => { if (child.isMesh) { const geometry = child.geometry;
const texturePoint = new THREE.TextureLoader().load(‘texture3.png’);
const sizeVariation = 0.001;
const geometryPoint = new THREE.BufferGeometry();
const positions = geometry.getAttribute(‘position’).array;
const randomSize = []; for (let i = 0; i < positions.length; i += 3) { const startSize = 0.006; const size = startSize + (Math.random() * sizeVariation); randomSize.push(size, size, size); // каждый размер - это три компоненты размера в формате [x, y, z] } // let startSize = 0.06;
const materialPoint = new THREE.PointsMaterial({ size: 0.03, sizeAttenuation: true, map: texturePoint, alphaTest: 0.01, transparent: true, color: new THREE.Color(1., 1., 1.), opacity: 1. });
const sizes = new Float32Array(randomSize); geometryPoint.setAttribute(‘size’, new THREE.BufferAttribute(sizes, 1));
const randomPosition = []; for (let i = 0; i < positions.length; i += 3) { randomPosition.push(10.0Math.random()-5.0, 10.0Math.random()-5.0, 10.0*Math.random()-5.0); } const randomPositionCopy = […randomPosition];
let increment = 0.002;
geometryPoint.setAttribute(‘position’, new THREE.Float32BufferAttribute(positions, 3));
const points = new THREE.Points(geometryPoint, materialPoint);
geometry.setAttribute(‘position’, new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); function updateArray(increment) { for(let j = 0; j < 75; j++) { for(let i = 0; i<randomPosition.length; i++) { if (randomPosition[i] < positions[i]) { randomPosition[i] = randomPosition[i] + increment; } else if(randomPosition[i] > positions[i]) { randomPosition[i] = randomPosition[i] - increment; } else if((randomPosition[i] - positions[i]) < 0.002) { randomPosition[i] = positions[i]; } } } geometryPoint.setAttribute(‘position’, new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); } function reverseUpdateArray(increment) { for(let j = 0; j < 75; j++) { for(let i = 0; i<randomPosition.length; i++) { if (randomPosition[i] < randomPositionCopy[i]) { randomPosition[i] = randomPosition[i] + increment; } else if(randomPosition[i] > randomPositionCopy[i]) { randomPosition[i] = randomPosition[i] - increment; } else if((randomPosition[i] - randomPositionCopy[i]) < 0.002) { randomPosition[i] = randomPositionCopy[i]; } } } geometryPoint.setAttribute(‘position’, new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); }
- Assistant
// изменяем позицию объекта planeMesh и добавляем его в объект-обертку wrapperObject
const planeGeometry = new THREE.PlaneGeometry(1000, 1000); const planeMaterial = new THREE.ShaderMaterial({ uniforms: uniforms, fragmentShader: shaderCode, side: THREE.DoubleSide });
const planeMesh = new THREE.Mesh(planeGeometry, planeMaterial); planeMesh.position.set(0, 0, -50); // устанавливаем начальную позицию объекта planeMesh wrapperObject.add(planeMesh); // добавляем planeMesh в объект-обертку
// изменяем функцию update(), чтобы обновлять позицию объекта-обертки в направлении камеры function update() { requestAnimationFrame(update); const distance = 10; // задаем расстояние между объектом-оберткой и камерой const vector = new THREE.Vector3(); // создаем вектор camera.getWorldDirection(vector); // получаем направление камеры в мировых координатах vector.multiplyScalar(-distance); // устанавливаем расстояние до объекта-обертки wrapperObject.position.copy(camera.position).add(vector); // устанавливаем позицию объекта-обертки в направлении камеры wrapperObject.lookAt(camera.position); // поворачиваем объект-обертку в направлении камеры const diffX = targetX - currentX; const diffY = targetY - currentY; const distanceToMouse = Math.sqrt(diffX * diffX + diffY * diffY); // расстояние от текущей позиции мыши до цели const speed = distanceToMouse / 10; // скорость движения объекта-обертки if (distanceToMouse < 1.0) { currentX = targetX; currentY = targetY; } else { currentX += speed * diffX / distanceToMouse; currentY += speed * diffY / distanceToMouse; } } update();