SOME BASIC AS2 TO AS3 CODE


Color
Old version:

First up, the old setRGB method of the legacy Color class.In the old days of ActionScript 1.0 and 2.0, you would create a Color object with a movieclip instance as an argument in the constructor, then apply the setRGB method on this Color instance. It was a bit weird, as you never really directly “talked to” the MovieClip whose colour you wanted to change.

var col:Color = new Color(some_mc);
col.setRGB(0x123456);

New Code

This has changed with AS3. The Color class is something else entirely, and in its place as a colour manipulator, we have this: ColorTransform.

import flash.geom.ColorTransform;
import flash.geom.ColorTransform;// create a new ColorTransform object
var colTrans:ColorTransform = new ColorTransform();
colTrans.color = 0xFF9900;
colTrans.alphaMultiplier = 0;
some_mc.transform.colorTransform = colTrans;

So this would set the colour of the object, but also set its alpha to 0.

Movie Clip Loader

Old Code

this.mcPreview.alpha = 0;
this.mcPreview.mcLoader = new MovieClipLoader();
this.mcPreview.mcLoaderListener = new Object();
this.mcPreview.mcLoaderListener.onLoadInit = Proxy.create(this, previewImageLoaded);
this.mcPreview.mcLoader.addListener(this.mcPreview.mcLoaderListener);
this.mcPreview.mcLoader.loadClip(pPath, this.mcPreview);

public class Proxy
{
public static function create(oTarget : Object, fFunction : Function,... arguments) : Function
{
/* Create an array of the extra parameters passed to the method. Loop
through every element of the arguments array starting with index 2,
and add the element to the aParameters array.*/
var aParameters : Array = new Array();
for(var i : Number = 2;i < arguments.length; i++)
{
aParameters[i - 2] = arguments[i];
}

// Create a new function that will be the proxy function.
var fProxy : Function = function():void
{
/* The actual parameters to pass along to the method called by proxy
should be a concatenation of the arguments array of this function
and the aParameters array.*/
var aActualParameters : Array = arguments.concat(aParameters);

/* When the proxy function is called, use the apply( ) method to call
the method that is supposed to get called by proxy. The apply( )
method allows you to specify a different scope (oTarget) and pass
the parameters as an array.*/

fFunction.apply(oTarget, aActualParameters);
};

// Return the proxy function.
return fProxy;
}
}
}
addChild(loader);

New Code

import flash.events.*;
import flash.display.Loader;
import flash.net.URLRequest;

var url:String = http://www.yourfullyqualidieddomain.com/yourswftoload.swf?cachebusters='+new Date().getTime();
var loader:Loader=new Loader();
loader.contentLoaderInfo.addEventListener(Event.OPEN,loadinit); loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,loading);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,completes);
loader.load(new URLRequest(url));




TWEEN

OLD CODE

the migration of onMotionFinished an event triggered on completion of the old mx.transitions.Tween class. There is a new class:TweenEvent (fl.transitions.TweenEvent) It looked like this in AS2:

import mx.transitions.Tween;
import mx.transitions.easing.Regular;

class SlidingClass extends MovieClip {var xTween:Tween
// class constructor etc. not shown
function slideTo(xTarget:Number, frames:Number, callbackObj:Object, callbackFunc:Function) : Void {
xTween = new Tween (this, "_x", Regular.easeOut, this._x, xTarget, frames, false)
xTween.onMotionFinished = function() {callbackFunc.call(callbackObj);
};};


New Code

no need to pass the target object anymore - that is inherent in the function argument:

import fl.transitions.Tween;
import fl.transitions.TweenEvent;
import fl.transitions.easing.Regular;
var xTween:Tween;

function slideTo(xTarget:Number, frames:Number, func:Function) {
xTween = new Tween(this, "x", Regular.easeOut, this.x, xTarget, frames, false);
xTween.addEventListener(TweenEvent.MOTION_FINISH, func);};


Because of AS3 Event handling, a reference to the Tween is automatically passed to the target function as an Event datatype, via the “target” property.


OnPress

//code in AS 2
cornerplus1.onPress = function () {

startDrag(this);

}


Warning: 1090: Migration issue: The onPress event handler is not triggered automatically by Flash Player at run time in ActionScript 3.0. You must first register this handler for the event using addEventListener ( 'mouseDown', callback_handler).

NEW

// in AS 3 becomes

cornerplus1.addEventListener(MouseEvent.MOUSE_DOWN, dragFn);
function dragFn(event:MouseEvent){
event.target.startDrag();
};


LoadVars


OLD

var msg:LoadVars = new LoadVars();
var msgSent:LoadVars = new LoadVars();
msg.var1 = "one";
msg.var2 = "two";
msgSent.onLoad = function($success:Boolean):Void
{
if ($success)
{
trace("Message sent.");
}
else
{
trace("Message failed.");
}
};
msg.sendAndLoad("http://www.yourfullyqualifieddomain.com/script.php", msgSent);

NEW

var scriptRequest:URLRequest = new URLRequest("http://www.yourfullyqualifieddomain.com/script.php");

var scriptLoader:URLLoader = new URLLoader();
var scriptVars:URLVariables = new URLVariables();
scriptLoader.addEventListener(Event.COMPLETE, handleLoadSuccessful);
scriptLoader.addEventListener(IOErrorEvent.IO_ERROR, handleLoadError);
scriptVars.var1 = "one";
scriptVars.var2 = "two";
scriptRequest.method = URLRequestMethod.POST;
scriptRequest.data = scriptVars;
scriptLoader.load(scriptRequest);
function handleLoadSuccessful($evt:Event):void
{
trace("Message sent.");
}
function handleLoadError($evt:IOErrorEvent):void
{
trace("Message failed.");
}

http://www.yourfullyqualifieddomain.com/script.php?var1=one&var2=two


MovieClip

Creating new instances of a class has been greatly simplified in ActionScript 3.0. In previous versions of ActionScript, you needed to call createEmptyMovieClip() or createTextField() if you wanted to create a new MovieClip or TextField. Now, in ActionScript 3.0, you can simply call new MovieClip() or new TextField() directly, as shown in the following examples:

OLD

// AS2
this.createEmptyMovieClip("mc", this.getNextHighestDepth());
mc.beginFill(0xFF0000);
mc.moveTo(0, 0);
mc.lineTo(100, 0);
mc.lineTo(100, 80);
mc.lineTo(0, 80);
mc.lineTo(0, 0);
mc.endFill();
mc._x = 80;
mc._y = 60;

The previous code creates a new movie clip instance, draws a red rectangle which is 100x80 pixels, and moves the instance to 80,60 on the Stage. Compare that to the following code which does the exact same thing, although using the new drawRect() method instead of having to use the moveTo() and lineTo() methods:

NEW

// AS3
var mc:MovieClip = new MovieClip();
mc.graphics.beginFill(0xFF0000);
mc.graphics.drawRect(0, 0, 100, 80);
mc.graphics.endFill();
mc.x = 80;
mc.y = 60;
addChild(mc);

MovieClip

OLD

ReferenceError: Error #1056: Caused by Declaring Stage Instances Private
If you declare a stage instance private you get the message: "ReferenceError #1056 Cannot create property my_mc on StageIntanceDeclarationsClass"

This error occurs when you uncheck the "Declare Stage Instances Automatically" checkbox in the "ActionScript 3.0 Settings" dialogbox and proceed to declare stage instances as private variables in the class associated with the containing MovieClip.

A Note on Inheritances and Declaring Stage Instances:
You cannot choose to simply always declare stage instances automatically without forcing the use of inheritance in classes linked to MovieClip Symbols. If you have a class APrime which is derived from class A and APrime is linked to a MovieClip Symbol, all stage instances used in the base class A must be manually declared in class A. "Declare Stage Instances Automatically" only declares instances in the class linked to the MovieClip Symbol and does NOT make those references available to any base classes.

Example:
Assume that the class StageIntanceDeclarations is set as the class associated with a MovieClip which c0ntains the MovieClip my_mc. Then the following code will cause ReferenceError #1056 at runtime.



package
{
import flash.display.MovieClip;
public class StageIntanceDeclarations extends MovieClip
{
//Private Causes ReferenceError #1056
private var my_mc:MovieClip;
function StageIntanceDeclarations()
{
}
}
}



The output is as follows:
ReferenceError: Error #1056: Cannot create property my_mc on StageIntanceDeclarations.
at flash.display::Sprite/flash.display:Sprite::constructChildren()
at flash.display::Sprite$iinit()
at flash.display::MovieClip$iinit()
at TestStageIntanceDeclarationsBase$iinit()
at flash.display::Sprite/flash.display:Sprite::constructChildren()
at flash.display::Sprite$iinit()
at flash.display::MovieClip$iinit()

NEW

To avoid this error simply declare my_mc as public:
public var my_mc:MovieClip;

'My Job > Flash/Flex' 카테고리의 다른 글

SOME BASIC AS2 TO AS3 CODE  (0) 2009/05/25
Actionscript 3.0 으로 넘어가야 하는 이유.  (0) 2009/04/29
[AS] String.prototype.stripTag  (0) 2008/07/22
[AS] MovieClip.prototype.centerClip  (0) 2008/07/22
[AS] MovieClip.prototype.killAll  (0) 2008/07/22
[AS] MovieClip.prototype.shakeIt  (0) 2008/07/22
Posted by 두리미

플래시 게시판, 로그인 모듈등 전혀 플래시로 할 필요가 없는데도 보다 화려한 ui를 위해
플래시로 작업을 요구할때.. "즐~"이라고 외쳐주고 싶지만..
뭐.. 만들어야지. 어쩌겠나;

sendAndLoad 웹상의 페이지를 호출하고, 결과를 받아오는 게 핵심이다.
소스는 무척 심플하다. 난 심플한 소스가 좋다.

Action Script

var sendLoadVar = new LoadVars();
var receiveLoadVar = new LoadVars();
var dataURL = http://즐.컴/두리미.php;
sendLoadVar.sendAndLoad(dataURL, receiveLoadVar, "Get"); // 등록시에는 post
receiveLoadVar.onLoad = function (success) {
 if(success){
 
 }
 else{
  trace("변수가져오기 실패했어요");
 }
  _root.var1 = this.var1;
}
stop();

php나 jsp나 asp나 상관없다.
결과를 저장하고 그 결과를 변수형태로 화면에 출력하자.
여러개를 넘길 수도 있다.

&var=ok&var2=22&var3=Hello!
Posted by 두리미

무비클립을 부모객체 기준 정중앙에 위치시킬때 유용하다.
정의해놓고 mc.centerClip(); 해버리면 끝;


MovieClip.prototype.centerClip = function (){
        this._y = this._parent._height / 2 - (this._height / 2);
        this._x = this._parent._width / 2 - (this._width / 2);
};
// USAGE:
// Center MovieClip
// by: Gustavo Perez
// aka pcMan @ www.mx-motion.com
//-------------------------------
// creates a stage-sized border rectangle
lineStyle(0.25, 0xFF6600, 100);
moveTo(0, 0);
lineTo(Stage.width, 0);
lineTo(Stage.width, Stage.height);
lineTo(0, Stage.height);
lineTo(0, 0);
// creates center crossing lines
moveTo(Stage.width/2-50, Stage.height/2);
lineTo(Stage.width/2+50, Stage.height/2);
moveTo(Stage.width/2, Stage.height/2-50);
lineTo(Stage.width/2, Stage.height/2+50);
// creates a new movieclip
createEmptyMovieClip("_mc", 0);
with (_root._mc) {
        beginFill(0xFF0000, 10);
        lineStyle(.25, 0x000000, 10);
        moveTo(0, 0);
        lineTo(200, 0);
        lineTo(200, 200);
        lineTo(0, 200);
        lineTo(0, 0);
        endFill();
        moveTo(_width/2, 0);
        lineTo(_width/2, _height);
        moveTo(0, _height/2);
        lineTo(_width, _height/2);
}
// This prototype get self and _parent size to center clip
// Use it under your own risk xD
// centering relative to self size and parent =)
_mc.centerClip();
Posted by 두리미

간단한 코드로 txt등에서 변수를 가져온다.
대충 아래의 프로세스로 코딩하면 된다.


Action Script

// 시스템 코드 사용 - euc-kr 이용할려면 꼭 넣어주자.
// 주: (flash는 기본적으로 utf-8 을 사용)
System.useCodepage = true;

// 데이터 로드 클래스 설정
var outData = new LoadVars();

// 로드 콜백 함수
outData.onLoad = function(success){
 if(success){
  trace("load complete");
  initData();
 }
 else{trace("에러프레임으로 보내기");}
};

// 로드 실행
outData.load("mn.txt");

// 데이터 초기화
function initData(){
 for(i=1;i<4;i++){
  trace(outData["mn"+i]);
 }
}

stop();



mn.txt
&mn1=메뉴첫번째
&mn2=메뉴두번째
&mn3=메뉴세번째
Posted by 두리미

플래시를 이용한 시계등 무비클립셋을 만들어놓고..
사용자 요구에 맞춰 동적으로 색상을 변화시킬 때가 있다.
간단하게 속성변경으로 무비클립의 색상을 제어할 수 있도록 addProperty를 통해 추가하자.

MovieClip.prototype.addProperty('_color', function() {
        return new Color(this).getRGB();
}, function(rgb) {
        new Color(this).setRGB(rgb);
});

/////////Usage://///////////////////

mc._color = 0xfdecaf;




 

Posted by 두리미
이전버튼 1 이전버튼