This is a sweet way to simulate flying through a 3d stack of images. You have to wait a few seconds for all 3 images to load. It uses very little processing power, and it’s fairly easy to understand. It uses this magic formula: scale = focalLength / (focalLength + z). My code here is very well commented, so I’ll let it do the talking. If you have any questions, just throw them in a comment.
Btw, the images are pulled from Flickr, from a very talented photographer.
Code:
//Declaring the URL, the Loader, and the XML variables var xmlURL:URLRequest = new URLRequest("images.xml"); var xmlLoader:URLLoader = new URLLoader(); var xml:XML;
//Declares the image array var imageArray:Array = new Array();
//Declares the variables needed for the 3D effect //Try playing around with the value of these variables to make it look different var focalLength:int = 50; var distance:int = 0; var distanceBetweenImages:int = 100;
//Telling the loader to load the URL xmlLoader.load(xmlURL);
//Detects when the loader has finished loading the data xmlLoader.addEventListener(Event.COMPLETE, parseXML);
//converts the loaded data into XML function parseXML(e:Event):void { xml = new XML(e.target.data); displayImages(); }
function displayImages():void { for (var k in xml.image) { //declares the movieclip that the image will be in var imageMC:MovieClip = new MovieClip();
//gets the URL for the image var imageURL:URLRequest = new URLRequest(xml.image[k]);
//declares the loader and loads the image var imageLoader:Loader = new Loader(); imageLoader.load(imageURL);
//adds the image to the movieclip imageMC.addChild(imageLoader);
//adds the image movieclip to the stage, and puts the image at the bottom of the image stack, //but above the background rectangle with the gradient, you will have to change this number //based on what you want to have behind your stack of images addChildAt(imageMC, 1);
//puts the image movieclip at a position imageMC.x = 18; imageMC.y = 20;
//adds the image movieclip to the array of images imageArray.push(imageMC); } }
function onEnterFrame(e:Event):void { //creates the distance from the screen to the first image in the stack of images //you can make this react to a scroll bar, or a slider, or anything you want //making it react to the mouse is just for this tutorials demonstrational purposes distance = (stage.stageWidth - stage.mouseX) - 200;
//loops through the image array for (var k in imageArray) { //puts the spacing between the images var z:int = distanceBetweenImages * k;
//figures out the scale var scale:Number = focalLength / (focalLength + (z + distance));
//puts limits on the scale, based on how the scale is computed //it is possible for it to be negative, we don't want that //makes the image invisible after it gets realls close if (scale > 1.2) { imageArray[k].visible = false;
//applies the scale to the image imageArray[k].scaleX = scale; imageArray[k].scaleY = scale;
//makes the image alpha the same as the scale, to add to the effect imageArray[k].alpha = scale;
//places the image at the center of the screen imageArray[k].x = (stage.stageWidth / 2) - (imageArray[k].width / 2); imageArray[k].y = (stage.stageHeight / 2) - (imageArray[k].height / 2); } }
It’s pulling the URLs for the images from a very simple XML file.
For this demo application, we’ve used the latest version of papervision3d with the code name GreatWhite. First of all, we need to include the papervision3d stuff.
These are all the classes we need for our application. The Camera3D class enables you to focus on a 3d object and zoom to it. Scene3D is a container that holds all 3d objects. The Viewport will be added to the main stage and is like a video screen that shows the result. Another important class is the BasicRenderEngine which renders all the objects from the scene with the current camera settings and outputs the result to the viewport. Papervision comes with different types of objects, but for our example we’ll only need the cube. And finally there are the materials which can be set to the objects. This is how papervision basically works.
Then we to set some constants for the sound channel
Next thing to do is to set the papervision variables
var viewport:Viewport3D; var scene:Scene3D; var camera:Camera3D; var cube:Cube; var renderer:BasicRenderEngine;
To keep a reference of each cube, we need to create 2 arrays. For each sound channel (left, right)
var cubesLeftChannel:Array = new Array(); var cubesRightChannel:Array = new Array();
At the end, we want to swing our camera from left to right and vice versa. To know in which direction we’re currently moving, we need to set a flag:
var bolAnimationForward:Boolean = true;
The next part is the same as in the previous tutorial. We create a new sound object and a url request for requesting the mp3 file. SndBytes will hold the current spectrum data.
var sndObject:Sound = new Sound(); var reqObject:URLRequest = new URLRequest("so-deep.ram2000.mp3"); var sndBytes:ByteArray = new ByteArray();
So, the next step will be the initializing of our 3d stuff, then loading the soundfile and finally creating the render loop. First of all, we create a new viewport and add it to the stage. The third parameter tells the viewport to use the whole width and height of the swf file for displaying the 3d objects.
viewport = new Viewport3D(0, 0, true); addChild(viewport);
Then we create a new basic render engine and a scene which holds the 3d objects
renderer = new BasicRenderEngine(); scene = new Scene3D();
Our cubes will need a material. We create a blue one for cubes that are displaying the left channel and a green material for the other ones. You can easily change the colors for each side using hex values.
var blueMaterial:MaterialsList = new MaterialsList( { front: new ColorMaterial(0x0066FF), back: new ColorMaterial(0x0066FF), right: new ColorMaterial(0x0046B0), left: new ColorMaterial(0x0046B0), top: new ColorMaterial(0x1171FF), bottom: new ColorMaterial(0x1171FF) } );
var greenMaterial:MaterialsList = new MaterialsList( { front: new ColorMaterial(0x00CC00), back: new ColorMaterial(0x00CC00), right: new ColorMaterial(0x009F00), left: new ColorMaterial(0x009F00), top: new ColorMaterial(0x00CC00), bottom: new ColorMaterial(0x00CC00) } );
Now we need to create the cubes for the left channel, position them correctly on the x-axis, keep a reference in the array and add them to the scene
for(var i = 0; i < cube =" new" x =" i">
The same procedure for the cubes standing for the right channel but with the green material and we place them between the green ones.
for(i = 0; i < cube =" new" x =" (i">
Finally we create a new camera, set the target to the cube in the middle, adjust the zoom and move the start position a bit to the upper left
camera = new Camera3D(); camera.zoom = 11; camera.target = cubesRightChannel[CUBES_PER_CHANNEL / 2 - 1] as Cube; camera.x -= 400; camera.y += 300;
Now we’re finished with creating all the necessary 3d stuff. Next thing to do is loading a sample mp3 file which is quite easy. We just load the url request we’ve created bevore and play the file.
sndObject.load(reqObject); sndObject.play();
The only thing left to do is the render loop. This loop will be executed on enter frame, in our case 60 times per second. First, we compute the spectrum and put the result in the defined byte array.
SoundMixer.computeSpectrum(sndBytes);
Then we set the right position for the byte array pointer, read the float value and assign it to the current cube scaleY value. Like this, the cubes will be resized according to the spectrum. After the end of the first loop, we repeat the procedure for the right channel cubes
for(var i = 0; i < cube =" cubesLeftChannel[i]" position =" CHANNEL_STEPS" scaley =" sndBytes.readFloat();" i =" 0;" mycube =" cubesRightChannel[i]" position =" 1024" scaley =" sndBytes.readFloat();">
To swing our camera a bit, we increase and decrease it’s x value
And now we need to tell the render engine to render the current scene, camera and viewport
renderer.renderScene(scene, camera, viewport);
That was already the whole trick. You can also try rendering other materials and different objects. These were just the basics about papervision3d. We hope you enjoyed reading this tutorial. Any feedbacks and questions are welcome.
// papervision vars var viewport:Viewport3D; var scene:Scene3D; var camera:Camera3D; var cube:Cube; var renderer:BasicRenderEngine;
// arrays holding references to cubes for each channel var cubesLeftChannel:Array = new Array(); var cubesRightChannel:Array = new Array(); // animation flag var bolAnimationForward:Boolean = true;
// sound vars var sndObject:Sound = new Sound(); var reqObject:URLRequest = new URLRequest("so-deep.ram2000.mp3"); var sndBytes:ByteArray = new ByteArray();
// INIT function init():void { init3D(); initSound(); // add event listener for render loop addEventListener(Event.ENTER_FRAME, renderLoop); }
// init3d function init3D():void { // Create viewport viewport = new Viewport3D(0, 0, true); // add viewport to stage addChild(viewport);
// create basic render engine renderer = new BasicRenderEngine();
// Create scene scene = new Scene3D();
// blue cube material var blueMaterial:MaterialsList = new MaterialsList( { front: new ColorMaterial(0x0066FF), back: new ColorMaterial(0x0066FF), right: new ColorMaterial(0x0046B0), left: new ColorMaterial(0x0046B0), top: new ColorMaterial(0x1171FF), bottom: new ColorMaterial(0x1171FF) } );
// green cube material var greenMaterial:MaterialsList = new MaterialsList( { front: new ColorMaterial(0x00CC00), back: new ColorMaterial(0x00CC00), right: new ColorMaterial(0x009F00), left: new ColorMaterial(0x009F00), top: new ColorMaterial(0x00CC00), bottom: new ColorMaterial(0x00CC00) } );
// create cubes for left channel for(var i = 0; i < cube =" new" x =" i" i =" 0;" cube =" new" x =" (i" camera =" new" zoom =" 11;" target =" cubesRightChannel[CUBES_PER_CHANNEL" i =" 0;" cube =" cubesLeftChannel[i]" position =" CHANNEL_STEPS" scaley =" sndBytes.readFloat();" i =" 0;" mycube =" cubesRightChannel[i]" position =" 1024" scaley =" sndBytes.readFloat();"> 800) bolAnimationForward = false; } else { camera.x -= 4; if(camera.x < -400) bolAnimationForward = true; } // render current scene renderer.renderScene(scene, camera, viewport); } init();
The purpose of this tutorial is to teach you the fine art of making a Flash 3D-engine. What this means is that we are going to find out how to take a set of 3D coordinates and transform them into 2D coordinates.
Limitations
My engine has a few limitations, some because this is a simpler "tutorial version", some because I was too lazy to implement the functions, some because the functions were to processor-consuming and last but not least those that I couldn't figure out:
no shadows
no solid faces
no curbs
etc.
This tutorial is definetely advanced so most of the time I won't include any images of the program since you probably know it perfectly. I've included one thing: an actionscript summary at the very end of the tutorial, for quick reference. Newbies, please stop reading now... The last thing I would like to say is that making a functional 3D engine is a kind of test, and you'll feel much prouder having figured it out all by yourselves. So if you want to give it a try, just check out the math link.
View Plane
As I've already said, we want to transform a set of 3D points into a set of 2D points. To do this we must somehow eliminate the third coordinate, the depth (z)to only have the x and the y left. However we cannot simply discard the depth information because we would lose the perspective. To keep the perspective, we must chose a point of view, the eye of the observer, and a view plane on which all the points are drawn. then for each point we trace the line between the eye and the point. We then calculate the coordinates of the intersection of the line and the plane: these are the 2D-coordinates of the point. Is this a bit complicated? Don't worry, I've made a picture:
To make the calculations a bit simpler (and the 3D engine faster) I've chosen to put the eye on the z-axis (eyex=0 and eyey=0). The view plane is parallel to the xy plane, that way every point on the plane has a fixed z and the 2D coordinates of each point are the x and y of the corresponding point on the view plane. The closer the view plane is to the object, the bigger it will appear. To change the zoom, we vary the position of the view-plane.
If you still haven't understood, I'm probably not such a good teacher and I can't help you anymore. However if you still want your engine you can just follow my step by step guideline and it will work. You should also take a look at the math page I link to here.
The Basic Movie
All right,let's start. We'll begin by making our basic bricks, the framework for our tutorial. This part will be as short as possible since I suppose that if you are trying this tutorial, you already feel quite at ease with flash. These are the things we need: Start by creating a new movie approximately 400*500 in size. Then create 3 layers: actions, buttons, and lines. Create 4 frames on the two last layers and insert ten blank key-frames on the actions layer. Now name these blank key frames in this order:
"model", for loading the points and lines
"start", for initiating all variables, etc.
"loop", for the basic program loop
"loop2"
"draw", for the drawing routine
"rotx", for the rotation around the x-axis
"roty", guess
"rotz", same again
"zoom", for calculating the zoom
"drawline", the line-drawing routine
Now we have the frame of our movie. Note that I am not making a preloader, you can do that all by yourselves!
Buttons, Line & Stuff
The buttons Now just create a simple button. It's only for the rotations and the zoom so you don't even need any second states. Now then again if you want to make it fancy, go ahead, no one will stop you. Place 8 instances of this button on the buttons layer, towards the bottom of the movie. We'll define their actions later.
The line This part is a bit more important since it determines whether your lines will be drawn correctly or not. Create a new movie clip and name it baseline. In it, draw a simple black line directed from the top left to the bottom right. Then select this line and set its length to 100px and its width to 100px. Now you should have a line that's oriented 45° downwards. Also, the good thing about it is that it's lenght in pixels is equal to its length in percent, so you can easily set its size with SetProperty. Now place one instance of this line on the lines layer. Name it baseline.
The extra stuff Just add some simple stuff such as a title, your name and preferably mine too (or some kind of a small note saying "original idea by KStor, but now my much better version" etc.) Also add an editable text-field. Name the corresponding variable zoomvalue. This will be used to display the value of the zoom.
The Math
This part of the tute is purely theoretical. It's a very simple explanation of the math I use (actually you'll notice it's not an explanation at all but just a couple of formulas)You don't have to read it if you don't care about how the tute works, but it's kind of interesting to know. On the other hand, if you want to know more, click here. The math we use is coordinates geometry in space. Let's start out with some definitions.
Vector A vector is an abstract kind of notion (that's an easy way of saying I don't know what it is) but very practical. It basically consists of a line drawn from the origin (0,0,0) to a point (x,y,z). It can also be thought of as a direction from one point to another: x units along the x-axis, y units along the y-axis and z units along the z-axis. The vector is defined by the three coordinates x, y and z.
Line equation A line can be described as all the points aligned with two points A (0x,0y,0z) and B. That way, it is defined by its origin A and the vector (dx,dy,dz) going from A to B. The equation looks like this: point = org + k * dir or with the coordinates (x,y,z) = (0x,0y,0z) + k * (dx,dy,dz) ,k being any real number.
Plane equation A plane is a surface that can be described by a normal vector (dx,dy,dz), ie a direction the plane is facinng, and a value k, indicating the position of the plane along this vector. The equation is: point * normal = k or with the coordinates (x,y,z) * (dx,dy,dz) = k, k being any real number.
Intersection of a plane and a line The line equation looks like this: point = org + u * dir. We have to find the value of u corresponding to the intersection. Using the plane equation, we find u = (k - org * normal) / (dir * normal) We then plug this into the line equation and find the coordinates of the point.
The model is the way our 3D object is coded, the way we define it mathematically. As I said in the introduction my 3D-engine is used mainly for lines, ie two connected points. Therefore, my model consists of two main parts: the coordinates of the points and the lines to be drawn. Added to this are the eyez, the maximum zoom value and the original zoom.
The points The points are coded in one long variable called points. They are coded this way:
"x1,y1,z1Rx2,y2,z2Rx3...Rxn,yn,zn"
xn, yn and zn are the x, y and z coordinates of point number "n". They contain three digits, so 50 will be coded "050", 6 will be coded "006", etc. Each point is separated by an "R" to make editing easier. You must also create a variable named totalpoints that contains the total number n of points.
The lines The lines are defined by the numbers of their extremeties. For example the line from point 7 to point 11 will be coded "0711". They are stored in a large variable named line:
"p1p'1Rp2p'2Rp3...Rpmp'm"
pm is one extremity of the line number m, p'm is the second extremity. Each point is coded by two digits, so point number 2 will be coded "02" and point 11 will become "11". You'll notice that as a result, my engine only accepts 99 points. If you need more, it's easy to change. However too many points will slow it down quite a bit (I haven't tried). You must also create a variable named totallines that contains the total number m of lines.
The Model (con't)
The other variables To this we have to add three extra variables that define the general way the object appears. First is the eyez, the z coordinate of the point of view. It should be negative. The further it is from the object, the less perspective there will be. In my example I set it to -500, my closest point being at -99. It's a pretty good value. Second is the maxzoom. This value is the z position of the view plane when the zoom is 100 percent. Be careful so that this value always is bigger than the eyez but smaller than the minimum possible z coordinate for any of your points after a rotation. For example when I rotate my point at z=-99, it will get closer to z=-140, so my maxzoom has to be lower than say 150. Third is the initial value of the zoom, set between 5 percent and 100. the variable is called zoom.
The cube These are all the variables you need to set. Now I'm going to give you the variables corresponding to a cube. Open the first key-frame of the actions layer. Then set this:
Set Variable: "totalpoints" = "8" Set Variable: "points" = "099,099R099,099,099R-99,099,-99R 099,099,-99R-99,-99,099R099,-99,099R-99,-99,-99R099,-99,-99R-99" Set Variable: "totallines" = "12" Set Variable: "lines" = "0102R0103R0105R0804R0806R0807R0506R 0507R0307R0304R0206R0204" Set Variable: "eyez" = "-500" Set Variable: "maxzoom" = "-200" Set Variable: "zoom" = "75"
Now your model is set up and we can start building the engine.
The Routine
Now comes the real part: the engine program itself.
The loading setup First we are going to create the initiation routine, the one that starts it all out. Open the second key-frame of the actions layer. This is what we do:
move the baseline instance so that no one can see it on the picture.
Set Property ("/baseline", X Position) = "1000"
then let's cut the points variable up into lots of separate coordinate variables:
Set Variable: "n" = "1" Loop While (n <= totalpoints) Set Variable: "x"&n = Substring (points,( (n-1) * 12 + 1), 3 ) Set Variable: "y"&n = Substring (points, ((n-1 ) * 12 + 5), 3 ) Set Variable: "z"&n = Substring (points, ((n-1) * 12 + 9), 3 ) Set Variable: "n" = n+1 End Loop
This places the x-coordinate of point 1 in variable x1, the y-coordinate in y1, the z in z1 and the same thing for all other points.
now we do the same thing for the lines variable:
Set Variable: "n" = "1" Loop While (n <=totallines) Set Variable: "pt1"&n = Substring (lines, (n-1)*5+1, 2 ) Set Variable: "pt2"&n = Substring (lines, (n-1)*5+3, 2 ) Set Variable: "n" = n+1 End Loop
The first end of point 1 is put in pt11, the second one in pt21, etc.
set the center of the display. These are the coordinates of point (0,0) in the movie.
Set Variable: "centerx" = "190" Set Variable: "centery" = "215"
That's all for the initial frame
The Routine (con't)
The loop Next we are just going to set up the basic loop. This will be used later for the zoom and the rotations. Open the 4th frame loop2 and enter
Go to and Play ("loop")
The zoom routine (part 1) We now have to make a basic zoom routine to transform the zoom value in percent into the z-coordinate of the view plane. We'll make the zoom buttons in a while. They way we do our conversion is to take a percent of the distance between the eyez (minimal zoom position) and the maxzoom position, and add the maxzoom. This way the z of the view plane takes values between eyez and maxzoom when the zoom takes values between 0 and 100 percent. Open the next to last keyframe zoom and enter this:
The depth variable contains the z-coordinate of the zoom plane. The draw command is the central routine of our engine, we'll build it soon. Also add this command to set the zoomvalue variable so the zoom shows up.
Set Variable: "zoomvalue" = "zoom= " & zoom & "%"
The drawline routine This is the last thing we have to do before the drawing routine it self. This routine will be used to draw the line linking two points. The way it works is that the baseline is duplicated and its size and position are adjusted to correspond to the points (it works, that's all that counts).
Set Variable: "pt1" = eval("pt1"&n) Set Variable: "pt2" = eval("pt2"&n) Set Property ("line"&n, X Position) = eval("2Dx"&pt1) Set Property ("line"&n, Y Position) = eval("2Dy"&pt1) Set Property ("line"&n, X Scale) = eval("2Dx"&pt2) - eval("2Dx"&pt1) Set Property ("line"&n, Y Scale) = eval("2Dy"&pt2) - eval("2Dy"&pt1)
If the number of the line is stored in variable n, the line number n is drawn.
The drawing routine This is the very core of the engine: the program that converts the 3D coordinates to 2D coordinates (as explained in The Math). In the fifth frame, draw, enter this:
Set Variable: "normalz" = depth * depth
Normalz is the value k in the plane equation, depth being the z-coordinate of the normal vector of the view-plane (the plane being parallel to the xy plane, the vectors coordinates are (0,0,depth))
Set Variable: "n" = "1" Loop While (n<=totalpoints) Set Variable: "u" = (depth - eyez)/(eval("z"&n) - eyez) If (n<=9) Set Variable: "2Dx0"&n = u * eval("x"&n) + centerx Set Variable: "2Dy0"&n = u * eval("y"&n) + centery Else Set Variable: "2Dx"&n = u * eval("x"&n) + centerx Set Variable: "2Dy"&n = u * eval("y"&n) + centery End If Set Variable: "n" = n + 1 End Loop
This part is a bit more complicated. We actually convert the 3D coordinates to 2D coordinates. For each point, we first calculate the value u as explained in The Math. Then we recalculate the 2D coordinates by multiplying the 3d coordinates by u. I can't explain exactly what I've done here but if you study the math link I gave you should be able to understand it.
Set Variable: "n" = "1" Loop While (n<=totallines) Duplicate Movie Clip ("/baseline", "line" & n, n) Call ("drawline") Set Variable: "n" = n + 1 End Loop
Finally we just draw the the lines by duplicating the basic movie clip and calling the drawline frame.
Ok, now your 3D engine is basically finished. But we also want a zoom and rotations. That's easy, follow the guide!
The Zoom
Let's work out the zoom. We really don't have very much to do, since most of it has alreday been done. Each time the main loop is looped it adds a certain value to the zoom (or substracts). When you roll over the zoom buttons, they change the value added from 0 to a positive or negative value (zoom in or out). When you roll out they reset it to 0.
First open the start frame(n°2) and add this code just after the setting of the xcenter and the ycenter.
Set Variable: "zm" = "0"
This initiates the zm variable, which indicates by how much the zoom should be changed.
Now open the loop layer and add this:
Call ("zoom") Call ("draw")
That way the zoom routine is called every time the engine loops. The draw routine is also called to refresh.
Let's continue the zoom routine. Open the next to last frame zoom. Normally we only have two commands: the calculation of the depth and the setting of the zoomvalue. Before this we are going to add a new command:
Set Variable: "zoom" = zoom + zm If (zoom> 100) Set Variable: "zoom" = 100 End If If (zoom <10)> First we add the zm value to the zoom, then we check that it doesn't exceed 100% or go under 10% (under ten percent the object gets too small). Last we set the buttons: double-click on your zoom-in button (any one of your eight buttons). Then set these actions:
On (Roll Over) Set Variable: "zm" = "5" End On On (Release, Roll Out) Set Variable: "zm" = "0" End On
I don't think this needs to be explained: while the mouse is over the button, the zoom increases by 5 percent at every loop. Now set the same thing for the zoom-out button but with "zm"="-5"
The Rotations
This is the last thing we have to do to have our functional 3D engine. The rotation works in a similar way to the zoom. We set two basic basesin and basecos variables. These contain the values of sin 10° and cos 10°. Then while one of the rotation buttons is rolled over the coordinates of all points are rotated around the corresponding axis by 10° at each loop. The rotation frames work with a sin variable and a cos variable, so the zoombuttons only load values in sin and cos and set an axis variable to x, y or z depending on the axis that should be rotated around.
First we modify the start frame. After all the rest we first set the basesin and basecos:
Set Variable: "basecos" = 0.9848 Set Variable: "basesin" = 0.1736
Then we call an initial rotation around the y-axis and the x-axis:
Set Variable: "sin" = basesin Set Variable: "cos" = basecos Call ("rotx") Call ("roty")
Now we change the loop frame. Add this:
Call ("rot"&axis)
This way the rotation is called at every loop. Notice that if axis=none then there will be no rotation since there is no rotnone frame.
Now we are going to do the buttons:
open your first button (say the up-rotation around the x-axis). Enter this
On (Roll Over) Set Variable: "sin" = - basesin Set Variable: "cos" = basecos Set Variable: "axis" = "x" End On On (Release, Roll Out) Set Variable: "axis" = "none" End On
The sign of the sine determines which direction the object turns. When you roll over the button, the axis turned around is set to x, and the sin and cos are stored. When you roll out, the axis is set to none. The principle is the same for all the other buttons, but with different values.
x-axis down rotation
Set Variable: "sin" = basesin Set Variable: "cos" = basecos Set Variable: "axis" = "x"
y-axis right-rotation
Set Variable: "sin" = - basesin Set Variable: "cos" = basecos Set Variable: "axis" = "y"
y-axis left-rotation
Set Variable: "sin" = - basesin Set Variable: "cos" = basecos Set Variable: "axis" = "y"
z-axis rotation(1)
Set Variable: "sin" = - basesin Set Variable: "cos" = basecos Set Variable: "axis" = "z"
z-axis rotation(2)
Set Variable: "sin" = basesin Set Variable: "cos" = basecos Set Variable: "axis" = "z"
The last thing we have to do to make our rotation functional is obviously to program the rot frames. This is a simple use of the math-formulas. Open the rotx frame and enter this
Set Variable: "n" = "1" Loop While (n<=totalpoints) Set Variable: "tmp" = (sin * eval("y"&n)) + ( cos * eval("z"&n)) Set Variable: "y"&n = cos * eval("y"&n) - sin * eval("z"&n) Set Variable: "z"&n = tmp Set Variable: "n" = n + 1 End Loop
If you check this out it corresponds to the formulas in The Math. Now do the same for the roty frame:
Set Variable: "n" = "1" Loop While (n<=totalpoints) Set Variable: "tmp" = - (sin * eval("x"&n)) + ( cos * eval("z"&n)) Set Variable: "x"&n = cos * eval("x"&n) + sin * eval("z"&n) Set Variable: "z"&n = tmp Set Variable: "n" = n + 1 End Loop
and for the rotz frame:
Set Variable: "n" = "1" Loop While (n<=totalpoints) Set Variable: "tmp" = (sin * eval("x"&n)) + ( cos * eval("y"&n)) Set Variable: "x"&n = cos * eval("x"&n) - sin * eval("y"&n) Set Variable: "y"&n = tmp Set Variable: "n" = n + 1 End Loop
That's all, your engine is finished!
Finished
OK, here it is. After hard work the engine is finally finished. You might not have understood everything, the math isn't really easy and I didn't explain very much. However if you study the math link you should be able to understand it pretty easily. To finish off here's some extra stuff I want to tell you:
Actionscript summary
Model standard This little paragraph is to deal about other 3D engines. I've seen a few, only two which draw lines and of the same level as mine. Their coding of points is equal or very similar to mine. Their lines were coded without the separating R to distinguish lines. This is both inconsistent with the points coding and not very practical. That's why I used my coding, and I suggest that it could be used as a preliminary standard for Flash 3D engines.
I had a hard time coding 3D lighting of a diamond-like object built out of (triangular) facets. Not that the code was giving me headaches, but my math skills are quite rusty ;-) The results of my findings are in this tutorial. I'll show you how to code the lighting of an object by a pinpoint light source moving over a sphere. No stress, I'll help you recall the trigonometry basics and illustrate the steps along the way. I however will assume some knowledge of flash, like making MCs, functions, the attachMovie scripting (+linkage), etc.
First play around with the my result of the adventure in math to come ;-)
PS. The light source can be set to manual: it'll then follow your mouse instead of following the path of a deltoid. Use the menu.
Next chapter I'll explain how to visualize the point you'd want your light to be most fierce, then we'll go over the math. After that I'll discuss chunks of code and we'll end with the whole script.
Pseudo 3D
As you can see we are working on a top view graphic. To show more clearly what we are trying to accomplish, here's an object at different angles:
My trick to faking 3D is to re-calculate the angles of all facets of the object into 2 angles: z-axis and xy-axis. The farther the light moves away from these coordinates projected on the sphere, the dimmer the lighting gets. That's where the trigonometrics come in handy. There alse is a way of doing this more accurate by using matrixes for every coordinate, but my math knowledge on that is even more rusty!. For this tutorial skipping the matrixes will also do just fine.
In-depth: The Math
We'll have to calculate a number of things:
the angle of the facets on the z-axis
the angle of the facets on the xy-axis
the angle of the light source on the z-axis - the light source has a fixed distance: the radius of the sphere
the angle of the light source on the xy-axis
the whiteness of each facet - depending on both angle (50%) and distance (50%) of the light source
the path the light source will follow in 'automatic' mode
What was the deal with these trigonometric functions again?
sin(a) = B / C
cos(a) = A / C
tan(a) = B / A
sin(b) = 1 (deg)
cos(b) = 0 (deg)
tan(b) = endless
sin(c) = A / C
cos(c) = B / C
tan(c) = A / B
And this pythagoras thingy?
C = sqrt(A*A + B*B)
Important! - Flash works in radians! The formula for calculating degrees from radians is:
radian = math.PI/180 * degree
Calculating the facet angles
To save me some serious paper filling calculations I've built in an angle detector (it's the lower left button). Just drag point1 and point2 parallel with the desired angle ;-) The front and side view can be accesed with the top right button. The use of atan is discussed in the next topic. The formula code is on the angle detection line mc:
onClipEvent (enterFrame) { //place the line between mcs point1 and point2 //notice the width and height of this line are 100 this._x = _root.angledetect.point1._x; this._y = _root.angledetect.point1._y; this._xscale = (_root.angledetect.point2._x-_root.angledetect.point1._x); this._yscale = (_root.angledetect.point2._y-_root.angledetect.point1._y); // Math.atan for angles xa= this._width; ya= this._height; _parent.angle=(Math.atan(ya/xa))/(Math.PI/180); // ------------------------------- // make less decimals and calculate angle2 _parent.angle=(int(_parent.angle*100))/100 _parent.point1.angle= _parent.angle _parent.point2.angle= 90 - _parent.angle // ------------------------------- }
The light source angle on the xy-axis
We'll use Math.atan to calculate this angle: we know A and B (distance base to light source on x and on y):
xt= xm - xb; yt= ym - yb;
xb and yb are the base coordinates, xm and ym the coordinates of the light source.
This function gives a flash angle, further on we'll recalculate this angle to an angle between 0 and 360 degrees.
The light source angle on the z axis
The fixed distance of the light source lets us calculate the angle it has. We know that side (C) will be the radius of the sphere, in this case 180. We calculate A (DeltaX) by using pythagoras on xt and yt.
_root.DeltaX=Math.sqrt(xt*xt+yt*yt);
Then we use the Math.acos on A and C to calculate the z-angle:
This'll return any angle to one between 0 and 360 degrees counting from 0 at the top clockwise to 360.
On to the whiteness!
Each facet calculates it's own whiteness. The whiteness is done by setting the _alpha of a white facet MC over the background of the object. Each facet has 2 variables: FacetX (its xy-angle) and FacetZ (its z-angle). We'll use the Math.cos function so that one side of the object is lit (cos(x)=1) and the other side is not (cos(x)=-1).
function SinMouseX(AngleX) { return Math.cos(Math.PI/180 * (_root.DgrMouseX - AngleX)); }
AngleX= FacetX
This function sets the most fierce point at FacetX and the less fierce point at (FacetX - 180) degrees. Then we set the _alpha. The ratio is 50% so z-angle and xy-angle have an equally strong influence:
function AlphaMouseX(Z,X) { return ((_root.DgrMouseZ/Z) * _root.ratio + X * (100 - _root.ratio)); }
Z= FacetZ
X= FacetX
The light source
The light source is symbolized by xm and ym. These coordintates either represent the coordinates of the mouse, or are put on the path of a function. For this path I chose a deltoid. I found this function on this page written by Paul Bourke in 1990. I made a button to switch between 'manual' and 'automatic', the if statements handles that. The variable i represents theta needed to make steps in the deltoid function. The _root.light mc is a white circle representing the light source.
// making the light move ----- i++; if (i>= 360) { i=i - 360 } // must be in radians (not degrees) theta=(_root.convrad) * i; // ------------------------------- // path of lightsource ----------- if (_root.lightsource == "manual") { xm = _root._xmouse; ym = _root._ymouse; } else if (_root.lightsource == "automatic"){ // you can replace this function for any other you like better xm = xb + (2 * a * Math.cos(theta) + a * Math.cos(2 * theta)); ym = yb + (2 * a * Math.sin(theta) - a * Math.sin(2 * theta)); } // -------------------------------
The Code
Most of the code hangs on the light source:
onClipEvent(load) { this._x=414.0; this._y=198.0; // a * 3 is radius of circle ----- a = 59; i = 0; _root.ratio=50; _root.convrad=Math.PI/180 // x base & y base (in stead of 0,0) xb = 198.0; yb = 198.0; function SinMouseX(AngleX) { return Math.cos(Math.PI/180 * (_root.DgrMouseX - AngleX)); } function AlphaMouseX(Z,X) { return ((_root.DgrMouseZ/Z) * _root.ratio + X * (100 - _root.ratio)); } } onClipEvent(enterFrame) { // making the light move ----- i++; if (i>= 360) { i=i - 360 } // must be in radians (not degrees) theta=(_root.convrad) * i; // ------------------------------- // path of lightsource ----------- if (_root.lightsource == "manual") { xm = _root._xmouse; ym = _root._ymouse; } else if (_root.lightsource == "automatic"){ xm = xb + (2 * a * Math.cos(theta) + a * Math.cos(2 * theta)); ym = yb + (2 * a * Math.sin(theta) - a * Math.sin(2 * theta)); } // ------------------------------- // pythagoras for angle mouse & x,ybase xt= xm - xb; yt= ym - yb; _root.DeltaX=Math.sqrt(xt * xt + yt * yt); // ------------------------------- // z is angle upwards: x,ybase -> light = radius = 180 _root.DgrMouseZ=int(Math.acos(_root.DeltaX/180) / _root.convrad); _root.DgrMouseX=int(Math.atan(yt/xt) / _root.convrad); // ------------------------------- // recompute flash-angles to normal-angles if(xt <0> 0){ _root.DgrMouseX += 270; } else if(xt <0>= 0 && yt <= 0){ _root.DgrMouseX += 90; } else if(xt>= 0 && yt>= 0){ _root.DgrMouseX += 90; } // ------------------------------- }
This is the code on the facets:
onClipEvent(load) { // angle of this facet ----------- FacetZ=45; FacetX=63.75; } onClipEvent(enterFrame) { XTemp=_root.light.SinMouseX(FacetX); // set alpha this._alpha = _root.light.AlphaMouseX(FacetZ,XTemp); }
The End
Well that's it really. I started out with one object and ended with the diamond. Meanwhile I thought up some nice things you could do with this code and how I could expand further. But I think I won't develop this further for now, I got what I needed, and if people'd like to make complete 3D engines with rotating objects or lights that have spherical forms instead of a pinpointed one, be my guest ;-)
Hello there flash users! In this tutorial, we will try to create a 3 Dimensional flower like this:
Now, let's list out the things we want to do:(This will be a good idea for any movie clip)
We want a 3D Flower rotating in a black background.
It should change it's color as it rotates.
It must rotate along with the mouse, i.e., it should respond to the mouse.
It must look real enough so that the user believes it is really a 3d flower.
Now, lets work out the logic, formulae, etc.
The Logic
Before you can even know the logic, you must understand a few points:
Flash 5 has practically no capability to do anything in 3d space.
Flash cannot also draw any lines or objects at runtime.
Complex 3d objects can cause it to become a nightmare in slow machines(like mine, a PII 350).
Now that you have understood these facts, you can go and design a logic:
You need to first specify the number of vertices an object is made up of, what points are connected and where they are located in 3 dimensional space.
You need to then rotate the object virtually, i.e., you must rotate an object that does not even exist. You can do this using trignometrical formulae(No, they are the easiest part of the apple).
Since Flash does not draw 3d, you must convert the 3D Points (with 3 co-ordinates x,y,z) to 2D Points(with 2 co-ordinates x & y). You can do this too by using simple formulae.(Now don't think that life's easy)
Then you must draw lines or circles connecting the 2D vertices got from the previous step. You can do this by using a small movieclip with a 45 degree line and then duplicating it and positioning it.
Then you must rotate this object every time the mouse moves.
We will do all the above one by one in the following steps.
Prepare the Stage
Open Flash 5. Press Ctrl+N to create a new movie. Press Ctrl+M to open Movie Properties. Give Frame Rate to 21. Set movie width and height to 700 and 525 pixels respectively. Any size is acceptable, as long as you change some of the variables you will come across as required. Also, change the background of the movie clip to black or some other dark color. We want the flower to stand out from the background.
Press F5 twice to make the movie three frames long. Click on the new layer icon thrice to create three new layers. Now name the layers as Miscellaneous, Scripts, Lines and vertices. Now, the time line should look like this:
Now, we need to create a few movieclips. But don't worry: the majority of the work will be done in the ActionScript Window later. Press Ctrl+F8 to create a new symbol. Name it as 'Vertex' and give behavior as MovieClip.
Now, Enter some text or anything. If it was text or some other movie clip, then press Ctrl+B to break it apart, or the alpha effects won't work. This is optional. You can even leave the movie clip empty. You just need the movieclip to hold some variables.
Now go back to the main scene. Click on the vertices layer. Drag the vertex movie clip from the library window(If you don't see the Library, press Ctrl+L to see it) on to the stage. If you don't see the Instance Pane, press Ctrl+I to open the Instance Pane. In that, give the name of the Vertex movieclip instance as point.
Press Ctrl+F8 to create a new movieclip named Line.
Press O to select the Oval tool.
Press the Click on the pencil button under the colors toolbar.
Then click on the no-Color icon under the colors toolbar.
Holding down the shift key, draw a circle.
Press V to enable the Arrow tool. Click on the circle to select it.
Click on Window - Panels - Transform to open the transform panel. Now, Click on the Skew Radio button and enter the two field's values as -40 and 35. The panel should look like this:
Click outside the circle to deselect the skewed circle. Now select it again by clicking on it.
If you donot see the info Panel, press Ctrl+Alt+I to invoke the info toolbar.
Enter W and H values as 100. If you see an icon similar to in the panel, click on the white box in the top left of that icon to get this icon:
Now enter X and Y values as 0 and 0.
Your workspace should look something like below
When done with the circle, click on the ' Scene 1' button on the top left above the timeline to go back to the Main Stage.
Click on the Lines layer. Now drag the Line movieclip from the Library window onto the stage. Now, press Ctrl+I to invoke the Instances Panel. Now give the Line MovieClip instance the name 'wire'.
Press F8 to create a new button. Give it any name you like.
Hit F5 thrice and then draw a small box or circle around the plus sign.
Go back to the main stage by clicking on the Scene 1 button on the top left.
Click on the Miscellaneous layer and then drag the button movieclip onto the stage.
Note: Make sure that all the three symbols are placed in the main stage outisde the viewable area. To do this,press Ctrl+2and drag the symbols to the grey area.
The Panel
Now that the stage is all set, we can go on to the ActionScripting part. But first, click on the first frame of the Scripts layer and press F6 to create a keyframe. If you don't see the Actions window, Press Ctrl+Alt+A to invoke the actions panel.
Most probably, you would end up with a panel like this:
Now, press the Small arrow in between the two vertical panes to hide the left pane. If it is already hidden, leave this step.
Now, press on the blank white space in the panel. Press Ctrl+E to shift to expert mode. This step is required only if you are in Normal mode, i.e., you cannot enter the script directly.
Now, resize the Actions panel as large as you can. But make sure that you can see it fully. In a fully maximized Flash window at 800 X 600 Resolution, you can get this big:
The Variables
Now, let's start with the scripting. We need to initialize certain variables and arrays. To the Java or C programmers, the first frame is like a constructor. It only runs once and has all the initializations and methods.
First, we need to initialize two variables, points and lines. Points defines the number of points the our 3d Object is made up of. Lines defines the number of lines our object consist of. For our objects, the following lines would be neccessary:
Points = 11; Lines = 10;
Now, a variable named viewport defines the zooming component of the screen. An initial value of 500 would be likely.
Viewport = 500;
We will now declare a variable having a formula to convert degrees to radians. We will need this later.
rad = (3.14*2)/360;
We need two arrays to contain the properties of our object. One is the line array, containing the properties of the lines. Another is the vertex array, containing the properties of each vertex. So, enter the following lines:
line = new Array(Lines); vertex = new Array(Points);
Because this movie is just to show off the 3d capabilities of flash, viewing it fullscreen would be more beautiful. So, enter the following line:
fscommand ("fullScreen", true);
Next, we need to duplicate the line and the point movieclips. Enter the following lines to do it:
for (i=0; i != Lines; i++) { wire.DuplicateMovieClip("l" add i, i); line[i] = eval("l" add i); } for (i=0; i != Points; i++) { point.DuplicateMovieClip("v" add i, (Lines*2)+i); vertex[i] = eval("v" add i); }
Explanation: The 1st for loop loops and duplicates the line movieclip until the number movieclips is equal to the value specified in the Lines variable. The 2nd loop creates n duplicates of the wire movieclip where n denotes the value of the variable of points. You could see that in both the loops, there is an eval function which assigns each duplicated movieclip a slot in the array we created in Step 4. This makes it easier to refer to their properties and the variables contained in them later.
Plot the Points
Here is a property in flash actionscript not everyone knows; As a matter of fact, even I learnt it just before making this movie. It goes like this: Because we have assigned a array slot to each movieclip, each array becomes like an object. Similar to java, we can have variables for each object, apart from their properties. That is, we can have 3 variables x,y and z for each array element to store the co-ordinates of each vertex. So let's put it to use. What we are going to do now is give each vertex its position in the 3 dimensional world. Because flash is not equipped to do this in any decent manner, we have a boring part of typing an awful lot of lines. We have to give the x,y,z co-ordinates for each vertex. In this tutorial, however, it is going to be easy as all you have to do is copy the following code and paste it in the action script window.
Now, we need to give the location of all the vertices. So, just copy the following code into the actionscript window of Flash:
As you can see, the values and the number of lines itself will differ for each object and you have to experiment with this to get a rough idea of where a -100,-100,-100 point will lie after rendering. I can explain that to you, however, that will be beyond the scope of this tutorial. And the .x, .y, .z are mere variables which can be assigned to an object array.
Remember when you were a kid and played those 'Join the Dots' games in the books? Well, you are going to do that again. This time, it will be in 3 dimensions. Here too, you will use the object array logic to store the variables. All you have to do is specify the two points to which each line is connected. So, we will need two variables a and b for each line. We will use the line array. Just copy the following code and paste it into the flash actionscript window:
The values assigned to them might be confusing, but if you see, they will say the number of the vertex in the vertex array to which they are connected. For example, the line 'line[0].a=0' says that it is connected to the vertex contained in the vertex array at the location of 0. Now, if your imagination powers are excellent and you are good in math, you will see that all this means to describe a err... flower like object.
Be sure that all the scripts mentioned in this page and all other previous pages are all placed in order in the first frame's actions. Also, place the upcoming scripts in the first frame itself, until or otherwise, specified.
A little this way
Note: If you find that any of the following has something common with the 'Advanced Math' Professor from the College you studied in, it is purely incidental.
But actually, it has something that you might remember studying in High School. It's actually the trignometrical formulae you will use to rotate the vertices "virtually" and then project it on to the screen.
The Logic: Now we have to workout the logic; You might say that "but we did that a long time ago!", but then, you read the note above: It's just as confusing as Advanced Math. You just can't understand it by reading it. So, let's go.
First, let's note that, we can rotate only one axis at a time. So, we need 3 sets of 3 variables for each vertex to rotate it along all the axes. We will then apply the formula, to rotate it on the x axis. We will store the rotated values in a new set of 3 variables. We will then apply the formula to rotate it on the y axis on the newly created set of 3 variables. We will then store the result in the next set of 3 variables. We will repeat it for the z axis rotation.
Now read the above paragraph again and again until you get it right.
Now, an important point: Although you can use the formula to rotate the object using just degree measure, Flash can calculate sine and cos values only with radian measure. So, you need to convert the degree to radian before you can use the sine and cos functions.
After rotating the object, we need to apply some formula to convert the x,y,z co-ordinates to just x,y co-ordinates, that is, convert the 3d address to a 2d address. That too will be done induvidually for each axes using formulae and the result is stored in two new variables.
After converting the object to 2d, we will have to draw the lines and vertices. We will use a for loop for doing this. We will adjust the _x,_y,_xscale,_yscale and _alpha properties of each movieclip to do this.
We will use three methods, each one for rotating, projecting and rendering the object.
We will do this next.
The Rotation
Now just copy and paste the following code into the first frame's actionscript window:
Now don't think that it is too difficult, we will break it down.
First, the parameters of the Rotate function recieve the number of degrees to be rotated in each axis.
The next 3 lines assign the radx,rady and radz variables the 'converted to radian' values of x, y and z variables. If you have poor memory, let me remind you that the rad variable you multiply with the x,y and z variables is actually a formula used to convert degrees to radians. We declared this variable in the first itself.
Next a for loop loops n number of times where n denotes the value of the points variable.
Inside the for loop, the formula for rotating the vertex in each axis is executed. Explaining each line would end up only in pages of explanation. So, try to figure it out all by yourself.
3d to 2d
Now that the object rotation script is over, we need to convert it to 2d. This is relatively simple. Just a few lines. Copy the following lines of code to the action script window:
function toScreen () { for (i=0; i != Points; i++) { vertex[i].dx = (vertex[i].x3*viewport)/(vertex[i].z3+600)+350; vertex[i].dy = (vertex[i].y3*viewport)/(vertex[i].z3+600)+262.5; } }
Not much to explain here: A for loop similar to the previous one. Two formulae are applied to the vertices and then stored in two new variables.
One thing to be noted, however, is that the constants at the end of the two formulae- 350 and 262.5 are actually half the values of the height and width values of the movieclip. If you are changing the size of the movieclip, you will have to change this values accordingly.
Rendering it
The last thing left to do is render the object. This will get a little complex, though. But just one function will do.
Copy and paste the following code into the actionscript window:
function render () { for (i=0; i != lines; i++) { with (line[i]) { _visible = true; _x = vertex[line[i].a].dx; _y = vertex[line[i].a].dy; _xscale = vertex[line[i].b].dx-vertex[line[i].a].dx; _yscale = vertex[line[i].b].dy-vertex[line[i].a].dy; } } for (i=0; i != points; i++) { with (vertex[i]) { _x = dx; _y = dy; _xscale = 75+(((((500-z3[i])/10)*30)/100)*(-1)); _yscale = 75+(((((500-z3[i])/10)*30)/100)*(-1)); _alpha = ((((z3[i]*(-1))+500)/10)); } }
Explanation:
Two For loops, one for drawing the lines and other for drawing the vertices are given. In the first loop, we change the x, y, xscale and yscale values of each line movieclip. Next, in the second loop, we change the x and y co-ordinates of the vertex movieclips. The xscale, yscale and alpha properties are adjusted so that they add more 'depth' realism to the scene. They are just some formulae created by me.
The TouchUps
Now that the methods are all done, there is very little coding to be done.
First, we need some variables that will change every time the frame is loaded. You will know what each of them does in the upcoming steps. Copy the following line and add it to the first frame's actionscript:
var ax, ay, az, oldx, oldy, bx, by, bz, nu;
Now, if you can't see the timeline, press the Tab key once to hide all panels.
Select the 2nd frame of the Scripts layer by clicking on it.
Press Tab key again to see the actions panel.
Copy the following code and paste it into the 2nd frame's actionscripts:
rotx = (oldy-_ymouse)/2; roty = (oldx-_xmouse)/2; oldx = _xmouse; oldy = _ymouse; ax += rotx; ay += roty; ay += by; ax += bx; az += bz; bx = 0; by = 0; bz = 0; rotate(ax, ay, az); ax++; ay++; az++; if (ax>360) { ax -= 360; } if (ay>360) { ay -= 360; } if (az>360) { az -= 360; } toScreen(); render();
The first four lines tell that the mouse has moved this much and so, add some values accordingly to the ax and ay variables. The next six lines will be explained later. Next, we call the rotate function to rotate the objects as per the ax, ay and az variables. Next, we increment the three variables by one. This is done to insure that the object keeps rotating even if the mouse is not moving.
Because the mouse moves only in 2 dimensions, we cannot get the z rotation values from the mouse movement itself. So, we just increment the z rotation value automatically.
Now the next 3 if functions make sure that the ax, ay and az variables don't cross 360 degrees.
Then, the toScreen() and render() methods to do the rest.
Then press Tab key to hide the panels. Click on the third frame in the Scripts layer. Press Tab key again to see the panels. Now just add one line of code to the script:
goToAndPlay(2);
This makes sure that the movie loops again and again within the two frames and does not enter the first frame once again.
The majority of the work is done. If you want, press Ctrl+Enter to check if all this has paid off. But wait! There is still some to go!
The Final touch
Now just two more steps to go.
If you cannot see the stage, press Tab key to hide all the panels. Now, select the button you once dragged on to the stage. Scroll through the stage to find it. After it has been selected, press Ctrl+Alt+A to open the ActionScript window. Copy and paste the following code into it:
on (keyPress "") { by = 2; } on (keyPress "") { by = -2; } on (keyPress "") { bx = 2; } on (keyPress "") { bx = -2; } on (keyPress "a") { bz = 2; } on (keyPress "z") { bz = -2; } on (keyPress "'") { Viewport += 5; } on (keyPress "/") { Viewport -= 5; }
These just add more interactivity to the movie. Now, the user can rotate the object in any axis and also zoom in or out of it. By press in up or down keys, the user is giving a positive or negative value to the bx variable. Remember that this variable also affects rotation.
Similarly, pressing the left and right keys rotates the object in y axis.
Since there is no way of controlling the z axis, pressing the a and z keys rotates it on the z axis.
The Next 2 events increment or decrement the Viewport variable. This variable is used to convert the 3d objects to 2d objects. This variable determines how close to the screen the point of origin is. So, by pressing the apostrohe(') and the slash(/) keys, you literally zoom in and out of the object.
There is one more small thing left to do. If you don't see the Library window, press Ctrl+L to invoke it. Now open the Line movieclip and select the "fat-line" like thing. If you don't see the Mixer panel, go to Window - Panels - Mixer to see the mixer panel. Now, change the alpha value of the circle to 83%.
If you want, you can give a color tween to the line movieclip so that it changes color as it moves.
Now that's it. Project Complete. Publish or save the file and view it in the standalone player.