user2212365
user2212365

Reputation: 95

THREE.js rotating camera around an object using orbit path

I am struggling in solving this problem.

On my scene, I have a camera which looks at the center of mass of an object. I have a some buttons that enable to set camera position on particular view (front view, back view,...) along a invisible sphere that surroung the object (constant radius).

When I click on the button, i would like the camera to move from its start position to the end position along the sphere surface. When camera moves I would like it to keep fixing center of mass of the object.

Has anyone have a clue on how to achieve this?

Thanks for help!

Upvotes: 2

Views: 3970

Answers (1)

Tim
Tim

Reputation: 761

If you are happy/prefer to use basic trigonometry then in your initialisation section you could do this:

var cameraAngle = 0;
var orbitRange = 100;
var orbitSpeed = 2 * Math.PI/180;
var desiredAngle = 90 * Math.PI/180;
...
camera.position.set(orbitRange,0,0);
camera.lookAt(myObject.position);

Then in your render/animate section you could do this:

if (cameraAngle == desiredAngle) { orbitSpeed = 0; }
else {
  cameraAngle += orbitSpeed;
  camera.position.x = Math.cos(cameraAngle) * orbitRange;
  camera.position.y = Math.sin(cameraAngle) * orbitRange;
}

Of course, your buttons would modify what the desiredAngle was (0°, 90°, 180° or 270° presumably), you need to rotate around the correct plane (I am rotating around the XY plane above), and you can play with the orbitRange and orbitSpeed until you hare happy.

You can also modify orbitSpeed as it moves along the orbit path, speeding up and slowing down at various cameraAngles for a smoother ride. This process is called 'tweening' and you could search on 'tween' or 'tweening' if you want to know more. I think Three.js has tweening support but have never looked into it.

Oh, also remember to set your camera's far property to be greater than orbitRadius or you will only see the front half of your object and, depending on what it is, that might look weird.

Upvotes: 3

Related Questions