Broxzier
Broxzier

Reputation: 2949

Rotating around a point gets closer and closer to it

I'm creating a web-application that's going to display 3D objects in a canvas. Now I came across this problem:

I am slowly rotating the camera around the scene so the 3D object can be looked at from all sides. For this I use this code (JavaScript):

var step = 0.1*Math.PI/180;
scene.camera.position.x = Math.cos(step) * (scene.camera.position.x - 0) - Math.sin(step) * (scene.camera.position.z - 0) + 0;
scene.camera.position.z = Math.sin(step) * (scene.camera.position.x - 0) + Math.cos(step) * (scene.camera.position.z - 0) + 0;

Those zeroes are the center of the scene, I leave them there in case we decide to use another base-origin.

This code will make the camera rotate around point 0,0, but it slowly gets closer and closer to it. Here are some screenshots to show you what it does:

Click for full view

There are no other parameters that have impact on the camera's position. I don't understand why it's doing this and what the problem could be.

Upvotes: 1

Views: 91

Answers (1)

Broxzier
Broxzier

Reputation: 2949

I found what was causing this issue: I change the camera's X position, then I change the camera's Z position with the new value of it's X position. Because this will be different the origin no longer is relatively at the same position for both calculations.

This was easy to fix, just by storing them into two new variables and then assigning them

var posx = Math.cos(step) * (scene.camera.position.x - 0) - Math.sin(step) * (scene.camera.position.z - 0) + 0;
var posz = Math.sin(step) * (scene.camera.position.x - 0) + Math.cos(step) * (scene.camera.position.z - 0) + 0;
scene.camera.position.x = posx;
scene.camera.position.z = posz;

Upvotes: 3

Related Questions