问题
I'm displaying an OBJ element with Three.js using WebGlRenderer, now I'd like to allow users to rotate the camera around the object in any direction, I've found this answer:
Rotate camera in Three.js with mouse
But both examples return me errors, the first says that projector is not defined, and I don't know what it means with "projector". I've just a simple camera, the object and some light. The second code says that undefined is not a function.
Does someone know how to get the result I need?
回答1:
This is what you want: http://threejs.org/examples/misc_controls_orbit.html
Include the orbit controls (after you have downloaded them):
<script src="js/controls/OrbitControls.js"></script>
Setup the variable:
var controls;
Attach the controls to the camera and add a listener:
controls = new THREE.OrbitControls( camera );
controls.addEventListener( 'change', render );
and in your animate function update the controls:
controls.update();
[Update] controls.autoRotate = true;
(tested in v73. Recent versions of OrbitControls.js has added this control.)
回答2:
Indeed, if you substitute 'camera' with the object of your choice, the object will rotate. But if there are other objects surrounding it (for example a grid on the floor), they will still stand still. That might be what you want, or it might look weird. (Imagine a chair rotating floating above the floor...?)
I choose to override the center object from OrbitControls.JS from my code after initializing the Orbit Controls
controls = new THREE.OrbitControls(camera, renderer.domElement);
…
controls.center = new THREE.Vector3(
chair.position.x,
chair.position.y,
chair.position.z
);
(disclaimer: I have the impression there are different versions of OrbitControls.js around, but I assume they all use this center-object)
回答3:
Add a listener to trigger render method on change of OrbitControl
:
const controls = new OrbitControls(camera, this.renderer.domElement);
controls.enableDamping = true; //damping
controls.dampingFactor = 0.25; //damping inertia
controls.enableZoom = true; //Zooming
controls.autoRotate = true; // enable rotation
controls.maxPolarAngle = Math.PI / 2; // Limit angle of visibility
controls.keys = {
LEFT: 37, //left arrow
UP: 38, // up arrow
RIGHT: 39, // right arrow
BOTTOM: 40 // down arrow
};
controls.addEventListener("change", () => {
if (this.renderer) this.renderer.render(this.scene, camera);
});
and in animate update controls:
start = () => {
if (!this.frameId) {
this.frameId = requestAnimationFrame(this.animate);
}
};
stop = () => {
cancelAnimationFrame(this.frameId);
};
renderScene = () => {
if (this.renderer) this.renderer.render(this.scene, camera);
};
animate = () => {
// update controls
controls.update();
}
来源:https://stackoverflow.com/questions/18466578/rotate-camera-around-object-with-three-js