Eightlines Creations

Experiments in Physical Computing

Registration Points in AS3

One of the frustrations with the Flash Player 10 3D API has to do with the registration point of a DisplayObject. The crux of the issue is that when you create an object it will be placed at the 0,0,0 point. This makes the anchor point of the object in the top-left, and causes 3D rotation to start from that location. In the Flash IDE you have the option when creating a new DisplayObject to select the registration point, this doesn’t exist when adding the object through code.

There’s several methods for doing this, but I’ve found the simplest way to do this as a one liner is through the Translate method on the DisplayObject’s Transform Matrix. The following code moves the registration point from 0,0,0 to -50,-50,0. Comment out the line bg.transform.matrix to observe the unshifted result.

(Note, I’m using bitshifting operators to determine the halfway point of the sprite. The code bg.width >> 1 equals bg.width / 2. Given that Bitshifting operators are generally regarded as being faster to execute this is the accepted practice in my shop. Feel free to write it how you feel comfortable.)

package {
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Matrix;
 
	public class MatrixTest extends Sprite
	{
		protected var s:Sprite; //Containing Sprite
 
		public function MatrixTest()
		{
			s = new Sprite();
			//Center the container
			s.x = stage.stageWidth >> 1;
			s.y = stage.stageHeight >> 1;
			addChild(s);
 
				var bg:Sprite = new Sprite();
				bg.graphics.beginFill(0xFF0000, .5);
				bg.graphics.drawRect(0,0,100,100);
				bg.graphics.endFill();
				/*
				   Create a new matrix for the object, the first four values are the identity matrix.
				   TX/TY will shift your position according to your calculations.
				   1, 0,
				   0, 1,
				   tx, ty
				*/
				bg.transform.matrix = new Matrix(1, 0, 0, 1, -bg.width >> 1, -bg.height >> 1);
				s.addChild(bg);
 
				//Indicator of registration point.
				var fg:Sprite = new Sprite();
				fg.graphics.lineStyle(1, 0x000000);
				fg.graphics.moveTo(-5, -5);
				fg.graphics.lineTo(5, 5);
				fg.graphics.moveTo(-5, 5);
				fg.graphics.lineTo(5, -5);
				s.addChild(fg);
 
			stage.addEventListener(MouseEvent.MOUSE_MOVE, moveHandler);
		}
 
		protected function moveHandler(e:MouseEvent):void
		{
			//Rotates object based on mouse position.
			//You may wish to restrain these values to 90 or 180 degrees.
			s.rotationX = mouseX;
			s.rotationY = mouseY;
		}
	}
}

Search

The archives run deep. Feel free to search older content using topic keywords.