3

this is the first time I write on stackoverflow ...a couple of days I'm trying to use the javascript library Three.js (actually version n° r99), I correctly entered the 3D model but when I see it loaded is seen from behind and not centered on the viewport, how can I fix it?

The code is this:

<script>

var scene = new THREE.scene();

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

camera.position.z = 15;

var render = new THREE.WebGLRenderer();
renderer.setSize ( window.InnerWidth, window.InnerHeight );
document.body.appendChild (renderer.domElement);
window.addEventListener('resize', function(){
var width = window.innerWidth;
var height = window.innerHeight;
renderer.setSize( width, height );
camera.aspect = width / height;
camera.updateProjectMatrix();
});

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

var loader = new THREE.ObjectLoader();
loader.load("/models/teschio.json",function (obj)
{
scene.add( obj );
});

var animate = function (){
requestAnimateFrame ( animate );
renderer.render (scene, camera);
}
animate();

</script>

and this is a wireframe screen currently: actual wireframe

thanks in advance for any answers.

Dario
  • 43
  • 2
  • 5

1 Answers1

7

Something like this:

var loader = new THREE.ObjectLoader();
loader.load("/models/teschio.json",function (obj)
{
  var box = new THREE.Box3().setFromObject( obj );
  var center = new THREE.Vector3();
  box.getCenter( center );
  obj.position.sub( center ); // center the model
  obj.rotation.y = Math.PI;   // rotate the model
  scene.add( obj );
});
prisoner849
  • 16,894
  • 4
  • 34
  • 68
  • It works great, you saved me ... thank you very much. How do these attributes you showed me make the 3d object center? – Dario Dec 18 '18 at 20:52
  • @Dario `THREE.Box3()` is AABB (axis-aligned bounding box). You can set it from the object you've loaded. Then use `.getCenter()` method to get its center. Then simply subtract the vector of the center from the default position of the object. You can read all the stuff in the [documentation](https://threejs.org/docs/index.html#api/en/math/Box3) :) If the answer solved your problem, mark it as accepted, please :) – prisoner849 Dec 18 '18 at 21:00