ThreeJS: Transform Control to Obj loader not working properly

When I try to load a object using object loader and add transform controls to it, and when I try to rotate / translate the object with the help of the controls. the whole object is not moving and it’s in irregular manner. Usually, we’ll update the mesh in the transform controls but when we use the object loader we can’t get the mesh details. So, Is there any probability to fix it by rotating the whole object smoothly using transform controls while loading a with object loaders.

// if (!Detector.webgl) Detector.addGetWebGLMessage();

        var camera, controls, scene, renderer, control, object;

        var controlData = false;

        init();

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

        animate();

        function init() {

            scene = new THREE.Scene();

            scene.background = new THREE.Color(0xFFCC99);

            // scene.fog = new THREE.FogExp2(0xcccccc, 0.002);

            renderer = new THREE.WebGLRenderer({ antialias: true });

            renderer.setPixelRatio(window.devicePixelRatio);

            renderer.setSize(window.innerWidth, window.innerHeight);

            document.body.appendChild(renderer.domElement);

            camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);

            // camera.position.set(400, 200, 0);

            camera.position.z = 120;

            // camera.position.y = 500; 

            // controls

            controls = new THREE.OrbitControls(camera, renderer.domElement);

            // 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.25;

            // controls.screenSpacePanning = true;

            controls.minDistance = 0.001;

            controls.maxDistance = 50000;

            

            controls.enableZoom = false;

            controls.enabled = false;

            // controls.maxPolarAngle = Math.PI / 2;

            controls.screenSpacePanning = true;

            controls.rotateSpeed = 5;

            // world

            control = new THREE.TransformControls(camera, renderer.domElement);

            control.addEventListener('change', render);

            control.addEventListener('dragging-changed', function (event) {

                console.log('hitin')

                orbit.enabled = !event.value;

                controls.enabled  = false;

            });

            // controls.minAzimuthAngle = Math.PI;

            // controls.maxAzimuthAngle = Math.PI;

            var axisHelper = new THREE.AxesHelper(20);

            // scene.add(axisHelper)

            // var geometry = new THREE.CylinderBufferGeometry( 0, 10, 30, 4, 1 );

            // var material = new THREE.MeshPhongMaterial( { color: 0xffffff, flatShading: true } );

            // for ( var i = 0; i < 500; i ++ ) {

            //  var mesh = new THREE.Mesh( geometry, material );

            //  mesh.position.x = Math.random() * 1600 - 800;

            //  mesh.position.y = 0;

            //  mesh.position.z = Math.random() * 1600 - 800;

            //  mesh.updateMatrix();

            //  mesh.matrixAutoUpdate = false;

            //  scene.add( mesh );

            // }

            function loadModel() {

                object.traverse(function (child) {

                    // if (child.isMesh) child.material.map = texture;

                });

                // object.position.y =  -95;

                // object.rotation.x = 11.3;

                // object.rotation.z = 0.9;

                // camera.lookAt(object.position);

                object.rotation.y = 0.9;

                var center = new THREE.Vector3(0, 0, 0);

                let box = new THREE.Box3().setFromObject(object)

                let sphere = box.getBoundingSphere()

                let centerPoint = sphere.center

                // object.position.copy(centerPoint);

                camera.lookAt(centerPoint)

                controls.target.set(0, 0, 0);

                object.position.z = -25

                scene.add(object);

                // console.log(object);

                // controlData

                object.children.forEach(item => {

                    console.log(item);

                    control.object(object);

                });

                // control.attach(object);

                scene.add(control);

                // console.log(control);

                // control.position.y = 15;

                // control.position.z = 30;

            }

            var manager = new THREE.LoadingManager(loadModel);

            manager.onProgress = function (item, loaded, total) {

                console.log(item, loaded, total);

            };

            // texture

            // var textureLoader = new THREE.TextureLoader(manager);

            // var texture = textureLoader.load('textures/UV_Grid_Sm.jpg');

            // model

            function onProgress(xhr) {

                if (xhr.lengthComputable) {

                    var percentComplete = xhr.loaded / xhr.total * 100;

                    console.log('model ' + Math.round(percentComplete, 2) + '% downloaded');

                }

            }

            function onError(xhr) { }

            var loader = new THREE.OBJLoader(manager);

            loader.load('./JSON Object/18JuneObjectOne.obj', function (obj) {

                object = obj;

            }, onProgress, onError);

            // lights

            var light = new THREE.DirectionalLight(0xffffff);

            light.position.set(1, 1, 1);

            scene.add(light);

            var light = new THREE.DirectionalLight(0xcacaca);

            light.position.set(- 1, - 1, - 1);

            scene.add(light);

            var light = new THREE.AmbientLight(0x222222);

            scene.add(light);

            //

            // var OFFSET = 20;

            // var bbox = new THREE.Box3().setFromObject(object);

            // camera.position.set(bbox + OFFSET, 0, 0);

            // var sphericalCoord = new THREE.Spherical();

            // sphericalCoord.setFromVector3(camera.position);

            // sphericalCoord.phi = THREE.Math.degToRad(45);

            // sphericalCoord.theta = THREE.Math.degToRad(45);

            // var vec = new THREE.Vector3().setFromSpherical(sphericalCoord);

            // camera.position.set(vec.x, vec.y, vec.z);

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

        }

        window.addEventListener('keydown', function (event) {

            switch (event.keyCode) {

                case 81: // Q

                    control.setSpace(control.space === "local" ? "world" : "local");

                    break;

                case 17: // Ctrl

                    control.setTranslationSnap(100);

                    control.setRotationSnap(THREE.Math.degToRad(15));

                    break;

                case 87: // W

                    control.setMode("translate");

                    break;

                case 69: // E

                    control.setMode("rotate");

                    break;

                case 82: // R

                    control.setMode("scale");

                    break;

                case 187:

                case 107: // +, =, num+

                    control.setSize(control.size + 0.1);

                    break;

                case 189:

                case 109: // -, _, num-

                    control.setSize(Math.max(control.size - 0.1, 0.1));

                    break;

                case 88: // X

                    control.showX = !control.showX;

                    break;

                case 89: // Y

                    control.showY = !control.showY;

                    break;

                case 90: // Z

                    control.showZ = !control.showZ;

                    break;

                case 32: // Spacebar

                    control.enabled = !control.enabled;

                    break;

            }

        });

        window.addEventListener('keyup', function (event) {

            switch (event.keyCode) {

                case 17: // Ctrl

                    control.setTranslationSnap(null);

                    control.setRotationSnap(null);

                    break;

            }

        });

        function onWindowResize() {

            camera.aspect = window.innerWidth / window.innerHeight;

            camera.updateProjectionMatrix();

            renderer.setSize(window.innerWidth, window.innerHeight);

        }

        function animate() {

            requestAnimationFrame(animate);

            controls.update(); // only required if controls.enableDamping = true, or if controls.autoRotate = true

            render();

        }

        window.addEventListener("wheel", function (event) {

            var factor = 10;

            // var mX = (event.clientX / window.innerWidth) * 2 - 1;

            // var mY = -(event.clientY / window.innerHeight()) * 2 + 1;

            var mX = 2 * event.clientX / window.innerWidth - 1;

            var mY = 1 - 2 * event.clientY / window.innerHeight;

            var vector = new THREE.Vector3(mX, mY, 0.1);

            vector.unproject(camera);

            vector.sub(camera.position);

            if (event.deltaY < 0) {

                camera.position.addVectors(camera.position, vector.setLength(factor));

                controls.target.addVectors(controls.target, vector.setLength(factor));

            } else {

                camera.position.subVectors(camera.position, vector.setLength(factor));

                controls.target.subVectors(controls.target, vector.setLength(factor));

            }

        });

        function render() {

            renderer.render(scene, camera);

        }

I’m confused a bit by your question. You are using OBJLoader in your code but talking about “object loader”. Are you aware that ObjectLoader and OBJLoader are two different classes?

2 Likes

I mean ObjLoader @Mugen87 Sorry for that

I don’t think this line is correct. TransformControls does not have a object method. It’s a property.