Friday, November 02, 2007

Came across a pretty cool way of rendering a 3D sphere on Paul Ortchanian's website today.

Click here to see the 3D sphere in action. Paul is very generous in sharing his work, you can see the full source code for 3D sphere on his site.

Let's jump in and figure out how Paul renders the 3D sphere.

outer loop with i going from -180 to 180
inner loop with j going from -180 to 180
_x = _path.centerX + Math.cos(i) * Math.cos(j)*_path.FL;
_y = _path.centerY + Math.cos(i) * Math.sin(j)*_path.FL;
inner loop end
out loop end


Let's see what the code in the inner loop and see what it is trying to do.
Assume for a sec the center is located at (0, 0), the location is now
_x = Math.cos(i) * Math.cos(j)*_path.FL;
_y = Math.cos(i) * Math.sin(j)*_path.FL;

As you know from high school math, you can draw a circle parametrically by using
x = radius * Math.cos(theta)
y = radius * Math.sin(theta)

So the above equation is essentially:
_x = Math.cos(i) * Math.cos(j)* radius;
_y = Math.cos(i) * Math.sin(j)* radius;

Notice the differing term between _x and _y is Math.cos(j) and Math.sin(j), which is responsible for drawing a circle. The Math.cos(i) term oscillates from 1 to -1 and back, in effect this creates a series of concentric circles by shrinking the radius of the circle from "radius" to a fraction of it (and back). All it takes now is to vary z from -1 to 1 for each circle using Math.sin or Math.cos and you have a 3D sphere!

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home