简体   繁体   中英

Rotating a vector around a sphere (simulating sun) in three.js

I am trying to adapt this code (which itself is a implementation of this ). I have gotten the general visualization and rendering to work, but I'm now trying to animate some realistic movement.

The point of the light source is determined by a normalized vector (for example THREE.Vector3(1, 0.75, 0) . The light will appear to be coming from the top right). Now what I would like to do is to have the vector rotate around the sphere in such a way that it seems like the sphere is orbiting the light source. But I can't figure out how to do this. I've tried updating/changing the position of the vector. But I'm not sure how to calculate the proper next x,y,z values. I've tried applying euler angles and rotational matrix, like so:

euler = new THREE.Euler(f,g,h, 'XYZ');
matrix = new THREE.Matrix4().makeRotationFromEuler(euler);
light = vector.applyMatrix4(matrix);

But here, I'm not sure how to get the correct values of f,g,h such that the light doesn't just wobble around the sphere.

Am I even on the right track?

Working example: http://jsfiddle.net/VsWb9/3890/

You are increasing linearly two of 3 coordinates in euler angles, that is the issue.

For other rotations than around x/y/z axis, the best for understanding/avoiding issues/coding/computational cost is to trust quaternions .

They are rather intuitive, in threejs too. They are made of 4 coordinates : 3 for a rotation axis, and the fourth for the rotation value.

var quat=new THREE.Quaternion();

//we set the axis around which the rotation will occur. It needs to be normalized
var axis=new THREE.Vector3(0,1,0).normalize();
//and the angle value (radians)
var angle=0;

//this is your light vector (=original position of your light)
var light=new THREE.Vector3(1,0,0).normalize();

Then in your render loop you change the angle value and tell the quaternion to use the axis above, and the updating angle :

angle+=.001//(or angle -= if your axis points in the +y direction like here)
quat.setFromAxisAngle(axis,angle);

And finally apply it :

light.applyQuaternion(quat);

Updated fiddle : http://jsfiddle.net/Atrahasis/0v93p2xy/


Note about normalized vectors :

  • a normalized vector is 1-unit length.
  • ( 1 , 0 , 0 ),( 0 , 1 , 0 ),( 0 , 0 , 1 ) are native-normalized vectors (and unit vectors).
  • ( 1 , .75 , 0 ) is not a normalized vector, its length is √(1²+.75²)=1.5625 (pythagoras)
  • for example ( 0.6614... , .75 , 0 ) is a normalized vector

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM