package { import flash.display.Shape; import flash.display.Sprite; import flash.events.KeyboardEvent; import flash.geom.Matrix3D; import flash.geom.Vector3D; import flash.ui.Keyboard; [SWF(width=800, height=600, backgroundColor=0x000000)] /** * Class demonstrates how Matrix3D's pointAt() can be used to orient a sprite * towards another sprite. Here, a ball is added to the stage and its movements on all * three axes are controlled by the user through the keyboard. An arrow is placed in the * center of the stage and is updated to always point at the ball. */ public class graphic_flex_image_effects_06_Flex_PointAtTest extends Sprite { private static const MOVE_RATE:uint = 15; protected var _ball:Shape; protected var _pointer:Shape; /** * Constructor. Creates the necessary sprites and sets up listener for * keyboard activity. */ public function graphic_flex_image_effects_06_Flex_PointAtTest() { createPointer(); createBall(); updatePointer(); stage.addEventListener(KeyboardEvent.KEY_DOWN, onStageKeyDown); } /** * Creates the ball shape that the user will control. */ private function createBall():void { _ball = new Shape(); _ball.graphics.beginFill(0xFFFFFF); _ball.graphics.drawCircle(0, 0, 20); _ball.graphics.endFill(); // places the ball offcenter so pointer can point at it _ball.x = stage.stageWidth/2 + 100; _ball.y = stage.stageHeight/2 - 100; addChild(_ball); } /** * Creates pointer shape. */ private function createPointer():void { _pointer = new Shape(); _pointer.graphics.beginFill(0xFF0000); _pointer.graphics.moveTo(-40, -40); _pointer.graphics.lineTo(40, 0); _pointer.graphics.lineTo(-40, 40); _pointer.graphics.lineTo(0, 0); _pointer.graphics.lineTo(-40, -40); _pointer.graphics.endFill(); // centers pointer _pointer.x = stage.stageWidth/2; _pointer.y = stage.stageHeight/2; // assigning to z creates Matrix3D on transform of _pointer _pointer.z = 0; addChild(_pointer); } /** * Updates the pointer, rotating it to point at the current ball position. */ protected function updatePointer():void { var ballPosition:Vector3D = new Vector3D(_ball.x, _ball.y, _ball.z); _pointer.transform.matrix3D.pointAt( ballPosition, Vector3D.X_AXIS, new Vector3D(0, -1, 0) ); } /** * Handles keyboard events. This updated ball position based on keyboard activity. * * @param event Event dispatched by Stage. */ private function onStageKeyDown(event:KeyboardEvent):void { switch (event.keyCode) { case Keyboard.UP: // if SHIFT is used, alter position on z axis if (event.shiftKey) { _ball.z -= MOVE_RATE; // otherwise alter position on y axis } else { _ball.y -= MOVE_RATE; } break; case Keyboard.DOWN: // if SHIFT is used, alter position on z axis if (event.shiftKey) { _ball.z += MOVE_RATE; // otherwise alter position on y axis } else { _ball.y += MOVE_RATE; } break; case Keyboard.RIGHT: _ball.x += MOVE_RATE; break; case Keyboard.LEFT: _ball.x -= MOVE_RATE; break; } // point pointer at current ball position updatePointer(); event.updateAfterEvent(); } } }