как изменить этот код, чтобы анимация точки pointMesh применялась и ко всем точкам…
- User
как изменить этот код, чтобы анимация точки pointMesh применялась и ко всем точкам points? код: 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-1.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.0*Math.random()-5.0, 10.0*Math.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)); } let time = 0; let sinPosition; let sinPosition2; let cosPosition; let randSignArray = []; let sign; let ratio = 1.0; for(let i = 0; i<randomPosition.length; i++) { sign = Math.random() < 0.5 ? -1.0 : 1.0; randSignArray[i] = sign; } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); window.addEventListener('wheel', function(event) { if (event.deltaY > 0) { updateArray(increment); if(ratio > 0.0) { ratio -= 0.01; } } else { reverseUpdateArray(increment); ratio += 0.01; } }); scene.add(points); points.rotateX(Math.PI/2.0); }}); camera.position.z = 3;
// ________________________________________________________________________________________________________________________________________________
// Создаем переменные для точки и радиусаlet point = new THREE.Vector3(0, 0, 0); let radius = 1;
// Создаем функцию для генерации случайной точки внутри заданного радиуса function generateRandomPointInRadius(radius) { let angle1 = Math.random() * 2 * Math.PI; let angle2 = Math.random() * 2 * Math.PI; let x = radius * Math.sin(angle1) * Math.cos(angle2); let y = radius * Math.sin(angle1) * Math.sin(angle2); let z = radius * Math.cos(angle1); return new THREE.Vector3(x, y, z); }
// Инициализируем переменные для генерации случайной точки let randomPoint = generateRandomPointInRadius(radius); let dist = point.distanceTo(randomPoint); let t = 0;
// Создаем функцию для анимации точки function animatePoint() { t += 0.01; if (t > 1) { randomPoint = generateRandomPointInRadius(radius); dist = point.distanceTo(randomPoint); t = 0; } let newPos = point.clone().lerp(randomPoint, t); let moveDist = newPos.distanceTo(point); if (moveDist >= dist) { randomPoint = generateRandomPointInRadius(radius); dist = point.distanceTo(randomPoint); t = 0; } point.copy(newPos); }
// Добавляем точку на сцену let pointGeometry = new THREE.SphereGeometry(0.2, 32, 32); let pointMaterial = new THREE.MeshBasicMaterial({color: 0xff0000}); let pointMesh = new THREE.Mesh(pointGeometry, pointMaterial); pointMesh.position.set(point.x, point.y, point.z); scene.add(pointMesh);
// ________________________________________________________________________________________________________________________________________________
let uniforms = { mouseCoord: {type:'v3', value: new THREE.Vector3()}, tex: { type:'t', value:texture }, res: { type:'v2', value:new THREE.Vector2(window.innerWidth,window.innerHeight)} };
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); scene.add(planeMesh); planeMesh.position.set(0, 0, -85);
controls.addEventListener('change', function() { planeMesh.quaternion.copy(camera.quaternion); });
let targetX = 0; let targetY = 0; let currentX = 0; let currentY = 0;
function update() { requestAnimationFrame(update); const diffX = targetX - currentX; const diffY = targetY - currentY; const distance = Math.sqrt(diffX * diffX + diffY * diffY); const speed = distance / 10; if (distance < 1.0) { currentX = targetX; currentY = targetY; } else { currentX += speed * diffX / distance; currentY += speed * diffY / distance; } } update();
document.addEventListener('mousemove', (event) => { targetX = event.clientX; targetY = event.clientY; uniforms.mouseCoord.value.x = currentX; uniforms.mouseCoord.value.y = -currentY + window.innerHeight; });
function animate() { requestAnimationFrame(animate); animatePoint(); pointMesh.position.set(point.x, point.y, point.z); controls.update(); uniforms.mouseCoord.value.x = currentX; uniforms.mouseCoord.value.y = -currentY + window.innerHeight; renderer.render(scene, camera); } animate(); });
- Assistant
Для того чтобы применить анимацию точки ко всем точкам, нужно создать массив точек и применять изменения к каждой точке в цикле. Можно заменить следующую часть кода:
// Добавляем точку на сцену let pointGeometry = new THREE.SphereGeometry(0.2, 32, 32); let pointMaterial = new THREE.MeshBasicMaterial({color: 0xff0000}); let pointMesh = new THREE.Mesh(pointGeometry, pointMaterial); pointMesh.position.set(point.x, point.y, point.z); scene.add(pointMesh);
на:
// Создаем массив точек const pointsArray = [];
for (let i = 0; i < 100; i++) { // Добавляем точку на сцену let pointGeometry = new THREE.SphereGeometry(0.2, 32, 32); let pointMaterial = new THREE.MeshBasicMaterial({color: 0xff0000}); let pointMesh = new THREE.Mesh(pointGeometry, pointMaterial); let randomPoint = generateRandomPointInRadius(radius); pointMesh.position.set(randomPoint.x, randomPoint.y, randomPoint.z); scene.add(pointMesh);
// Добавляем точку в массив pointsArray.push(pointMesh); }
// Создаем функцию для анимации точек function animatePoints() { t += 0.01; if (t > 1) { randomPoint = generateRandomPointInRadius(radius); dist = pointsArray[0].position.distanceTo(randomPoint); t = 0; } let newPos = point.clone().lerp(randomPoint, t); let moveDist = newPos.distanceTo(point); if (moveDist >= dist) { randomPoint = generateRandomPointInRadius(radius); dist = pointsArray[0].position.distanceTo(randomPoint); t = 0; } point.copy(newPos);
// Применяем изменения ко всем точкам в массиве for (let i = 0; i < pointsArray.length; i++) { let distToPoint = pointsArray[i].position.distanceTo(point); let distToNewPos = pointsArray[i].position.distanceTo(newPos); if (distToNewPos <= distToPoint + moveDist) { let newPoint = pointsArray[i].position.clone().lerp(randomPoint, t); pointsArray[i].position.copy(newPoint); } } }
Кроме того, нужно удалить следующую строку кода, так как эта точка уже не нужна:
pointMesh.position.set(point.x, point.y, point.z);
- User
нет, эта анимация должна применяться к const points = new THREE.Points(geometryPoint, materialPoint);
- Assistant
Для того, чтобы применить анимацию к
points, можно изменить код в функцииanimate()и добавить новую функциюanimatePoints(). Вот как это можно сделать:- Добавьте следующие переменные в начале кода, чтобы они были доступны везде:
let point = new THREE.Vector3(0, 0, 0); let radius = 1; let randomPoint = generateRandomPointInRadius(radius); let dist = points.geometry.vertices[0].distanceTo(randomPoint); let t = 0;Эти переменные будут использоваться для случайной точки и ее анимации.
- Замените функцию
animate()на следующий код:
function animate() { requestAnimationFrame(animate); animatePoints(); controls.update(); uniforms.mouseCoord.value.x = currentX; uniforms.mouseCoord.value.y = -currentY + window.innerHeight; renderer.render(scene, camera); }Функция
animatePoints()будет работать с анимацией точки.- Добавьте следующую функцию
animatePoints()после функцииanimate():
function animatePoints() { t += 0.01; if (t > 1) { randomPoint = generateRandomPointInRadius(radius); dist = points.geometry.vertices[0].distanceTo(randomPoint); t = 0; } let newPos = point.clone().lerp(randomPoint, t); let moveDist = newPos.distanceTo(point); if (moveDist >= dist) { randomPoint = generateRandomPointInRadius(radius); dist = points.geometry.vertices[0].distanceTo(randomPoint); t = 0; } point.copy(newPos); for (let i = 0; i < points.geometry.vertices.length; i++) { let distToPoint = points.geometry.vertices[i].distanceTo(point); let distToNewPos = points.geometry.vertices[i].distanceTo(newPos); if (distToNewPos <= distToPoint + moveDist) { let newPoint = points.geometry.vertices[i].clone().lerp(randomPoint, t); points.geometry.vertices[i].copy(newPoint); } } points.geometry.verticesNeedUpdate = true; }Функция
animatePoints()будет работать с изменением каждой точки. Она сначала генерирует случайную точку внутри заданного радиуса и определяет точкуnewPosмежду текущей и случайной точками, используя функциюlerp(). Затем она проверяет, находится ли каждая точка в расстоянииdistToPointот текущей точки. Если да, то она генерирует новую точкуnewPointмежду текущей и случайной точками для этой точки и применяет изменение вpoints.- Удалите следующую строку кода, так как она больше не нужна:
const points = new THREE.Points(geometryPoint, materialPoint);- В клиентском коде вместо
points.rotateX(Math.PI/2.0);добавьте следующий код, чтобы сделать начальную анимацию и задать начальные радиус и точку:
const initialRadius = 5; let initialRandomPoint = generateRandomPointInRadius(initialRadius); let initialDist = point.distanceTo(initialRandomPoint); let initialT = 0; function animateInitialPoint() { initialT += 0.005; if (initialT > 1) { initialRandomPoint = generateRandomPointInRadius(initialRadius); initialDist = point.distanceTo(initialRandomPoint); initialT = 0; } let newPos = point.clone().lerp(initialRandomPoint, initialT); let moveDist = newPos.distanceTo(point); if (moveDist >= initialDist) { initialRandomPoint = generateRandomPointInRadius(initialRadius); initialDist = point.distanceTo(initialRandomPoint); initialT = 0; } point.copy(newPos); pointMesh.position.set(point.x, point.y, point.z); } camera.position.z = 10; function animate() { requestAnimationFrame(animate); animateInitialPoint(); animatePoints(); controls.update(); uniforms.mouseCoord.value.x = currentX; uniforms.mouseCoord.value.y = -currentY + window.innerHeight; renderer.render(scene, camera); } animate();Функция
animateInitialPoint()будет работать с анимацией начальной точки. Она генерирует случайную точку внутри большего радиуса, задает начальную точкуpointи начальную анимацию для нее.В итоге вы получите анимацию, которая будет применяться к каждой точке в
points. - User
код целиком
- Assistant
Вот полный код с изменениями:
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 = 10; 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-1.png'); const loader = new GLTFLoader(); const url = 'GRAF_3_23.glb'; loader.load(url, function (gltf) {