vinni
vinni

Reputation: 653

Three.js move camera distance to object by z

I'm rotating a PerspectiveCamera with orbitControls around an object. Now I want to move the camera closer to the object but keep the actual rotation.

My coordinate to set the distance to the objects are output as [0,0,100].

But my CameraPosition is [-500, 96, 1772]. How can I keep the "rotation" but move the camera closer to the object to a distance of 100.

Do I need to use getAzimuthalAngle() or getPolarAngle()?

Upvotes: 3

Views: 4192

Answers (2)

Aryan K
Aryan K

Reputation: 11

this will work. I was trying to load the GLTF model through this code snippet.

    loader.load('./demo-models/model-1/scene.gltf', function (gltf) {
         gltf.position.x -= 60
         scene.add(gltf.scene);
    });

But that didn't work out. So after debugging for a while, I realized I could play around with some parameters of the Perspective Camera. Well initially the first argument was 75 units which made my object way too far from the screen, I had to zoom in until I could get a clear view. Some code tweaks, it works the best when I set it to 1.

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

Upvotes: 1

prisoner849
prisoner849

Reputation: 17596

For example, like this, if you object is not in the center of a scene:

camera.position.sub(obj.position).setLength(100).add(obj.position);

If the object is in the center:

camera.position.setLength(100);

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(25, 0, 100);
var renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

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

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

var obj = new THREE.Mesh(new THREE.CubeGeometry(10, 10, 10), new THREE.MeshBasicMaterial({
  color: "red",
  wireframe: true
}));
obj.position.set(25, 0, 0);
scene.add(obj);
controls.target.copy(obj.position);
controls.update();

stepCloser.addEventListener("click", onClick, false);

function onClick() {
  camera.position.sub(obj.position).setLength(100).add(obj.position);
}

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<button id="stepCloser" style="position: absolute;">
  100 units to the object
</button>

Upvotes: 3

Related Questions