# Random Motion

### Case Study: Random Motion on a Sphere

Now that we've got this cool technique for generating random motion, let's do something interesting.

The goal is to see if we can create random movement over the surface of a sphere. We'll see that with a little geometry, a little trigonometry and our random motion algorithm we can tackle something that might otherwise seem impossible.

First let's take a look at the geometry and the trig involved. It's not too bad. Really.

In a spherical coordinate system, positions are identified by the distance from the origin ([0,0,0]) which we'll refer to as "r" (for radius), the angle from one axis (we'll use the z axis), which we'll call "phi" and the angle of rotation around that axis (which we'll call "theta"). Examine this diagram:

If you're familiar with trigonometry the diagram above should give you all the info you need to figure out how we're going to translate our radius 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]
```

This is really just the merging of the formula for a point on the surface of a sphere with our random motion expression.

To get the stars to always face the null at the center of the sphere, you just add this orientation expression to each star:

```
lookAt(position,thisComp.layer("center").position)
```

Just to add a little interest, I added our random rotation expression to the z rotation property of each star:

```
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)
```

That's it - with a moderate change to the random motion expression we've generated 3D movement on a spherical surface.