rendering

Principle and Code

Now that we’ve mastered the technique for generating random motion, let’s do something fun.

Our goal is to see if we can create random motion on a sphere. We’ll see that with some geometry, some trigonometry and our random motion algorithms, we can solve some seemingly impossible problems.

Let’s first look at geometry and trigonometric functions involved. It’s not too bad. Really.

In the spherical coordinate system, the position is determined by the distance (r) to the origin ([0,0,0]) (representing the radius), the Angle from an axis (we will use the z-axis)(we will call it phi), and the Angle of rotation about that axis (we will call it theta).

Check this graph:

If you’re familiar with trigonometric functions, the diagram above should give you all the information you need to figure out how to convert radii and two angles to x,y, and z coordinates.

Take a look at the code:

r = 50; //radius of sphere
segMin = 2; //minimum segment duration
segMax = 4; //maximum segment duration

end = 0;
j = 0;
while ( time >= end){
  j += 1;
  seedRandom(j,true);
  start = end;
  end += random(segMin,segMax);
}
endTheta =  random(0.Math.PI*2);
endPhi = random(0.Math.PI);
seedRandom(j-1.true);
dummy = random(); //this is a throw-away value
startTheta =  random(0.Math.PI*2);
startPhi = random(0.Math.PI);
theta = ease(time,start,end,startTheta,endTheta);
phi = ease(time,start,end,startPhi,endPhi);
sinPhi = Math.sin(phi);
x = r*Math.cos(theta)*sinPhi;
y = r*Math.sin(theta)*sinPhi;
z = r*Math.cos(phi);
center = thisComp.layer("center").position;
center + [x,y,z]
Copy the code

This is actually a combination of the formula for a point on the sphere and our expression for random motion.

To keep the star always facing the empty object in the center of the sphere, you simply add this orientation expression to each star:

lookAt(position,thisComp.layer("center").position)
Copy the code

To spice things up a bit, I added a random rotation expression to each star’s Z-rotation property:

segMin = 3.; //minimum segment duration
segMax = 7.; //maximum segment duration
minVal = -180;
maxVal = 180;

end = 0;
j = 0;
while ( time >= end){
  j += 1;
  seedRandom(j,true);
  start = end;
  end += random(segMin,segMax);
}
endVal =  random(minVal,maxVal);
seedRandom(j-1.true);
dummy=random(); //this is a throw-away value
startVal =  random(minVal,maxVal);
ease(time,start,end,startVal,endVal)
Copy the code

That’s it — we’ve generated 3D motion on a sphere with modest changes to the expression for random motion.