20 January 2010

Understanding shearing using Matrix object

Any display object in AS3.0 Flash project has transform property and among other things you can use this property to shear (skew) that object. Easy way to do this is to use Matrix object. Now, Matrix object isn't so difficult to understand, although it is scary to some (for unexplainable reasons). All you have to do is understand it's parameters and what they do. Here is simple list.

Matrix(a, b, c, d, tx, ty)

a - x scale of display object
b - y shearing of display object
c - x shearing of display object
d - y scale of display object
tx - x translation
ty - y translation

Let's add some Sprites and see how different parameters values change display object. First create new Flash AS3 project, open actions panel and input these import statements.

import flash.display.Sprite;
import flash.geom.Matrix;
import flash.display.MovieClip;
import flash.events.Event;

We will create few boxes and place them on stage.

var box:Sprite = new Sprite();
box.graphics.lineStyle(1, 0x0000ff); // blue object
box.graphics.drawRect(0, 0, 100, 100);
addChild(box);
box.transform.matrix = new Matrix(1, 0, 0, 1, 50, 100);

var box1:Sprite = new Sprite();
box1.graphics.lineStyle(1, 0x00ff00); // green object
box1.graphics.drawRect(0, 0, 100, 100);
addChild(box1);
box1.transform.matrix = new Matrix(1, .5, 0, 1, 50, 200);

var box2:Sprite = new Sprite();
box2.graphics.lineStyle(1, 0xff0000); // red object
box2.graphics.drawRect(0, 0, 100, 100);
addChild(box2);
box2.transform.matrix = new Matrix(1, 0, .5, 1, 150, 100);

var box3:Sprite = new Sprite();
box3.graphics.lineStyle(1, 0x000000); // black border object
box3.graphics.drawRect(0, 0, 100, 100);
addChild(box3);
box3.transform.matrix = new Matrix(1, .5, .5, 1, 150, 200);

Take a look how different values of b and c parameter shear display object along x and y axis.

This also works for any display object. Feel free to create new MovieClip, give it linkage name gBox. Use next code:

var gBox1:gBox = new gBox();
addChild(gBox1);
gBox1.x = 400;
gBox1.y = 150;

var gBox2:gBox = new gBox();
gBox1.x = 400;
gBox1.y = 150;
addChild(gBox2);
gBox2.transform.matrix = new Matrix(1, .5, .5, 1, 550, 300);

Here is the result.


You can even include shearing effect inside animation. Create another box Sprite and add counter variable. This variable will track amount of shearing. For testing purposes use simple onFrame function.



var box4:Sprite = new Sprite( );
box4.graphics.lineStyle(1, 0x000000);
box4.graphics.drawRect(0, 0, 100, 100);
addChild(box4);
box4.x = 500;
box4.y = 50;
var counter:Number = 0;

stage.addEventListener(Event.ENTER_FRAME, onFrame, false, 0, true);

function onFrame(evt:Event):void
{
if (counter > .98) {
counter = 0;
}else{
counter += 0.01;
box4.transform.matrix = new Matrix(1, 0, counter, 1, 0, 0);
}
}


That's all. Now you understand shearing using Matrix object. So do I.

*_*

0 comments:

 

template by blogger templates