Fumio Nonaka http://www.fumiononaka.com/

Technical Writer/Trainer/ActionScript Developer

Flash Player 11 adds new methods of the Matrix3D class to copy elements

Flash Player 11 and AIR 3.0 adds new methods of the Matrix3D class to copy elements between a Matrix3D object and Matrix3D, Vector3D or Vector objects. A Matrix3D object represents a square matrix of order 4 to transform coordinates in 3D.[*1]

Representation of Matrix3D elements

A Matrix3D object represents a square matrix of order 4.

The four methods in the table below copy elements of a row or column between the referenced Matrix3D ooject and the Vector3D object of its argument.

Target Method of Matrix3D class Direction
Column copyColumnFrom() Vector3D -> Matrix3D
copyColumnTo() Matrix3D -> Vector3D
Row copyRowFrom() Vector3D -> Matrix3D
copyRowTo() Matrix3D -> Vector3D

Matrix3D.rawData property reads or writes 16 elements of a Matrix3D object, which are stored in a Vector object with Number base type. The two methods in the table below can copy all 16 elements between the referenced Matrix3D object and the Vector object of its argument. A Vector object of the Matrix3D.rawData property stores elements of a matrix column-by-column.[*2]

Method of Matrix3D class Direction
copyRawDataFrom() Vector -> Matrix3D
copyRawDataTo() Matrix3D -> Vector

The Matrix3D.copyFrom() method copies elements between the referenced Matrix3D object and the other one of it argument. It does not create new Matrix3D object unlike the Matrix3D.clone() method. As it can use existing Matrix3D object, it consume less memory and can avoid the garbage collection.


[*1] [Matrix3D] of the [Help] shows the figure below with the following description:

The Matrix3D class uses a 4×4 square matrix: a table of four rows and columns of numbers that hold the data for the transformation. The first three rows of the matrix hold data for each 3D axis (x,y,z). The translation information is in the last column. The orientation and scaling data are in the first three columns. The scaling factors are the diagonal numbers in the first three columns. Here is a representation of Matrix3D elements:

Representation of Matrix3D elements in the Help

But the positions of “x-axis”, “y-axis” and “z-axis” are not match to the statement that “The first three rows of the matrix hold data for each 3D axis (x,y,z)”. Therefore, the figure inserted in the body text is modified to place them to the correct positions.

[*2] The [Help] describes a Vector object of the Matrix3D.rawData as follows:

A Vector of 16 Numbers, where every four elements can be a row or a column of a 4×4 matrix.

However every four elements is a COLUMN of a 4×4 matrix as described in the body text.

Calculating coordinates to rotate

There are two formulas to calculate coordinates (x, y) with trigonometric functions by specifying angle ø. The first is “polar coordinates” defined with a radius, distance r from the origin (0, 0), and an angle ø between the x axis.

[1] polar: radius r from the origin (0, 0) and angle ø between the x axis.

x: r cosø
y: r sinø

ActionScript30for3D_M01_006

The following code places a MovieClip instance my_mc at the point of which the radius is radius and the angle is radians.

my_mc.x = radius * Math.cos(radians);
my_mc.y = radius * Math.sin(radians);

The second is the formula of transforming coordinates (x, y), which rotates the point around the origin (0, 0) by angle ø.

[2] transform: rotating point (x, y) around the origin (0, 0) by angle ø.

x: x cosø – y sinø
y: x sinø + y cosø

The following code rotates a MovieClip instance my_mc around the origin of the parent instance by angle theta.

var nSin:Number = Math.sin(theta);
var nCos:Number = Math.cos(theta);
var nX:Number = my_mc.x;
var nY:Number = my_mc.y;
my_mc.x = nCos * nX - nSin * nY;
my_mc.y = nSin * nX + nCos * nY;

Formula [2] is superior to [1] to rotate many instances around the origin by the same angle. The Math.sin() and Math.cos() methods should not be called every time to rotate instances because the angle remains the same.

var nSin:Number = Math.sin(theta);
var nCos:Number = Math.cos(theta);
//
for (var i:uint = 0; i < count; i++) {
	// get reference of my_mc
	var nX:Number = my_mc.x;
	var nY:Number = my_mc.y;
	my_mc.x = nCos * nX - nSin * nY;
	my_mc.y = nSin * nX + nCos * nY;
}

See the wonderfl test code to compare two ways.

Calculating coordinates to rotate - wonderfl build flash online

Comparing Graphics.drawPath() method with traditional Graphics API

According to the explanation of the [Help] Graphics.drawPath() method is faster than the traditional Graphics API.

Generally, drawings render faster with drawPath() than with a series of individual lineTo() and curveTo() methods.

However, as long as I tested and compared these methods, any significant differences were not found.

[Drawing API] of the [Help] shows an example code using the Graphics.drawPath() method, which runs faster than the Graphics.moveTo() and Graphics.lintTo() methods. But the coordinates to be passed to the methods are stored in a Vector object. The Vector object is directly specified to the Graphics.drawPath() method, while Graphics.moveTo() and Graphics.lintTo() methods have to take numbers out of the Vector object.

The best case to use Graphics.drawPath() method might be to draw the same shape to multiple instances. Once two Vector objects for the methods arguments are created they can be passed to the methods multiple times. The test code is uploaded to wonderfl.

Comparing Graphics.drawPath() method with traditional Graphics API – wonderfl build flash online

note: “AS3 graphics.drawPath versus moveTo, lineTo Methods – Preserving Transparency” is introduced to the wonderfl post as a comment.

Mysterious class World in Flash CS5

Create a new FLA file in Flash Professional CS5 and write the following frame action:

var test:World = new World();

[Test Movie] generates the compile error #1136:

Incorrect number of arguments. Expected 2.

I have never defined the class World but tried to solve the errors by adding several functions as follows:

var test:World = new World(this, this);
function createWorld() {}
function getStepSize(temp) {}
function setStepSize(temp, temp2) {}
trace(test);  // Output: [object World]

Both Flash CS4 porfessional and Flash Professional CS5.5 don’t have such class, “World”. I suspect Adobe left the unnecessary class in CS5 by mistake. You have to be careful if you define the class named “World” in CS5.

[postscript: 2011/09/23]
According to the comments below and the blog article “Flash CS5 Built-in Physics Discovered“, the class World is a part of physics engine in the inverse Inverse Kinematics framework. And once the API was planned to release with the “Physics” panel but was abandoned by Adobe.

Based on the blog the following code was written to test the library:

const COUNT:uint = 50;
var instances:Vector.<Shape> = drawShapes(COUNT);
var physics:PhysicsManager = new PhysicsManager(stage);
var myWorld:World = physics.createWorld();
assignPhysics();
myWorld.enableCollisions(true);
myWorld.setGravity(new Point(0, 200));
stage.addEventListener(MouseEvent.CLICK, startPhysics);
function startPhysics(eventObject:MouseEvent):void {
	addEventListener(Event.ENTER_FRAME, animatePhysics);
}
function assignPhysics():void {
	var myPoint:Point = new Point(1, 1);
	for (var i:uint = 0; i < COUNT; i++) {
		var instance:DisplayObject = instances[i];
		var physicsObject:PhysObj = myWorld.addPhysObj(instance, myPoint, 0, false);
		if (i % 2) {
			physicsObject.setNonMoving(true);
		}
	}
}
function animatePhysics(eventObject:Event):void {
	myWorld.updateAllObjects();
	myWorld.step();
}
function drawShapes(count:uint):Vector.<Shape> {
	var nStageWidth:int = stage.stageWidth;
	var nStageHeight:int = stage.stageHeight;
	var nWidth:Number = 25;
	var nHeight:Number = 5;
	var instances:Vector.<Shape> = new Vector.<Shape>(count);
	for (var i:uint = 0; i < count; i++) {
		var myShape:Shape = new Shape();
		var myGraphics:Graphics = myShape.graphics;
		myGraphics.beginFill(uint(0xFFFFFF * Math.random()));
		myGraphics.drawRect(-nWidth / 2, -nHeight / 2, nWidth, nHeight);
		myGraphics.endFill();
		addChild(myShape);
		instances[i] = myShape;
		myShape.x = nStageWidth * Math.random();
		myShape.y = nStageHeight * Math.random();
		myShape.rotation = 360 * Math.random();
	}
	return instances;
}

Just copy the whole code and paste it into the first frame of the main timeline in Flash Professional CS5. Then do [Test Movie] and click on the stage. A half of instances randomly placed will fall down.

Instances are randomly placed on the stage

Instances are randomly placed on the stage

Click on the stage and a half of Instances fall down

Click on the stage and a half of Instances fall down

Flash Professional CS5 includes the PffLib.swc library file in the application folder

Flash Professional CS5 includes the PffLib.swc library file in the application holder

The API of the physics engine is stored in the application folder of Flash CS5, Adobe Flash CS5/Common/Configuration/ActionScript 3.0/libs. You may use the file in CS5.5 as well by adding its folder path to the [Library path] in the [Advanced ActionScript 3.0 Settings].

When to use the ?: conditional operator

The conditional operator ?: is used to select an alternative value to be assigned. It is basically faster than the if statement.

myVariable = (condition) ? valueA : valueB;

if (condition) {
	myVariable = valueA;
} else {
	myVariable = valueB;
}

However if the value selected by the conditional operator is to be added with the addition assignment operator +=, its operation will come to be slow.

myVariable += (condition) ? valueA : valueB;

Using the assignment operator = instead makes it a little faster.

myVariable = (condition) ? myVariable + valueA : myVariable + valueB;

But in this case, the if statement is better to use.

if (condition) {
	myVariable += valueA;
} else {
	myVariable += valueB;
}

Merging two arrays

Grant Skinner (@gskinner) tweeted a handy trick for merging two arrays in JavaScript. This can be utilized in ActionScript 3.0 as well.

arr1.push.apply(arr1, arr2);

@gskinner:
Advantage of previous trick vs concat: doesn’t have the cost of constructing a new array.

I tried to compare speed of this technique with the Array.concat() method’s. The results of the first code posted to wonderfl were varied. In the code the number of elements in both of source and joined arrays are 300.

The second code joins 100 elements arrays to 10000 elements of source. Then the trick with Function.apply() and Array.push() methods is faster than Array.concat(). But the third code’s results are opposite. It merges additional arrays containing 10000 elements with source arrays containing 100 elements.

From these results referencing an Array instance with Function.apply() method seems to be faster but adding elements with Array.push() method might be slower than Array.concat() method.

Correction of a sample code in “Using the Text Layout Framework” of the CS5 help

Using the Text Layout Framework” in “ActionScript 3.0 Developer’s Guide” on the Flash CS5 help includes some example codes to show how to use the Text Layout Framework. However, the second example in the section “The Text Layout Framework View” yields errors. The following two corrections should be made.

First, insert the xmlns attribute into the Flow element of the XML data (markup).

// var markup:XML = <TextFlow><p><span>Hello, World</span></p></TextFlow>;
var markup:XML = <TextFlow xmlns=’http://ns.adobe.com/textLayout/2008′><p><span>Hello, World</span></p></TextFlow>;

Second, the method updateAllContainers() is not implemented in the IFlowComposer interface. Use the updateAllControllers() method instead.

// myFlow.flowComposer.updateAllContainers();
myFlow.flowComposer.updateAllControllers();

The corrected frame action below works and shows the text in the top left corner of the stage.

// import necessary classes
import flashx.textLayout.container.*;
import flashx.textLayout.compose.*;
import flashx.textLayout.elements.TextFlow;
import flashx.textLayout.conversion.TextConverter;

// first, create a TextFlow instance named myFlow
// var markup:XML = <TextFlow><p><span>Hello, World</span></p></TextFlow>;
var markup:XML = <TextFlow xmlns='http://ns.adobe.com/textLayout/2008'><p><span>Hello, World</span></p></TextFlow>;
var myFlow:TextFlow = TextConverter.importToFlow(markup, TextConverter.TEXT_LAYOUT_FORMAT);

// second, create a controller
// the first parameter, this, must point to a DisplayObjectContainer
// the last two parameters set the initial size of the container in pixels
var contr:ContainerController = new ContainerController(this, 600, 600);

// third, associate it with the flowComposer property
myFlow.flowComposer.addController(contr);

// fourth, update the display list ;
// myFlow.flowComposer.updateAllContainers();
myFlow.flowComposer.updateAllControllers();

Using a class in flashx.textLayout package prevents the constructor from accessing Stage

Text Layout Framework example: News layout” in the [Help] yields the run-time error #1009. Because using a class in flashx.textLayout package prevents the constructor from accessing the Stage instance.

Note: The code has already been fixed. But it is good to know how to access the Stage object when classes in flashx.textLayout package are used. (2010/06/20)

As the test script below shows, the Stage object is available after the DisplayObject.addedToStage event, which is dispatched twice.

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flashx.textLayout.elements.TextFlow;
	public class TextLayoutFormatTest extends Sprite {
		public function TextLayoutFormatTest() {
			var my_fmt:TextFlow;
			trace("constructor", stage, parent);
			addEventListener(Event.ADDED_TO_STAGE, onAdded);
		}
		private function onAdded(eventObject:Event):void {
			trace(stage, parent);
		}
	}
}

// [Output]:
constructor null null
[object Stage] [object Loader]
[object Stage] [object Stage]

As for the prior example in the [Help], TLFNewsLayout class, the statements in the constructor should be moved into a listener method of the DisplayObject.addedToStage event as follows:

package {
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.geom.Rectangle;

	import flashx.textLayout.compose.StandardFlowComposer;
	import flashx.textLayout.container.ContainerController;
	import flashx.textLayout.container.ScrollPolicy;
	import flashx.textLayout.conversion.TextConverter;
	import flashx.textLayout.elements.TextFlow;
	import flashx.textLayout.formats.TextLayoutFormat;

	public class TLFNewsLayout extends Sprite {
		private var hTextFlow:TextFlow;
		private var headContainer:Sprite;
		private var headlineController:ContainerController;
		private var hContainerFormat:TextLayoutFormat;

		private var bTextFlow:TextFlow;
		private var bodyTextContainer:Sprite;
		private var bodyController:ContainerController;
		private var bodyTextContainerFormat:TextLayoutFormat;

		private const headlineMarkup:String = "TLF News Layout ExampleThis example formats text like a newspaper page with a headline, a subtitle, and multiple columns";

		private const bodyMarkup:String = "There are many such lime-kilns in that tract of country, for the purpose of burning the white marble which composes a large part of the substance of the hills. Some of them, built years ago, and long deserted, with weeds growing in the vacant round of the interior, which is open to the sky, and grass and wild-flowers rooting themselves into the chinks of the stones, look already like relics of antiquity, and may yet be overspread with the lichens of centuries to come. Others, where the lime-burner still feeds his daily and nightlong fire, afford points of interest to the wanderer among the hills, who seats himself on a log of wood or a fragment of marble, to hold a chat with the solitary man. It is a lonesome, and, when the character is inclined to thought, may be an intensely thoughtful occupation; as it proved in the case of Ethan Brand, who had mused to such strange purpose, in days gone by, while the fire in this very kiln was burning.The man who now watched the fire was of a different order, and troubled himself with no thoughts save the very few that were requisite to his business. At frequent intervals, he flung back the clashing weight of the iron door, and, turning his face from the insufferable glare, thrust in huge logs of oak, or stirred the immense brands with a long pole. Within the furnace were seen the curling and riotous flames, and the burning marble, almost molten with the intensity of heat; while without, the reflection of the fire quivered on the dark intricacy of the surrounding forest, and showed in the foreground a bright and ruddy little picture of the hut, the spring beside its door, the athletic and coal-begrimed figure of the lime-burner, and the half-frightened child, shrinking into the protection of his father's shadow. And when again the iron door was closed, then reappeared the tender light of the half-full moon, which vainly strove to trace out the indistinct shapes of the neighboring mountains; and, in the upper sky, there was a flitting congregation of clouds, still faintly tinged with the rosy sunset, though thus far down into the valley the sunshine had vanished long and long ago.";

		public function TLFNewsLayout() {
			addEventListener(Event.ADDED_TO_STAGE, initialize);
		}
		function initialize(eventObject:Event):void {
			removeEventListener(Event.ADDED_TO_STAGE, initialize);
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;

			// Headline text flow and flow composer
			hTextFlow = TextConverter.importToFlow(headlineMarkup,TextConverter.TEXT_LAYOUT_FORMAT);
			hTextFlow.flowComposer = new StandardFlowComposer();

			// initialize the headline container and controller objects
			headContainer = new Sprite();
			headlineController = new ContainerController(headContainer);
			headlineController.verticalScrollPolicy = ScrollPolicy.OFF;
			hContainerFormat = new TextLayoutFormat();
			hContainerFormat.paddingTop = 4;
			hContainerFormat.paddingRight = 4;
			hContainerFormat.paddingBottom = 4;
			hContainerFormat.paddingLeft = 4;

			headlineController.format = hContainerFormat;
			hTextFlow.flowComposer.addController(headlineController);
			addChild(headContainer);
			stage.addEventListener(flash.events.Event.RESIZE, resizeHandler);

			// Body text TextFlow and flow composer
			bTextFlow = TextConverter.importToFlow(bodyMarkup,TextConverter.TEXT_LAYOUT_FORMAT);
			bTextFlow.flowComposer = new StandardFlowComposer();

			// The body text container is below, and has three columns
			bodyTextContainer = new Sprite();
			bodyController = new ContainerController(bodyTextContainer);
			bodyTextContainerFormat = new TextLayoutFormat();
			bodyTextContainerFormat.columnCount = 3;
			bodyTextContainerFormat.columnGap = 30;

			bodyController.format = bodyTextContainerFormat;
			bTextFlow.flowComposer.addController(bodyController);
			addChild(bodyTextContainer);
			resizeHandler(null);
		}

		private function resizeHandler(event:Event):void {
			const verticalGap:Number = 25;
			const stagePadding:Number = 16;
			var stageWidth:Number = stage.stageWidth - stagePadding;
			var stageHeight:Number = stage.stageHeight - stagePadding;
			var headlineWidth:Number = stageWidth;
			var headlineContainerHeight:Number = stageHeight;

			// Initial compose to get height of headline after resize
			headlineController.setCompositionSize(headlineWidth, headlineContainerHeight);
			hTextFlow.flowComposer.compose();
			var rect:Rectangle = headlineController.getContentBounds();
			headlineContainerHeight = rect.height;

			// Resize and place headline text container
			// Call setCompositionSize() again with updated headline height
			headlineController.setCompositionSize(headlineWidth, headlineContainerHeight );
			headlineController.container.x = stagePadding / 2;
			headlineController.container.y = stagePadding / 2;
			hTextFlow.flowComposer.updateAllControllers();

			// Resize and place body text container ;
			var bodyContainerHeight:Number = (stageHeight - verticalGap - headlineContainerHeight);
			bodyController.format = bodyTextContainerFormat;
			bodyController.setCompositionSize(stageWidth, bodyContainerHeight );
			bodyController.container.x = (stagePadding/2);
			bodyController.container.y = (stagePadding/2) + headlineContainerHeight + verticalGap;
			bTextFlow.flowComposer.updateAllControllers();
		}
	}
}

The result of the TLFNewsLayout class

The result of the TLFNewsLayout class

Decrement versus Increment in Loop 2

Adobe’s “Optimizing Performance for the Flash Platform” recommends that “Use reverse order for while loops” in its “Miscellaneous optimizations” section. And in my last post, decrement was not explicitly faster than increment with the following code to compare them:

while (--i > -1)

while (++i < MAX_NUMBER)  // MAX_NUMBER is a constant

Difference was very little in my Mac OS environment. But in Internet Explorer 7 and Firefox 3/Flash Player 10/Windows Vista, decrement was faster up to twenty percent than increment. After several trials, speed of operation between decrement and increment seems to be almost the same. The condition of loop does not care if expression is decrement or increment.

The difference came from value to be compared with a counter variable. The new sample script for increment below does not use a constant in the condition. Then its speed seems to be almost identical to the decrement's.

while (++i < <the literal number>)

Decrement versus Increment in Loop

Adobe’s “Optimizing Performance for the Flash Platform” recommends that “Use reverse order for while loops” in its “Miscellaneous optimizations” section.

while (--i > -1)

But according to my test significant difference could not be found between decrement and increment. In other language they said that decrement and increment are identical.

The pre-increment/decrement is a little faster than post, which is included in my test, though.

Quaternion notation of Vector3D

The [Help] of the Vecror3D.w property mentions about the quaternion notation as follows:

Quaternion notation employs an angle as the fourth element in its calculation of three-dimensional rotation. The w property can be used to define the angle of rotation about the Vector3D object.

But this sounds like explanation of the axis angle (see Orientation3D .AXIS_ANGLE Constant). The axis angle uses a combination of an axis and an angle to determine the rotation. For an argument of the Matrix3D.decompose() or Matrix3D.recompose() method Orientation3D.AXIS_ANGLE can be specified as the orientation style used for the matrix transformation.

Try to rotate a Matrix3D object 180 degrees (π) around the axis (1/√2, 1/√2, 0).

The axis of rotation

var myMatrix3D:Matrix3D = new Matrix3D();
var axis:Vector3D = new Vector3D(Math.SQRT1_2, Math.SQRT1_2,0);
myMatrix3D.prependRotation(180, axis);
var axisAngle:Vector3D = myMatrix3D.decompose(Orientation3D.AXIS_ANGLE)[1];
trace(axisAngle, axisAngle.w);

The frame action above outputs as follows:

Vector3D(0.7071067094802856, 0.7071068286895752, -2.339619844353034e-24) 3.1415927410125732

[Note]: 0.707… = 1/√2 and 3.14… = π radians = 180 degrees.

The (x, y, z) coordinates represents the axis and Vector3D.w property is an angle of the rotation. This result seems to fit the explanation of the [Help] quoted above.

But the quaternion notation determine the rotation by the four value. The following expression of the quaternion Q represents the rotation of θ around the vector U.

U = (x, y, z) and |U| = 1
Q = (cos(θ/2); sin(θ/2)U)

Then try to rotate a Matrix3D object 60 degrees around the y axis (0, 1, 0).

var myMatrix3D:Matrix3D = new Matrix3D();
myMatrix3D.prependRotation(60, Vector3D.Y_AXIS);
var quaternion:Vector3D = myMatrix3D.decompose(Orientation3D.QUATERNION)[1];
trace(quaternion.w, quaternion);

The frame action above outputs as follows:

0.8660253882408142 Vector3D(0, 0.4999999701976776, 0)

These numbers represent the quaternion of 60 degrees’ rotation.

0.866… = cos(60/2) = cos(30)
(0, 0.5, 0) = sin(60/2) (0, 1, 0)

Return value of Matrix3D.recompose() method

The [Help] of the Matrix3D.recompose() method tells about its return value as follows:

Returns false if any of the scale elements are zero.

But this is not true. Try the code below, in the 7th statement of which the third element, the z coordinate, of the scale Vector3D instance is set to zero.

var myMatrix3D:Matrix3D = new Matrix3D();
trace(myMatrix3D.decompose());
// Output: Vector3D(0, 0, 0),Vector3D(0, 0, 0),Vector3D(1, 1, 1)
var myVector:Vector.<Vector3D> = new Vector.<Vector3D>();
myVector.push(new Vector3D());  // translation
myVector.push(new Vector3D());  // rotation
myVector.push(new Vector3D(1, 1, 0));  // scale
trace(myMatrix3D.recompose(myVector));
// Output: true
trace(myMatrix3D.decompose());
// Output: Vector3D(0, -1.9986319541931152, 0),Vector3D(-1.5707963705062866, NaN, 0),Vector3D(7.667765755019554e-19, -1.998608112335205, 1.9719639421382673e-19)

The method returns true as long as the argument of Vector instance has three Vector3D elements. Therefore, the explanation in the [Help] should be rewritten as follows:

Returns false if any of the Vector3D elements of the Vector instance as the argument don’t exist or are null.

Note: The coordinates of Vector3D elements come to be invalid values if any of the scale elements are zero.

Calculation in the Utils3D.projectVectors() method

The Utils3D.projectVectors() method projects a Vector of three-dimensional space coordinates to a Vector of two-dimensional space coordinates. And the method also sets the t value of the uvt data.

Calculation in the Utils3D.projectVectors() method

Values for the calculation in the Utils3D.projectVectors() method

The Utils3D.projectVectors() method calculates t value of the uvt data by the following formula:

t value = 1 / (Distance to the origin + z coordinate value)

Also, the method calculates projected x and y values by the following formula:

Projected x or y value = Three-dimensional space x or y coordinate * Focal length * t value

The frame action below compares the results of calculation by the formulas above with the methods’. And [Output] is as follows:

0,0,0.0004 // uvt data
0.0004 // Calculated t value
20,20 // Projected x and y coordinates
20 // Calculated two-dimensional space x or y coordinate

var myPerspective:PerspectiveProjection = new PerspectiveProjection();
var myMatrix3D:Matrix3D = new Matrix3D();
var nDistance:Number = 1000;  // Distance to the origin
var nX:Number = 100;  // Three-dimensional space x or y coordinate
var nZ:Number = 1500;  // Three-dimensional z coordinate
var vertices3D:Vector.<Number> = Vector.<Number>([nX, nX, nZ]);
var vertices2D:Vector.<Number> = new Vector.<Number>();
var uvtData:Vector.<Number> = Vector.<Number>([0, 0, 0]);
var nT:Number = 1/(nDistance + nZ);  // t value
myPerspective.focalLength = 500;  // Focal length 
myMatrix3D.appendTranslation(0, 0, nDistance);
myMatrix3D.append(myPerspective.toMatrix3D());
Utils3D.projectVectors(myMatrix3D, vertices3D, vertices2D, uvtData);
trace(uvtData);  // uvt data
trace(nT);  // Calculated t value
trace(vertices2D);  // Projected x and y coordinates
trace(nX * myPerspective.focalLength * nT);  // Calculated two-dimensional space x or y coordinate

Rotating an instance with the y axis

Try to rotate a MovieClip instance named my_mc 80 degrees with the y axis. The trace() function in the code below displays information in the [Output] panel as follows:

80.00003182368921 1.3962639570236206

var nRotationY:Number = 80;
my_mc.rotationY = 0;
var myMatrix3D:Matrix3D = my_mc.transform.matrix3D;
myMatrix3D.prependRotation(nRotationY, Vector3D.Y_AXIS);
trace(my_mc.rotationY, myMatrix3D.decompose()[1].y);

Rotating an instance 80 degrees

Then change the number of degrees in the variable, nRotationY, to 100. The code seems to rotate an instance 100 degrees. However, the number of degrees shown in the [Output] panel is still 80.

80.00003182368921 1.3962639570236206

var nRotationY:Number = 100;  // 80;
my_mc.rotationY = 0;
var myMatrix3D:Matrix3D = my_mc.transform.matrix3D;
myMatrix3D.prependRotation(nRotationY, Vector3D.Y_AXIS);
trace(my_mc.rotationY, myMatrix3D.decompose()[1].y);

Rotating an instance 100 degrees

The following code reveals the reason.

0 80.00003182368921 0
Vector3D(0, 1.3962639570236206, 0)
180.00000500895632 80.00003182368921 180.00000500895632
Vector3D(3.1415927410125732, 1.3962639570236206, 3.1415927410125732)

var mySprite:Sprite = new Sprite();
var axis:Vector3D = Vector3D.Y_AXIS;  // Vector3D.X_AXIS  // Try to change this
mySprite.rotationY = 0;
var myMatrix3D:Matrix3D = mySprite.transform.matrix3D;
myMatrix3D.prependRotation(80, axis);
xTrace(mySprite);
myMatrix3D.prependRotation(20, axis);
xTrace(mySprite);
function xTrace(targetSprite:Sprite):void {
	trace(targetSprite.rotationX, targetSprite.rotationY, targetSprite.rotationZ);
	trace(targetSprite.transform.matrix3D.decompose()[1]);
}

When the Matrix3D.prependRotation() method rotates an instance 100 degrees with y axis, it is only rotated 80 degrees but is flipped with x and z axes.

The appearance of the instance is all right. But the number of degrees is not good. Besides, 100 degrees can be set with x or z axis. It means that the result of y axis is not consistent. Therefore, I suspect that this is a bug.

Three types of transformation objects in the Transform class

The Transform class has several kinds of transformation objects as its properties.

The Transform class provides access to color adjustment properties and two- or three-dimensional transformation objects that can be applied to a display object.

I noticed three types of properties from the point of view of getting and seting their values.

The first example is the Transform.matrix property. It does not provide its Matrix object reference but its copy. It means that operations to the copy will not affect to the property’s Matrix object. To set a Matrix object to the Transform.matrix property, the object should be assigned to the property.

var mySprite:Sprite = new Sprite();
var myMatrix:Matrix = new Matrix();
mySprite.transform.matrix = myMatrix;
myMatrix.translate(100, 50);
trace(mySprite.transform.matrix);
// Output: (a=1, b=0, c=0, d=1, tx=0, ty=0)
mySprite.transform.matrix = myMatrix;
trace(mySprite.transform.matrix);
// Output: (a=1, b=0, c=0, d=1, tx=100, ty=50)
myMatrix = mySprite.transform.matrix;
myMatrix.scale(2, 1.5);
trace(mySprite.transform.matrix);
// Output: (a=1, b=0, c=0, d=1, tx=100, ty=50)
trace(mySprite.transform.matrix == myMatrix);  // Output: false

The second example is the Transform.matrix3D property. Unlike to the Transform.matrix property, a Matrix3D object’s reference is obtained from the property. Therefore, once its reference is gotten, operations to the reference affects to the Transform.matrix3D property.

var mySprite:Sprite = new Sprite();
var myMatrix3D:Matrix3D = new Matrix3D();
mySprite.transform.matrix3D = myMatrix3D;
myMatrix3D.prependTranslation(100, 50, 0);
trace(mySprite.transform.matrix3D.position);
// Output: Vector3D(100, 50, 0)
trace(mySprite.transform.matrix3D == myMatrix3D);  // Output: true

The third one is the Transform.perspectiveProjection property. When a new PerspectiveProjection instance is assigned to the property, operations to the instance do not affect to the property as well as the Transform.matrix property. Then, try to get the object from the property and set it to a variable again. You can operate the variable as if it was the object reference of the property. However the variable’s object is not evaluated to be equal to the property’s value. It is a mysterious property, isn’t it.

var mySprite:Sprite = new Sprite();
var myPerspective:PerspectiveProjection = new PerspectiveProjection();
mySprite.transform.perspectiveProjection = myPerspective;
myPerspective.fieldOfView = 20;
trace(mySprite.transform.perspectiveProjection.fieldOfView);  // Output: 55
myPerspective = mySprite.transform.perspectiveProjection;
myPerspective.fieldOfView = 100;
trace(mySprite.transform.perspectiveProjection.fieldOfView);  // Output: 100
trace(mySprite.transform.perspectiveProjection == myPerspective);
// Output: false