Basic 3D Point Object in Flash 5 (ActionScript 1.0)

A very simple 3D routine written in ActionScript 1.0. If you need to understand transformation and projection of 3D geometry, this script may be a good starting point. It creates a model and a camera. The object responds to the mouse movements. We use a 3D rotation matrix to transform the object points along the x and y axes.

This code block is placed inside the the host clip's onClipEvent (load) event handler. Whenever the mouse moves the onClipEvent (mouseMove) handler calls the objectRotate() function.

Code:

```/* 2 axis rotation matrix
*******************************************************/
function xy_matrix (rx, ry) {
var cosrx = Math.cos(rx);
var sinrx = Math.sin(rx);
var cosry = Math.cos(ry);
var sinry = Math.sin(ry);
var r = {
r11 :  cosry ,
r12 :  0 ,
r13 :  sinry ,
r21 :  sinrx * sinry ,
r22 :  cosrx ,
r23 : -cosry * sinrx ,
r31 : -cosrx * sinry ,
r32 :  sinrx ,
r33 :  cosrx * cosry
}
return r;
}

/* point object constructor
*******************************************************/
function Point(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}

/* point rotation method
*******************************************************/
Point.prototype.rotate = function(R) {
var vector = {
x : R.r11 * this.x + R.r12 * this.y + R.r13 * this.z ,
y : R.r21 * this.x + R.r22 * this.y + R.r23 * this.z ,
z : R.r31 * this.x + R.r32 * this.y + R.r33 * this.z
}
return vector;
}

/* camera object constructor
*******************************************************/
function Camera(focal_length, zoom) {
this.f = focal_length;
this.zoom = zoom;
}

/* camera projection method
*******************************************************/
Camera.prototype.project = function(vector, mc) {
var k = this.zoom * this.f/(vector.z - this.f);
mc._x = k * vector.x;
mc._y = k * vector.y;
}

/* the array of points that make up the model
*******************************************************/
this.model = [
new Point( 1, 1, 1) ,
new Point( 1, 1,-1) ,
new Point( 1,-1, 1) ,
new Point( 1,-1,-1) ,
new Point(-1, 1, 1) ,
new Point(-1, 1,-1) ,
new Point(-1,-1, 1) ,
new Point(-1,-1,-1)
];

/* main program
*******************************************************/
function rotateObject(model) {

/* capture mouse coordinates */
var rx = _ymouse / 100;
var ry = _xmouse / 100;

/* calculate rotation matrix */
var m = xy_matrix(rx, ry);

/* draw object */
for(var i = 0; i < model.length; i++) {

/* calculate transformation */
var vector = model[i].rotate(m);

/* project points to camera plane */
this.cam.project(vector, this[i]);

}

/* update frame */
updateAfterEvent();
}

/* build model
*******************************************************/
for(var i = 0; i < this.model.length; i++) {
this.attachMovie("locator", i, i);
}