0

Пытаюсь настроить изменение расположения камеры с помощью кнопки но увы не меняет расположение. Кнопки отрисовывает, ошибок не выдаёт, но и расположение камеры не меняет.

Вот код :

... 

camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 );
                camera.position.set( 400, 200, 0 );
... 

... 

                  var controls2 = new function () {
                   this.pozishon = 0; 
                   if (this.pozishon==1) {
                    camera.position.set( 400, 200, 0 );
                   }
                   if(this.pozishon==2) {
                    camera.position.set( 0, 200, 400 );
                   }
                   if(this.pozishon==3 ) {
                   //   camera.lookAt(new THREE.Vector3(0,0,0));
                    //camera.position.set( 400, 400, 0 );
                   
                   camera.position.set( 400, -1800, 800);
camera.lookAt( 400, 400, 0 );
camera.up.set( 0, 0, 1 );
camera.updateProjectionMatrix();
                   }
                   
                   };
                 
                gui = new GUI( { title: 'меню' } );
                const geometryFolder  = gui.addFolder("камера");
                geometryFolder.add(controls2, "pozishon", { 'прямо': 1, 'верх':2, 'бок': 3 }).name("камера");
                //geometryFolder.add(controls, 'rotationSpeed', 0, 0.5);
                //geometryFolder.add(controls, 'bouncingSpeed', 0, 0.5);
                const primitiveFolder =  gui.addFolder("примитивы");
                 
... 

1
  • А с чего оно должно менять расположение камеры? Где, когда и (главное) почему положение должно поменяться? 2 мая в 20:52

2 ответа 2

1

Должно быть что-то типа такого:

body{
  overflow: hidden;
  margin: 0;
}
<script async src="https://ga.jspm.io/npm:es-module-shims@1.6.3/dist/es-module-shims.js" crossorigin="anonymous"></script>
<script type="importmap">
  {
    "imports": {
      "three": "https://unpkg.com/three@0.152.0/build/three.module.js",
      "three/addons/": "https://unpkg.com/three@0.152.0/examples/jsm/"
    }
  }
</script>
<script type="module">
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { GUI } from "three/addons/libs/lil-gui.module.min.js";

console.clear();

let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 1000);
camera.position.set(-3, 5, 8).setLength(12);
camera.lookAt(scene.position);
let renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(innerWidth, innerHeight);
//renderer.setClearColor(0x404040);
document.body.appendChild(renderer.domElement);
window.addEventListener("resize", (event) => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(innerWidth, innerHeight);
});

scene.add(new THREE.GridHelper());

let controls2 = {
  pozishon: 0
}

let gui = new GUI({ title: "меню" });
const geometryFolder = gui.addFolder("камера");
geometryFolder
  .add(controls2, "pozishon", { "прямо": 1, "верх": 2, "бок": 3 })
  .name("камера")
  .onChange(val => {
  switch(val){
    case 1:
      camera.position.set(0, 1, 10);
      break;
    case 2:
      camera.position.set(0, 5, 10);
      break;
    case 3:
      camera.position.set(5, 5, 10);
      break;
    default:
      alert("Что-то пошло не так")
  }
  camera.lookAt(scene.position);
});
const primitiveFolder = gui.addFolder("примитивы");

renderer.setAnimationLoop((_) => {
  renderer.render(scene, camera);
});

</script>

У контроллера добавляется обработчик события .onChange().

2
  • Спасибо что научили делать вот такую штуку (реально 😎круто)
    – timob256
    5 мая в 12:13
  • 1
    @timob256 Пожалуйста :) На самом деле это всего лишь пример одного из множества вариантов, и рассматривать как финальное решение его не нужно. Но если и в таком виде работает - тогда хорошо, рад, что смог помочь ) 5 мая в 12:26
0

body{
  overflow: hidden;
  margin: 0;
}
<script async src="https://ga.jspm.io/npm:es-module-shims@1.6.3/dist/es-module-shims.js" crossorigin="anonymous"></script>
<script type="importmap">
  {
    "imports": {
      "three": "https://unpkg.com/three@0.152.0/build/three.module.js",
      "three/addons/": "https://unpkg.com/three@0.152.0/examples/jsm/"
    }
  }
</script>
<script type="module">
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { GUI } from "three/addons/libs/lil-gui.module.min.js";
import Stats from 'three/addons/libs/stats.module.js';

console.clear();

let camera, controls, scene, renderer;
        let stats, container;
        let gui;

        init();
        //render(); // remove when using next line for animation loop (requestAnimationFrame)
        animate();

        function init() {
            container = document.getElementById( 'container' );

            scene = new THREE.Scene();
            scene.background = new THREE.Color( 0x94afb5 );
            scene.fog = new THREE.FogExp2( 0x94afb5, 0.002 );

            renderer = new THREE.WebGLRenderer( { antialias: true } );
            renderer.setPixelRatio( window.devicePixelRatio );
            renderer.setSize( window.innerWidth, window.innerHeight );
            //document.body.appendChild( renderer.domElement );
            //container.appendChild( renderer.domElement );
         
            //container=document.body.appendChild( renderer.domElement );
            document.body.appendChild( renderer.domElement );


            camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 );
            camera.position.set( 400, 200, 0 );

            // controls

            controls = new OrbitControls( camera, renderer.domElement );
            controls.listenToKeyEvents( window ); // optional

            //controls.addEventListener( 'change', render ); // call this only in static scenes (i.e., if there is no animation loop)

            controls.enableDamping = true; // an animation loop is required when either damping or auto-rotation are enabled
            controls.dampingFactor = 0.05;

            controls.screenSpacePanning = false;

            controls.minDistance = 100;
            controls.maxDistance = 500;

            controls.maxPolarAngle = Math.PI / 2;

            // world
                 // рисую квадраты осей 

//--------------Создаем объект-------------------
const points = [];
points.push(new THREE.Vector3(-10, 10, 0));
points.push(new THREE.Vector3(10, 10, 0));
points.push(new THREE.Vector3(10, -10, 0));
points.push(new THREE.Vector3(-10, -10, 0));
points.push(new THREE.Vector3(-10, 10, 0));
const osxyMaterial = new THREE.LineBasicMaterial({ color: 0x7457bd, linewidth: 1 });
const osxyGeometry = new THREE.BufferGeometry().setFromPoints(points);
const osxy = new THREE.Line(osxyGeometry, osxyMaterial);
scene.add(osxy);

const points1 = [];
points1.push(new THREE.Vector3(0, -10, 10));//Указываем вектор первой точки
points1.push(new THREE.Vector3(0, 10, 10));//Указываем вектор второй точки
points1.push(new THREE.Vector3(0, 10, -10));
points1.push(new THREE.Vector3(0, -10, -10));
points1.push(new THREE.Vector3(0, -10, 10));
const osxzMaterial = new THREE.LineBasicMaterial({ color: 0x3d803d, linewidth: 1 });
const osxzGeometry = new THREE.BufferGeometry().setFromPoints(points1);
const osxz = new THREE.Line(osxzGeometry, osxzMaterial);
scene.add(osxz);

const points2 = []
points2.push(new THREE.Vector3(-10, 0, 10));//Указываем вектор первой точки
points2.push(new THREE.Vector3(10, 0, 10));//Указываем вектор второй точки
points2.push(new THREE.Vector3(10, 0, -10));
points2.push(new THREE.Vector3(-10, 0, -10));
points2.push(new THREE.Vector3(-10, 0, 10));
const osyzMaterial = new THREE.LineBasicMaterial({ color: 0xab5641, linewidth: 1 })
const osyzGeometry = new THREE.BufferGeometry().setFromPoints(points2)
const osyz = new THREE.Line(osyzGeometry, osyzMaterial)
scene.add(osyz) 

            // lights

            const dirLight1 = new THREE.DirectionalLight( 0xffffff );
            dirLight1.position.set( 1, 1, 1 );
            scene.add( dirLight1 );

            const dirLight2 = new THREE.DirectionalLight( 0x002288 );
            dirLight2.position.set( - 1, - 1, - 1 );
            scene.add( dirLight2 );

            const ambientLight = new THREE.AmbientLight( 0x222222 );
            scene.add( ambientLight );

           // тут!!! статистика. 

            stats = new Stats();
            //container.appendChild( stats.dom );
             document.body.appendChild( stats.dom );
            //
            
            // tyt knopki
            
            let controls2 = {
  pozishon: 0
}

let gui = new GUI({ title: "меню" });
const geometryFolder = gui.addFolder("камера");
geometryFolder
  .add(controls2, "pozishon", { "прямо": 1, "верх": 2, "бок": 3 })
  .name("камера")
  .onChange(val => {
  switch(val){
case 1:
  camera.position.set(0, 1, 10);
  break;
case 2:
  camera.position.set(0, 5, 10);
  break;
case 3:
  camera.position.set(5, 5, 10);
  break;
default:
  alert("Что-то пошло не так")
  }
  camera.lookAt(scene.position);
});
const primitiveFolder = gui.addFolder("примитивы");

renderer.setAnimationLoop((_) => {
  renderer.render(scene, camera);
  });

            window.addEventListener( 'resize', onWindowResize );
        }

        function onWindowResize() {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize( window.innerWidth, window.innerHeight );
        }

        function animate() {
            requestAnimationFrame( animate );
            stats.update();
            render();
        }

        function render() {
            renderer.render( scene, camera );
        }

</script>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.