Actionscript: How do I rotate an external png image using a matrix? - actionscript-3

Okay so I have two import pieces of code involved in this. This first tiny bit is what creates an object called OBJECT_arrow. It is located in the main function of my main class:
new OBJECT_arrow().CREATE(this,200,200);
It isn't really all that important. Now this next bit is the OBJECT_arrow class. What it does is loads an external png image and draws it.
package
{
import flash.net.URLRequest;
import flash.display.*;
import flash.system.*;
import flash.events.*;
import Math;
public class OBJECT_arrow extends Sprite
{
public var X:Number = 0; public var Y:Number = 0;
public var DEPTH:int = 0 ;
public var CONTAINER:Sprite = new Sprite();
public var imageLoader:Loader = new Loader();
public var image:URLRequest = new URLRequest ('ARROW.png');
public function CREATE(CONTAINER:Sprite,X:Number,Y:Number):void
{
this.X = X; imageLoader.x = this.X;
this.Y = Y; imageLoader.y = this.Y;
this.CONTAINER = CONTAINER;
CONTAINER.stage.addEventListener(Event.ENTER_FRAME,STEP);
imageLoader.load(image);
DRAW();
}
public function STEP(event:Event):void
{
DRAW();
}
public function DRAW():void
{
addChild (imageLoader);
(CONTAINER as MAIN).DRAW_LIST[(CONTAINER as MAIN).DRAW_LIST.length] = this;
(CONTAINER as MAIN).DRAW_LIST[(CONTAINER as MAIN).DRAW_LIST.length] = DEPTH;
}
}
}
Now I know the mathematics behind rotation and know to rotate before I translate and everything but I simply don't know how to apply the transformation to an external image in as3.

When you load an image with Loader it is stored as an object of type DisplayObject.
If you want it to be rotated, just set the rotation property.

To apply a matrix, you can use the transform() method of the DisplayObject.
You should also take a look at the BitmapData (raw image data) and Bitmap (DisplayObject to hold the BitmapData) classes. Depending on the complexity of what you're trying to do, they may serve you better. Specifically, BitmapData will allow you to lock() the image while you are fiddling with its bits. Flash won't render the BitmapData until you unlock() it, which can be a great performance improvement if you're doing a lot of fiddling.

Related

How can I use a document class in a single AS3 movie clip?

I have a confetti generator that I am tyring to add to a single movie clip within my flash file. The clip is masked and I want to have some graphics and text appear above the confetti (which will be above a background layer as well).
I purchased a decent script and have modified it to work with some original confetti artwork but I can't figure out how to use this class (or change it for use) in just the one movie clip. Pasting the class below. I've been stressing about this for a couple of hours now, any help would be greatly appreciated.
package com.pixeljunkyard
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import caurina.transitions.*;
import fl.motion.Color;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
public class Main extends Sprite
{
//Create Heart Instance
private var hearts:Heart;
//Amount of hearts
private var totalHearts:Number = 30;
//Falling Speed
private var speed:Number = 1.5;
//Constructor
public function Main()
{
//Align top left for screen aspect ratio
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
//Loop through the amount of heart to be created
for (var i = 0; i < totalHearts; i++)
{
//Create new heart
var heart = new Heart();
//Set Random value
var randScale:Number = randRange(50, 100);
var randRotation:Number = randRange( -180, 180);
var randRotationY:Number = randRange( -360, 360);
//Random position and scale
heart.x = randRange(0, stage.stageWidth);
heart.y = randRange( -stage.stageHeight, stage.stageHeight);
heart.scaleX = randScale/100;
heart.scaleY = randScale/100;
//Name each heart with the number of creation
heart.name = "heart" + i;
var Low : int = 1;
var High : int = 8;
var myRandomNumber:int = Math.floor(Math.random()*(1+High-Low))+Low;
heart.gotoAndStop(myRandomNumber);
//Add eventlisteners for interactions
heart.addEventListener(MouseEvent.ROLL_OVER, hit_heart);
heart.addEventListener(Event.ENTER_FRAME, change_shade);
//Initial Animation
Tweener.addTween(heart, {time:randRange(1,5)/speed, rotation:randRotation,rotationY:randRotationY,y:stage.stageHeight+(heart.height/2)+20, transition:"linear", onComplete:rebirth,onCompleteParams:[heart]} );
//Add to Stage
addChildAt(heart, i);
}
}
//Change shade to give lighting effect
private function change_shade(e:Event):void
{
//New color instance
var c:Color = new Color();
//Set properties
c.brightness = e.target.rotation / 300;
//Apply color to heart
e.target.transform.colorTransform = c;
}
//Random Function
private function randRange(min:Number, max:Number):Number
{
var randomNum:Number = Math.floor(Math.random() * (max - min + 1)) + min;
return randomNum;
}
//Interactive animation
private function hit_heart(e:Event):void
{
Tweener.addTween(e.target, { time:randRange(1,3), rotationY:e.target.rotationY+180 } );
}
//Reset heart to top of the screen once fallen
private function rebirth($heart:Heart):void
{
$heart.x = randRange(0, stage.stageWidth);
$heart.y = -$heart.height;
Tweener.addTween($heart, {time:randRange(1,5)/speed, rotation:randRange(-180,180),y:stage.stageHeight+($heart.height/2)+20, transition:"linear", onComplete:rebirth,onCompleteParams:[$heart]} );
}
}
}
Now I understand your problem.
First of all, I suggest to never write code on the timeline, except simple stuff like stop() or gotoAndPlay("loop").
The easiest way to achieve what you want is to do the following:
Make a blank MovieClip in Flash IDE Ctrl + F8
Give it a linkage like this:
Then click the edit button (marked with a red rectangle)
Open in Flash Professional if asked
Save the file in your .FLA directory and copy the contents of your Main.as file into this file
Remove the package name ("com.pixeljunkyard")
Change the public class Main extends Sprite to public class ConfettiContainer extends MovieClip and import flash.display.MovieClip
Now you have a class ConfettiContainer which does the same stuff that you Main.as file did. Don't forget to copy anything that this Main.as class uses from stage to your ConfettiContainer MovieClip.
You can now create and use it like this:
var confetti:ConfettiContainer = new ConfettiContainer();
addChild(confetti);
P.S. If you can't see Export for Actionscript option when creating a Symbol in Flash, click Advanced.

AS3/AIR Mobile Click and/or touchevents on moving objects

few weeks ago i asked a question about a similair issue, but within the Starling Framework (Starling TouchEvent on Sprite)
Now, i am working on another mobile app/game with Away3d. I seem to have the same problem touching/tapping a moving sphere or box. When the sphere is not moving, i can just tap it exactly at its position, but when it rotates, the click-event doesnt fire very accurate.
this only happens on Mobile (tested on Android 4.2.2: Nexus7/Galaxy S2 and iOS: iPad2/iPad Retina)
package {
import away3d.containers.ObjectContainer3D;
import away3d.containers.View3D;
import away3d.core.pick.PickingColliderType;
import away3d.core.pick.PickingType;
import away3d.debug.AwayStats;
import away3d.entities.Mesh;
import away3d.events.MouseEvent3D;
import away3d.primitives.SphereGeometry;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.geom.Vector3D;
[SWF(frameRate="60")]
public class Main extends Sprite {
private var _container:ObjectContainer3D;
private var _view:View3D;
private var _sphere:Mesh;
public function Main()
{
super();
addEventListener(Event.ADDED_TO_STAGE, onAdded_toStage);
}
private function onAdded_toStage(e:Event):void {
removeEventListener(Event.ADDED_TO_STAGE, onAdded_toStage);
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.addEventListener(Event.RESIZE, onResize_stage);
init3d();
}
private function onResize_stage(e:Event):void {
_view.width = stage.stageWidth;
_view.height = stage.stageHeight;
}
private function onEnter_frame(e:Event):void {
_container.rotationY += 1;
_view.render();
}
private function onClick_sphere(e:MouseEvent3D):void {
//reposition the sphere
var deg:Number = Math.random() * 360;
_sphere.x = 250 * Math.cos(deg);
_sphere.z = 250 * Math.sin(deg);
_sphere.y = 80 + (Math.random() * 40);
}
private function init3d():void {
//create the 3d-view
_view = new View3D();
_view.width = stage.stageWidth;
_view.height = stage.stageWidth;
addChild(_view);
//create a cub
_view.camera.z = -400;
_view.camera.y = 75;
_view.camera.lookAt(new Vector3D(0, 125, 0));
//create container
_container = new ObjectContainer3D();
_view.scene.addChild(_container);
//create sphere to tap
_sphere = new Mesh(new SphereGeometry(10));
_sphere.pickingCollider = PickingColliderType.AS3_FIRST_ENCOUNTERED;
_sphere.y = 100;
_sphere.z = -250;
_sphere.mouseEnabled = true;
_sphere.addEventListener(MouseEvent3D.CLICK , onClick_sphere);
_container.addChild(_sphere);
var stats:AwayStats = new AwayStats(_view);
addChild(stats);
addEventListener(Event.ENTER_FRAME, onEnter_frame);
}
}
NOTE: i also tried different framerates, more events(Mouse_up, down etc), different pickers.
As this problem also happens with 2d moving sprites (in starling) my guess is that is might be Stage3D or AIR related, instead of starling/away3d.
Anyone has some suggestions? Maybe i'm forgetting to set something in the app.xml?
Both framework have to deal with an event less system (Stage3D). Stage3D doesn't catch or receive any events and certianly not touch or mouse event. So both frameworks simulate those events with an internal system that catches events on the stage and try to reproduce an accurate estimation. I personally find those systems too CPU expensive and not accurate enough so my advice is to do like me, create your own system. Simply catch event on the stage and decide which of displayed objects (on Stage3D using their position) has been touched. I personally get a performance boost out of it (especially with starling) and much more accuracy.

Changing class properties in AS3

Okay, so I've recently been trying to get my head properly around OOP in AS3. Right now I have a really simple scenario where I've got a class, Paddle, which draws a rectangle. In my document class I create two instances of the Paddle class, paddle1 and paddle2.
I've also created a property for my Paddle class which I want to change the colour of the rectangle that it draws. I want to be able to adjust this property from the main class. I know I could do this by passing in attributes when instantiating the class but it seems like a property would be a better way, and now I want to know if this is the right way of thinking or not.
main class:
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Engine extends Sprite
{
private var paddle1:Paddle = new Paddle();
private var paddle2:Paddle = new Paddle();
public function Engine()
{
paddle1.x = 30;
paddle1.color = 0xFF00FF;
stage.addChild(paddle1);
paddle2.x = stage.stageWidth - 45;
paddle2.color = 0xFF0000;
stage.addChild(paddle2);
}
}
}
Paddle class:
package
{
import flash.display.MovieClip;
import flash.display.Shape;
import flash.display.Graphics;
import flash.events.Event;
public class Paddle extends MovieClip
{
public var color:uint = 0xFFFFFF;
public function Paddle()
{
var child:Shape = new Shape();
child.graphics.beginFill(color);
child.graphics.drawRect(0, 260, 15, 80);
child.graphics.endFill();
addChild(child);
}
}
}
If changing the properties in this way is not the best way of doing things then of course say so. Otherwise, what am I doing wrong that it doesn't work? Seems like it's something to do with the order (by the time the main class changes the colour attribute, it's already created the rectangle and it's too late to change it?)
Thanks :D
EDIT: realised it might help to say what happens when I execute this code. Basically changing the color attribute from the Engine class doesn't change the colour of the rectangle and they both just stay white (FFFFFF)
The issue you're having is that when you do:
new Paddle();
Your constructor code is run. What this means is that the Rectangle has already been drawn with the color defined at the top of the class. You're then changing the color property after this, which as you can see has no effect.
I suggest you make a draw() function for your Paddle. It could accept a color and be used to draw the Rectangle. It might look like this:
public class Paddle extends MovieClip
{
private var _child:Shape;
public function Paddle()
{
_child = new Shape();
addChild(_child);
}
public function draw(color:uint):void
{
_child.graphics.clear();
_child.graphics.beginFill(color);
_child.graphics.drawRect(0, 260, 15, 80);
_child.graphics.endFill();
}
}
This way provides an advantage which is that you can modify the arguments of draw() to accept dimensions for your Rectangle or other elements that will affect the visuals. This will be cleaner and faster than having to add more properties to the class itself if you decide you want to do this.
You're then able to do this:
var paddle1:Paddle = new Paddle();
var paddle2:Paddle = new Paddle();
paddle1.draw(0xFF00FF);
paddle2.draw(0xFF0000);
What you might do is to allow the constructor to assign a color in addition to creating a setter for the color, having both calls subsequently drawing the paddle (which, by the way, could also be a simple flash.display.Shape):
Paddle.as:
package
{
//Imports
import flash.display.Sprite;
//Class
public class Paddle extends Sprite
{
//Constants
private static const DEFAULT_COLOR:uint = 0xFF0000;
//Properties
private var mColor:uint;
//Constructor
public function Paddle(color:uint = DEFAULT_COLOR)
{
mColor = color;
draw();
}
//Draw
private function draw():void
{
graphics.clear();
graphics.beginFill(mColor);
graphics.drawRect(0, 0, 15, 80);
graphics.endFill();
}
//Set Color
public function set color(value:uint):void
{
mColor = value;
draw();
}
//Get Color
public function get color():uint
{
return mColor;
}
}
}
so now you can create and position as many Paddle instances as you want, each having their own color setter:
Red Instance:
var paddleRed:Paddle = new Paddle();
paddleRed.y = 10;
addChild(paddleRed);
Green Instance:
var paddleGreen:Paddle = new Paddle(0x00FF00);
paddleGreen.y = 126;
addChild(paddleGreen);
Blue Instance:
var paddleBlue:Paddle = new Paddle();
paddleBlue.color = 0x00FF00;
paddleBlue.y = 260;
addChild(paddleBlue);
Why not do both? :D
public class Paddle extends MovieClip
{
private var color:uint;
private var rec:Shape;
public function Paddle(newColor:uint = 0xFFFFFF) // default color
{
color = newColor;
rec = new Shape();
drawShape();
addChild(rec);
}
public function drawShape()
{
child.graphics.clear();
child.graphics.beginFill(color);
child.graphics.drawRect(0, 260, 15, 80);
child.graphics.endFill();
}
public function setColor(newColor:uint)
{
color = newColor;
drawShape();
}
}

As3 magnify image

I want to create a image magnify application like following:
A masked small window showig big image area corresponding to the mouse X and Y on the small image. There are many magnifying image application exaples online such as:
http://www.flashandmath.com/intermediate/magglass/mag_glass.html
But here the mouse and mask moves with same X and Y. What i want is that masked window display only certain area corresponding to mouse X and Y on Small image.
Any help would be highly appreciated. thanks.
i wrote a recipe last year for exactly what you're looking for. i do not guarantee that's it's as refactored or efficient as it could be, but it works really well. change it up as much as you like. i post the code hear for anyone to freely use.
however, the photograph and loupe asset i do not permit anyone to use without prior request, please.
the class lets you alter your own magnification strength, even at runtime if you want. you can use your own loupe graphic, but one is also included in the source files (please ask me first if you want to use it in your project).
Description:
Magnifier: Creating A Customizable
Magnifier For Image Assets
The following code demonstrates the
solution for creating a customizable
magnifier for image assets using the
Magnifier class.
The Magnifier constructor receives 6
parameters. The first
loupeDisplayObject:DisplayObject
required parameter is a reference to a
display object that is used as the
virtual loupe. In order for the class
to function properly, the
loupeDisplayObject:DisplayObject must
contain a circular or elliptically
shaped void or alpha transparency at
its center.
The second imageURL:String required
parameter supplies the URLLoader’s
load function’s URLRequest with the
URL of the target image asset. The
image provides BitmapData for both
thumbSprite:Sprite and
magnificationSprite:Sprite objects,
which are scaled using the third
thumbScale:Number and fourth
magnificationScale:Number optional
parameters. The scale of the
thumbSprite:Sprite is exhibited on
stage, while the scale of the
magnificationSprite:Sprite is visible
during magnification.
The Magnifier class operates by
employing mouse events to toggle the
visibility of a virtual loupe over an
image asset. A maskSprite:Sprite
ellipse, both indexed below and based
on the size of the
loupeDisplayObject:DisplayObject, is
created to mask the
magnificationSprite:Sprite. However,
the fifth maskWidth:Number and sixth
maskHeight:Number optional parameters
can be set to manually size a
maskSprite:Sprite that is more
suitable for a
loupeDisplayObject:DisplayObject with
a complex shape.
Calling the public deallocate()
function of the Magnifier instance
prior to its nullification will mark
it as being available for garbage
collection.
Class FIle:
package
{
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.geom.Matrix;
import flash.net.URLRequest;
import flash.ui.Mouse;
import fl.transitions.Tween;
import fl.transitions.TweenEvent;
import fl.transitions.easing.Regular;
public class Magnifier extends Sprite
{
//Class Variables
private var loupeDisplayObject:DisplayObject;
private var imageWidth:Number;
private var imageHeight:Number;
private var thumbScale:Number;
private var magnificationScale:Number;
private var maskWidth:Number;
private var maskHeight:Number;
private var imageBitmapData:BitmapData;
private var maskSprite:Sprite;
private var magnificationSprite:Sprite;
private var thumbSprite:Sprite;
private var loupeTween:Tween;
private var magnificationTween:Tween;
//Constructor
public function Magnifier (
loupeDisplayObject:DisplayObject,
imageURL:String,
thumbScale:Number = 0.5,
magnificationScale:Number = 1.0,
maskWidth:Number = NaN,
maskHeight:Number = NaN
)
{
this.loupeDisplayObject = loupeDisplayObject;
this.thumbScale = Math.max(0.1, Math.min(thumbScale, 1.0));
this.magnificationScale = Math.max(0.1, magnificationScale);
this.maskWidth = maskWidth;
this.maskHeight = maskHeight;
init(imageURL);
}
//Load And Handle Image
private function init(imageURL:String):void
{
var imageLoader:Loader = new Loader();
imageLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageHandler);
imageLoader.load(new URLRequest(imageURL));
}
private function errorHandler(evt:IOErrorEvent):void
{
throw(evt.text);
}
private function imageHandler(evt:Event):void
{
evt.target.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);
evt.target.removeEventListener(Event.COMPLETE, imageHandler);
imageWidth = evt.target.content.width;
imageHeight = evt.target.content.height;
imageBitmapData = new BitmapData(imageWidth, imageHeight);
imageBitmapData.draw(evt.target.content);
createComponents();
}
//Create Components
private function createComponents():void
{
//Loupe Visibility
loupeDisplayObject.alpha = 0;
//Mask
if (isNaN(maskWidth)) maskWidth = loupeDisplayObject.width;
if (isNaN(maskHeight)) maskHeight = loupeDisplayObject.height;
maskSprite = new Sprite();
maskSprite.graphics.beginFill(0x00FF00, 0.5);
maskSprite.graphics.drawEllipse(0, 0, maskWidth, maskHeight);
maskSprite.graphics.endFill();
maskSprite.mouseEnabled = false;
//Magnification
magnificationSprite = scaleImage(new Matrix(magnificationScale, 0, 0, magnificationScale));
magnificationSprite.mouseEnabled = false;
magnificationSprite.alpha = 0;
magnificationSprite.mask = maskSprite;
//Thumb
thumbSprite = scaleImage(new Matrix(thumbScale, 0, 0, thumbScale));
thumbSprite.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
//Add Components To The Display List
addChild(thumbSprite);
addChild(magnificationSprite);
addChild(maskSprite);
addChild(loupeDisplayObject);
}
private function scaleImage(matrix:Matrix):Sprite
{
var scaledResult:Sprite = new Sprite();
scaledResult.graphics.beginBitmapFill(imageBitmapData, matrix, false, true);
scaledResult.graphics.drawRect(0, 0, imageWidth * matrix.a, imageHeight * matrix.d);
scaledResult.graphics.endFill();
return scaledResult;
}
//Mouse Event Handlers
private function mouseDownHandler(evt:MouseEvent):void
{
thumbSprite.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
thumbSprite.addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
mouseMoveHandler(evt);
setLoupeAsVisible(true);
}
private function mouseMoveHandler(evt:MouseEvent):void
{
loupeDisplayObject.x = evt.localX - loupeDisplayObject.width / 2;
loupeDisplayObject.y = evt.localY - loupeDisplayObject.height / 2;
maskSprite.x = evt.localX - maskSprite.width / 2;
maskSprite.y = evt.localY - maskSprite.height / 2;
magnificationSprite.x = 0 - evt.localX / thumbSprite.width * (magnificationSprite.width - thumbSprite.width);
magnificationSprite.y = 0 - evt.localY / thumbSprite.height * (magnificationSprite.height - thumbSprite.height);
}
private function mouseOutHandler(evt:MouseEvent):void
{
thumbSprite.addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler);
setLoupeAsVisible(false);
}
private function mouseOverHandler(evt:MouseEvent):void
{
thumbSprite.removeEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler);
setLoupeAsVisible(true);
}
private function mouseUpHandler(evt:MouseEvent):void
{
if (thumbSprite.hasEventListener(MouseEvent.MOUSE_OVER)) thumbSprite.removeEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler);
thumbSprite.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
thumbSprite.removeEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler);
stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
setLoupeAsVisible(false);
}
//Loupe Tween And Visibility
private function setLoupeAsVisible(response:Boolean):void
{
var targetAlpha:Number;
if (response)
{
targetAlpha = 1.0;
Mouse.hide();
}
else
{
targetAlpha = 0.0;
Mouse.show();
}
loupeTween = new Tween(loupeDisplayObject, "alpha", Regular.easeIn, loupeDisplayObject.alpha, targetAlpha, 0.25, true);
magnificationTween = new Tween(magnificationSprite, "alpha", Regular.easeIn, magnificationSprite.alpha, targetAlpha, 0.25, true);
}
//Clean Up
public function deallocate():void
{
thumbSprite.removeEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
}
}
}

Flash CS4 AS3 horizontal movieclip scrolling with mouse move

I'm new to AS3 and have been working on an XML driven navigation system written in AS3.
At present, I've imported the contents of an XML file and plotted it inside a containing MovieClip created at root level dynamically on the stage. This MovieClip is called 'container'.
What I want to accomplish is a smooth, accelerating / decelerating effect which animates the container movieclip along the X axis depending on where the mouse cursor is in relation to the middle of the stage.
My code can be found here: http://pastie.org/521432
Line 87 onwards is the code I'm using right now to make the movieclip scroll left & right.
What I have does work but is clunky but does work - I just want it to be a little more polished and have drawn a blank with Google. Because I want the MovieClip to continue to scroll at the current relative speed even when the mouse stops moving, I used an instance of the Timer class.
Can anyone suggest improvements? Thanks in advance.
You should separate out you calculations and your drawing methods. So have it do all the calculations in an onMouseMove handler, but actually draw the changes in an onEnterFrame handler.
Also I think your algorithm could be much simpler and nobody would notice. I made a quick example of how you might do it. paste this code into an AS3 file called Main.as and make it the document class of a new FLA.
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
public class Main extends Sprite
{
private const boxCount:int = 10;
private const boxWidth:int = 45;
private const boxMargin:int = 5;
private const startPoint:int = 150;
private const boxesWidth:int = boxCount * (boxWidth + boxMargin);
private const endPoint:int = boxesWidth + startPoint;
private const zeroPoint:int = boxesWidth / 2 + startPoint;
private var container:MovieClip;
private var targetX:Number;
private var speed:Number = 0;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
container = new MovieClip();
addChild(container);
container.x = 150;
container.y = 300;
for (var i:int = 0; i < boxCount; i++)
{
container.graphics.beginFill(Math.random() * 0xFFFFFF);
container.graphics.drawRect(i*(boxWidth+boxMargin), 0, boxWidth, boxWidth);
}
addEventListener(Event.ENTER_FRAME, enterFrameHandler);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
}
private function mouseMoveHandler(e:MouseEvent):void
{
var distanceFromCenter:int = stage.mouseX - zeroPoint;
speed = distanceFromCenter * -0.01; // Bring number into a good range, and invert it.
}
private function enterFrameHandler(e:Event):void
{
container.x += speed;
}
}
}