нужно добавить плоскость, неподвижную относительно камеры в three.js
- User
нужно добавить плоскость, неподвижную относительно камеры в three.js
- Assistant
Для добавления плоскости, неподвижной относительно камеры в three.js можно использовать объекты THREE.PlaneGeometry и THREE.Mesh, а затем задать их позицию и ориентацию относительно камеры. Например:
// Создаем плоскость var planeGeometry = new THREE.PlaneGeometry(100, 100); var planeMaterial = new THREE.MeshBasicMaterial({color: 0xeeeeee}); var planeMesh = new THREE.Mesh(planeGeometry, planeMaterial); // Позиционируем плоскость относительно камеры planeMesh.position.set(0, 0, -50); planeMesh.rotation.x = Math.PI / 2; // Добавляем плоскость на сцену scene.add(planeMesh);В этом примере мы создаем плоскость с размерами 100x100 и цветом 0xeeeeee. Затем мы позиционируем плоскость перед камерой (на расстоянии -50 от камеры по оси Z) и поворачиваем ее на 90 градусов вокруг оси X, чтобы она была параллельна оси XY. Наконец, мы добавляем плоскость на сцену.
- User
при повороте камеры с помощью OrbitControls она также должна быть неподвижна относительно камеры
- Assistant
Для того чтобы плоскость оставалась неподвижна относительно камеры при использовании OrbitControls, нужно обновлять ее позицию и ориентацию на каждом кадре, используя событие "change" контроллера. Например:
// Создаем плоскость var planeGeometry = new THREE.PlaneGeometry(100, 100); var planeMaterial = new THREE.MeshBasicMaterial({color: 0xeeeeee}); var planeMesh = new THREE.Mesh(planeGeometry, planeMaterial); // Позиционируем плоскость относительно камеры planeMesh.position.set(0, 0, -50); planeMesh.rotation.x = Math.PI / 2; // Добавляем плоскость на сцену scene.add(planeMesh); // Обновляем позицию и ориентацию плоскости при изменении контроллера controls.addEventListener('change', function() { planeMesh.position.copy(camera.position); planeMesh.quaternion.copy(camera.quaternion); });В этом примере мы добавляем обработчик события "change" на контроллер, который будет вызываться при каждом изменении позиции или ориентации камеры. В этом обработчике мы копируем позицию и ориентацию камеры в объект плоскости, чтобы она оставалась неподвижной относительно камеры.
- User
planeMeshGradient не видно код: 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 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)); // animateVerticles(); // function animateVerticles() { // requestAnimationFrame(animateVerticles); // time += 0.1; // sinPosition = Math.sin(time)*0.1; // cosPosition = Math.cos(time*0.1)*0.1; // sinPosition2 = Math.sin(time/Math.PI)*0.1; // for(let i = 0; i<randomPosition.length; i++) { // randomPosition[i] += (sinPosition * cosPosition * sinPosition2) * randSignArray[i] * ratio; // } // 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; } console.log(ratio); }); // Создаем плоскость в виде фона const planeGeometry = new THREE.PlaneGeometry(5, 5, 1, 1); // const planeMaterial = new THREE.MeshBasicMaterial({color: 0xffffff}); // const planeMesh = new THREE.Mesh(planeGeometry, planeMaterial); // planeMesh.rotation.x = -Math.PI/2; // scene.add(planeMesh); // Создаем градиентный фон для плоскости const planeTexture = new THREE.TextureLoader().load('gradient-1.png'); planeTexture.minFilter = THREE.LinearFilter; planeTexture.magFilter = THREE.LinearFilter; planeTexture.wrapS = THREE.ClampToEdgeWrapping; planeTexture.wrapT = THREE.ClampToEdgeWrapping; const planeMaterialGradient = new THREE.MeshBasicMaterial({map: planeTexture}); const planeMeshGradient = new THREE.Mesh(planeGeometry, planeMaterialGradient); planeMeshGradient.rotation.z = -Math.PI/2; planeMeshGradient.position.y = 0.1; controls.addEventListener('change', function() { planeMeshGradient.position.copy(camera.position); planeMeshGradient.quaternion.copy(camera.quaternion); }); scene.add(planeMeshGradient); 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);
// ________________________________________________________________________________________________________________________________________________
// const texture = makeTexture(); // texture.needsUpdate = true; // texture.minFilter = THREE.LinearFilter; // texture.magFilter = THREE.LinearFilter;
// const attributes = { // alpha: { // type: 'f', // value: [] // }, // customColor: { // type: 'c', // value: [] // }, // size: { // type: 'f', // value: [] // }
// };
// const uniforms = { // color: { // type: "c", // value: new THREE.Color(0xfffffff) // }, // texture: { // type: "t", // value: texture // } // };
// const shaderMaterial = new THREE.ShaderMaterial({ // uniforms: uniforms, // vertexShader: document.getElementById('vertexshader').textContent, // fragmentShader: document.getElementById('fragmentshader').textContent, // blending: THREE.AdditiveBlending, // transparent: true, // // fog: false, // depthTest: false, // // depthWrite: false // });
// function makeTexture() { // const canvas = document.createElement('canvas'); // const size = 100; // canvas.width = size; // canvas.height = size; // const context = canvas.getContext('2d'); // const gradient = context.createRadialGradient(canvas.width / 2, canvas.height / 2, 0, canvas.width / 2, canvas.height / 2, canvas.width / 2); // gradient.addColorStop(0, 'rgba(255, 255, 255, 1)'); // gradient.addColorStop(0.9, 'rgba(255, 255, 255, 1)'); // gradient.addColorStop(1, 'rgba(255, 255, 255, 0)'); // context.fillStyle = gradient; // context.fillRect(0, 0, canvas.width, canvas.height); // return new THREE.Texture(canvas); // }
// ________________________________________________________________________________________________________________________________________________
function animate() { requestAnimationFrame(animate); animatePoint(); pointMesh.position.set(point.x, point.y, point.z); controls.update(); renderer.render(scene, camera); } animate(); });
- Assistant
Для того, чтобы плоскость с градиентным фоном render-илась на экране, необходимо убедиться, что координаты данной плоскости находятся перед координатами героев, которых вы загрузили, и что расстояние между плоскостью и камерой достаточно большое, чтобы она была видимой. Попробуйте изменить строку
planeMeshGradient.position.y = 0.1наplaneMeshGradient.position.set(0,0,-10). - User
ошибка в строке Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'addEventListener') controls.addEventListener('change', function() {
- Assistant
Ошибка "Cannot read properties of undefined (reading 'addEventListener')" говорит о том, что у переменной
controlsнет свойстваaddEventListener. В вашем коде, видимо, переменнаяcontrolsне была определена или не была присвоена объекту типаOrbitControls.Убедитесь, что вы создали объект
controlsи правильно его инициализировали. Например, для инициализацииOrbitControlsобъекта в вашем коде можно использовать следующий код:const controls = new OrbitControls(camera, renderer.domElement);Здесь
camera- это объект камеры, аrenderer.domElement- это элемент DOM, на который отображается сцена. Если у вас все еще возникает ошибка, пожалуйста, обновите свой код, чтобы я мог помочь вам лучше.