AIR 3 & FP11 - RTMFP + Starling framework

Project/Programming 2012. 1. 17. 11:36
    

설정

트랙백

댓글

Starling 이미지 로드 및 scale & rotation

Programming/Framework 2012. 1. 12. 10:52

package {
	import starling.events.Event;
	import starling.core.Starling;
	import starling.display.Sprite;
	import starling.display.Button;
	import starling.display.Image;
	import starling.textures.Texture;
	import starling.events.Touch;
	import starling.events.TouchEvent;
	import starling.events.TouchPhase;
	import starling.animation.Tween;
	import starling.animation.Transitions;
	import starling.utils.deg2rad;
	import starling.display.DisplayObject;
	import starling.text.TextField;
    import starling.utils.HAlign;
    import starling.utils.VAlign;
    
    import utils.TouchSheet;
	
	import flash.geom.Rectangle;
	import flash.geom.Point;
	import flash.display.Bitmap;
	import flash.net.URLRequest;
	import flash.display.Loader;
	import flash.events.Event;

	public class Demo extends Sprite {

		private var _loader:Loader;
		private var _image:Image;
		private var _posText:TextField;
		private var _sheet:TouchSheet;
		
		public function Demo() {
			_loader = new Loader();
			_loader.load(new URLRequest("https://t1.daumcdn.net/cfile/tistory/11252E424F0ADA1C06"));
			_loader.contentLoaderInfo.addEventListener(flash.events.Event.COMPLETE, onLoadedHandler);
		}

		
		private function onLoadedHandler(e:flash.events.Event):void{
			var bitmap:Bitmap = _loader.content as Bitmap;
			var texture:Texture = Texture.fromBitmap(bitmap);
			_image = new Image(texture);
			
			
			 var description:String = 
                "- touch and drag to move the images \n" +
                "- pinch with 2 fingers to scale and rotate \n" +
                "- double tap brings an image to the front \n" +
                "- use Ctrl/Cmd & Shift to simulate multi-touch";
            
            var infoText:TextField = new TextField(300, 75, description);
            infoText.x = 10;
			infoText.y = 35;
			infoText.fontSize = 12;
			infoText.color = 0x999999;
            infoText.vAlign = VAlign.TOP;
            infoText.hAlign = HAlign.LEFT;
            addChild(infoText);
			
			_sheet = new TouchSheet(_image);
			_sheet.scaleX = 0.2;
			_sheet.scaleY = 0.2;
			setAlignCenter(_sheet);
			_sheet.addEventListener(TouchEvent.TOUCH, onTouchHandler);
			addChild(_sheet);
			
			_posText = new TextField(400, 480, "");
			_posText.x = 10;
			_posText.y = 105;
			_posText.fontSize = 12;
			_posText.color = 0xBBBBBB;
            _posText.vAlign = VAlign.TOP;
            _posText.hAlign = HAlign.LEFT;
			_posText.touchable = false;
            addChild(_posText);
			
			stage.addEventListener(starling.events.Event.RESIZE, onResizeHandler);
			
		}
		
		private function onTouchHandler(e:TouchEvent):void{
			var touches:Vector.<Touch> = e.getTouches(_sheet);
			_posText.text = "_sheet.x : "+_sheet.x+"\n"+
							"_sheet.y : "+_sheet.y+"\n"+
							"_sheet.width  : "+_sheet.width+"\n"+
							"_sheet.height : "+_sheet.height;
			
			var len:int = touches.length;
			for(var i:int=0;i<len;i++){
				var touch:Touch = touches[i];
				var currentPoint:Point = touch.getLocation(_sheet);
				var previousPoint:Point = touch.getPreviousLocation(_sheet);
				_posText.text +="\n\n"+"touches["+i+"]========================\n"+
								"previousGlobalX : "+touch.previousGlobalX+"\n"+
								"previousGlobalY : "+touch.previousGlobalY+"\n"+
								"globalX : "+touch.globalX+"\n"+
								"globalY : "+touch.globalY+"\n"+
								"getLocation().x : "+currentPoint.x+"\n"+
								"getLocation().y : "+currentPoint.y+"\n"+
								"getPreviousLocation().x : "+previousPoint.x+"\n"+
								"getPreviousLocation().y : "+previousPoint.y;
			}
			
		}
		
		private function onResizeHandler(e:starling.events.Event):void{
			
		}

		private function setAlignCenter(inTarget:DisplayObject):void{
			inTarget.x = stage.stageWidth >> 1;
			inTarget.y = stage.stageHeight >> 1;
		}

		public override function dispose():void {
			super.dispose();
		}
	}
}

    

설정

트랙백

댓글

Starling performance test

Project/Programming 2012. 1. 10. 21:58

package {
	import starling.events.Event;
	import starling.core.Starling;
	import starling.display.Sprite;
	import starling.display.Button;
	import starling.textures.Texture;
	import starling.display.DisplayObject;
	import starling.display.Image;
	import starling.utils.deg2rad;
	import flash.display.Bitmap;


	public class Demo extends Sprite {

		[Embed(source = "f60.png")]
		private var MyBitmap:Class;
		
		private var _myTexture:Texture;
		private var _arrButterflys:Vector.<Butterfly>;

		public function Demo() {
			// addedToStage 이벤트에 대한 리스너 추가
			addEventListener( Event.ADDED_TO_STAGE , onAddedToStage);
		}


		private function onAddedToStage(e:Event):void {
			var myBitmap:Bitmap = new MyBitmap() as Bitmap;
			_myTexture = Texture.fromBitmap(myBitmap);

			var len:int = 800;
			
			_arrButterflys = new Vector.<Butterfly>(len, false);
			
			for (var i:int = 0; i<len; i++) {
				var fly:Butterfly = new Butterfly(_myTexture);
				
				fly.alpha = Math.random();
				fly.destX = Math.random()*stage.stageWidth;
				fly.destY = Math.random()*stage.stageHeight;
				
				fly.setVertexColor(0, Math.random()*0xFFFFFF);
				fly.setVertexColor(1, Math.random()*0xFFFFFF);
				fly.setVertexColor(2, Math.random()*0xFFFFFF);
				fly.setVertexColor(3, Math.random()*0xFFFFFF);
				
				fly.x = Math.random()*stage.stageWidth;
				fly.y = Math.random()*stage.stageHeight;
				fly.rotation = deg2rad(Math.random()*360);
				
				fly.pivotX = fly.width >> 1;
				fly.pivotY = fly.height >> 1;
				
				_arrButterflys[i] = fly;
				addChild(fly);
			}

			stage.addEventListener(Event.ENTER_FRAME, onFrame);
		}
		
		private function onFrame(e:Event):void{

			var len:uint = _arrButterflys.length;

			for (var i:int = 0; i < len; i++){

				// move the sausages around
				var fly:Butterfly = _arrButterflys[i];
				
				fly.x -= ( fly.x - fly.destX ) * .1;
				fly.y -= ( fly.y - fly.destY ) * .1;

				if (Math.abs(fly.x - fly.destX)<1 && Math.abs(fly.y-fly.destY) < 1){
					fly.destX = Math.random()*stage.stageWidth;
					fly.destY = Math.random()*stage.stageHeight;
					fly.rotation = deg2rad(Math.random()*360);
				}
			}
		}

		public override function dispose():void {
			removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			_myTexture.dispose();
			super.dispose();
		}
	}
}

import starling.display.Image;
import starling.textures.Texture;

class Butterfly extends Image{
	
	public var destX:Number = 0;
	public var destY:Number = 0;
	
	public function Butterfly(inTexture:Texture):void{
		super(inTexture);
	}
}

    

설정

트랙백

댓글

[Starling-10] 터치 이벤트와 Touch 클래스

Programming/Framework 2012. 1. 10. 14:39
Starling은 손가락의 조작이나 마우스 조작 모두 동일한 이벤트( TouchEvent )로 취급한다. Flash Player의 마우스 이벤트와는 달리 이벤트 종류는 TouchEvent.TOUCH 하나 뿐이다. 따라서 클릭 및 이동 등의 조작 상태는 이벤트에 포함되어 있는 Touch 객체 속성에서 판단하게 되어 있다.

Starling의 모든 표시 객체(Sprite, Stage, Quad, …)는 TouchEvent을 처리할 수 있다. 단, Button 클래스는 내부적으로 터치 이벤트를 triggered 이벤트로 변환하고 있기 때문에 자신의 리스너를 추가하는 것은 주의가 필요하다. 또한 표시 객체 자신이나 부모 개체 touchable 속성이 false의 경우는 TouchEvent를 받을 수 없다.

아무튼 Starling에서 터치 작업을 처리하려면 우선 표시 객체에 TouchEvent.TOUCH 이벤트 리스너를 추가해야 한다. 아래는 샘플이다.

import starling.events.TouchEvent;
myImage.addEventListener(TouchEvent.TOUCH,onTouch);

private function onTouch(e:TouchEvent):void {
trace(e.target);
}

Starling의 이벤트는 표시 목록에 버블링하기 위해 아래의 계층 객체에서 이벤트도 검색할 수 있다. (참고:사양에서는 계층의 위에서 아래로 전파하지만 지금의 구현에서는 Stage에서 이벤트를 받을 수도 있는 것 같다.)

샘플에서 사용하는 target 속​​성과 currentTarget 속​​성 사용법은 Flash Player 표준 이벤트와 동일하다. 기타 TouchEvent에는 다음과 같은 속성도 있다. 모든 읽기 전용이다.

ctrlKey : 이벤트가 발생할 때 Ctrl 키가 눌리고 있었는지 나타내는
shiftKey : 이벤트 발생시 Shift 키가 눌리고 있었는지 나타내는
timestamp : 터치가 시작된 이후의 시간(초)
touches : 사용 가능한 Touch 객체의 벡터

마지막 touches은 이벤트와 관련된 하나 이상의 Touch 객체의 벡터다. Touch 객체는 이벤트 발생시킨 손가락이나 마우스 조작 정보를 보유하고 있다.


Touch 객체 가져오기
TouchEvent에는 Touch 객체를 취득하기 위한 메소드가 포함되어 있다. 멀티 터치를 사용하지 않는 경우 getTouch()메소드에서 Touch 객체를 얻을 수 있다. (멀티 터치의 경우는 후술)

private function onTouch(e:TouchEvent):void {
var touch:Touch = e.getTouch(stage);
if (touch) {
  trace(e.target, touch.target);
}
}

getTouch() 메소드의 첫 번째 인수는 검색할 Touch 객체를 좁히려는 조건이다. 작업의 대상이 된 표시 객체가 인수로 지정된 오브젝트와 일치하는 또는 인수 계층 아래에​​ 포함된 경우, getTouch()는 값을 반환한다. 실제 작업의 대상은 Touch 객체 취득 후에 target 속​​성에서 볼 수 있다. (작업의 대상과 이벤트의 대상은 반드시 일치하지 않는다는 것에 유의)

Touch객체는 target 이외에도 작업을 식별하는 특성이 몇 가지가 더 있다.

target : 터치 조작의 대상이 된 표시 객체
id : 터치를 식별하는 숫자
timestamp : 터치 조작 시간 (터치 시작으로부터 초)


TouchPhase
위에서 이야기한 것처럼, Touch 객체는 작업 상태를 나타내는 속성이 있다. 속성 이름은 phase다.

phase : 현재 터치 상황

phase 속성에 설정 가능한 값은 TouchPhases 클래스에 정의되어 있다. 자주 사용되는 값은 다음 세 가지다.

BEGAN : 손가락이 화면에 접한 또는 마우스 버튼이 눌러진
MOVED : 손가락이 화면을 이동하거나 마우스 버튼이 눌러진 상태 이동
ENDED : 손가락이 화면에서 떨어진 또는 마우스 버튼에서 떨어진

BEGAN이 한 번, MOVED가 0 이상 반복되고, ENDED가 한 번 발생하는 것이 기본적인 흐름이다.다음과 같은 상태도 있다.

STATIONARY : 손가락 또는 마우스가 이전 프레임에서 이동

일반적으로 이 상태에서는 이벤트가 발생되지 않아야하지만, 멀티 터치를 취급하는 경우에는 STATIONARY가 포함될 수 있다.마지막으로 마우스 이용 때만 나타나는 상태다.

HOVER : 마우스 버튼이 눌러지지 않은 상태에서 표시 객체에 포인터가 있을 때

손가락으로 (지금까지) 접하지 않고 포인터를 이동시킬 수 없기 때문에 OVER는 있어도 HOVER는 없다는 것이다.


포인터 위치 가져오기
Touch 객체는 스테이지의 현재 위치와 이전 위치 속성을 가지고 있다. 다음 네 가지다. 형태는 모두 Number.

globalX : 스테이지 좌표를 기준으로 한 현재의 손가락 (포인터)의 x 좌표
globalY : 스테이지 좌표를 기준으로 한 현재의 손가락 (포인터)의 y 좌표
previousGlobalX : 스테이지 좌표를 기준으로 이전의 손가락 (포인터)의 x 좌표
previousGlobalY : 스테이지 좌표를 기준으로 이전의 손가락 (포인터)의 y 좌표

그러나 대부분의 경우 다른 좌표계에서의 위치를​​ 계산하게 될 것이다. 그래서, Touch 클래스에는 위의 속성 값을 특정 객체를 기준으로 한 좌표로 변환하는 메소드를 제공 한다.

public function getLocation(space:DisplayObject):Point
public function getPreviousLocation(space:DisplayObject):Point

이 두 메소드는 인수 객체의 좌표를 기준으로 한 현재의 위치 또는 마지막 위치를 반환한다.아래는 Touch 객체의 위치 정보를 사용하는 샘플이다.

var touch:Touch = event.getTouch(this, TouchPhase.MOVED);
if (touch) {
// 부모 개체를 기준으로 이동 거리를 계산하는
var currentPos:Point = touch.getLocation(parent);
var previousPos:Point = touch.getPreviousLocation(parent);
var delta:Point = currentPos.subtract(previousPos);

// 객체의 위치를​​ 변경
x += delta.x;
y += delta.y;
}

getTouch() 메소드의 두 번째 인수는 원하는 상태를 지정할 수 있다. 위의 예제에서는 손가락 이동 정보를 취급하기 위하여 TouchPhase.MOVED를 지정하고 있다.


더블 클릭의 사용 방법
Touch 객체를 통해 더블 클릭을 감지할 수 있도록 tapCount 속성이 있다. 이 속성을 사용하여 더블 클릭에 해당하는 코드를 작성한 것이 아래의 예제다.

touch = event.getTouch(this, TouchPhase.ENDED);
if (touch & & touch.tapCount == 2) parent.addChild (this);

작동 상태가 ENDED의 Touch 객체가 존재하며 탭 횟수가 2 회인 경우를 검색하고 있다.멀티 터치Starling은 멀티 터치도 지원한다. 멀티 터치를 처리하려면 Starling 객체에 다음과 같이 설정한다.

mStarling.simulateMultitouch = true;

이 상태에서 실제로 멀티 터치를 하면 터치 때마다 Touch 객체가 만들어진다. 그리고 TouchEvent에 전달된다. TouchEvent에서 여러 Touch 개체를 가져오려면 getTouches() 메소드를 사용한다. 아래는 그 예제다.

var touches:Vector.<Touch>=touchEvent.getTouches(this); 


반환 값은 Touch 벡터다. getTouch()뿐만 아니라 두 번째 인수로 원하는 상태를 지정할 수 있다.참고로 Ctrl 키를 사용하여 데스크탑 환경에서도 멀티 터치를 시뮬레이션할 수 있게 되어 있다. 물론 실제 터치 디바이스에서는 손가락으로 조작하면 된다.

원본 : http://cuaoar.jp/2012/01/starling-touch.html



package {
	import starling.events.Event;
	import starling.events.Touch;
	import starling.events.TouchEvent;
	import starling.events.TouchPhase;
	import starling.core.Starling;
	import starling.display.Sprite;
	import starling.display.Image;
	import starling.textures.Texture;
	import starling.display.DisplayObject;
	import starling.animation.Tween;
	import starling.animation.Transitions;
	import starling.utils.deg2rad;
	import flash.display.Bitmap;
	import flash.geom.Point;


	public class Demo extends Sprite {

		[Embed(source="icon128.png")]
		private var MyBitmap:Class;
		
		private var myButton:Image;

		public function Demo() {
			// addedToStage 이벤트에 대한 리스너 추가
			addEventListener( Event.ADDED_TO_STAGE , onAddedToStage);
		}


		private function onAddedToStage(e:Event):void {
			var myBitmap:Bitmap = new MyBitmap() as Bitmap;
			var myTexture:Texture = Texture.fromBitmap(myBitmap);
			
			myButton = new Image(myTexture);
			myButton.addEventListener(TouchEvent.TOUCH, onTouchHandler);
			
			myButton.pivotX = myButton.width >> 1;
			myButton.pivotY = myButton.height >> 1;
			addChild(myButton);
			setAlign(myButton);

		}
		
		private function onTouchHandler(e:TouchEvent):void{
			var touch:Touch = e.getTouch(myButton);
			if(touch){
				switch(touch.phase){
					case TouchPhase.BEGAN : myButton.setVertexColor(0, 0xFF6600);
											myButton.setVertexColor(1, 0xFF6600);
											myButton.setVertexColor(2, 0xFF6600);
											myButton.setVertexColor(3, 0xFF6600);
					break;
					case TouchPhase.MOVED : 
					break;
					case TouchPhase.ENDED : myButton.setVertexColor(0, 0xFFFFFF);
											myButton.setVertexColor(1, 0xFFFFFF);
											myButton.setVertexColor(2, 0xFFFFFF);
											myButton.setVertexColor(3, 0xFFFFFF);
				}
			}
			
			
			/*
			touch = e.getTouch(myButton, TouchPhase.MOVED);   
			if (touch) {        
					// 부모 개체를 기준으로 이동 거리를 계산하는      
					 var currentPos:Point = touch.getLocation(parent);      
					 var previousPos:Point = touch.getPreviousLocation(parent);     
					 var delta:Point = currentPos.subtract(previousPos);        
			 
					// 객체의 위치를​​ 변경     
					 myButton.x +=  delta.x;     
					 myButton.y +=  delta.y; 
			}
			*/
			
			touch = e.getTouch(this, TouchPhase.ENDED); 
			if (touch && touch.tapCount == 2){
				rotationToTween(0.6, 90, Transitions.EASE_OUT_BOUNCE);
			}
			
			var touches:Vector.<Touch> = e.getTouches(stage); 
			if(touches.length == 2){
				var firstPos:Point = touches[0].getLocation(parent);      
				var secondPos:Point = touches[1].getLocation(parent);  
				var distance:Number = Point.distance(firstPos, secondPos);

				scaleToTween(0.2, distance*0.01, Transitions.EASE_OUT);
			}else{
				touch = e.getTouch(this, TouchPhase.MOVED); 
				if (touch){
					moveToTween(0.14, touch.globalX, touch.globalY, Transitions.EASE_OUT);
				}
			}
			
		}
		
		private function rotationToTween(inTime:Number, inRot:int, inEase:String):void{
			var tween:Tween = new Tween(myButton, inTime, inEase);
			tween.animate("rotation", myButton.rotation+deg2rad(inRot));
			Starling.juggler.add(tween);
		}
		
		private function moveToTween(inTime:Number, inX:int, inY:int, inEase:String):void{
			var tween:Tween = new Tween(myButton, inTime, inEase);
			tween.moveTo(inX, inY);
			Starling.juggler.add(tween);
		}
		
		private function scaleToTween(inTime:Number, inScale:Number, inEase:String):void{
			var tween:Tween = new Tween(myButton, inTime, inEase);
			tween.scaleTo(inScale);
			Starling.juggler.add(tween);
		}

		private function setAlign(inTarget:DisplayObject):void {
			inTarget.x = stage.stageWidth >> 1;
			inTarget.y = stage.stageHeight >> 1;
		}

		public override function dispose():void {
			removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			super.dispose();
		}
	}
}

    

설정

트랙백

댓글

[Starling-09] Starling의 Button 클래스 사용

Programming/Framework 2012. 1. 9. 11:22
Starling은 버튼을 쉽게 구현할 수 있도록 Button 클래스가 포함되어 있다. Button 클래스는 DisplayObjectContainer 클래스의 서브 클래스다. 따라서 모든 표시 객체를 자식으로 가질 수 있지만 보통은 스킨 이미지와 제목을 표시한다. 그리고 버튼 클릭을 알리는 기능이 있다.

아래가 Button의 생성자다. 첫 번째 인수는 버튼에 대한 스킨이 되는 텍스처이고 옵션으로, 두 번째 인수에 제목을, 3번 째 인수에는 누를 때 표시할 텍스처를 지정할 수 있다.
Button(upState:Texture, text:String = "", downState:Texture=null)

Flash Professional에서 만든 버튼과 달리, "오버" 스킨은 지정할 수 없다. 아마도 이것은 터치 장치의 이용을 전제로 하고 있기 때문이라고 생각된다.

버튼을 클릭하면 (또는 탭하면) triggered라는 이벤트가 발생한다. 클릭시 실행하고 싶은 처리는 triggered 이벤트 리스너 함수에 작성한다. 아래는 그 예제다. 텍스처 포함 관련 부분은 여러번 나왔기 때문에 생략한다.
import starling.display.Button;
	import starling.events.Event;

	private var myButton:Button;

	private function onAddedToStage(e:Event):void {
		var myBitmap:Bitmap = new MyBitmap  ;
		var myTexture:Texture = Texture.fromBitmap(myBitmap);

		// 텍스처를 지정하여 단추의 객체를 생성
		myButton = new Button(myTexture);

		// triggered 이벤트 수신기를 추가
		myButton.addEventListener(Event.TRIGgered, onTriggered);
	}

	private function onTriggered(e:Event):void {
		// 이벤트를 발생 개체를 가져
		trace(e.target);
	}

Staring 이벤트는 Flash Player의 이벤트처럼 버블링(표시 목록 계층 간에 전파, 자식에서 부모 방향으로만 지원) 하는 여러 버튼을 사용할 때는 triggered 이벤트를 부모 객체에서 처리하는 것도 가능하다.


스킨 지정
Starling 버튼은 터치하면 (또는 버튼에 마우스가 눌러진 상태가 되면), 버튼의 표시 크기가 조금 작아진다. 손가락을 떼면 원래 크기로 돌아간다. 이 것은 버튼에 표준 텍스처 하나만 지정된 경우의 동작이다. 버튼을 눌린 상태에 해당하는 텍스처를 지정하면 텍스처가 작아지는 대신 스킨이 바뀐다.

이 두 텍스처는 생성자에 지정할 수 있지만 나중에 속성에서도 설정할 수 있다. 아래가 속성 목록이다.

upState : 버튼이 터치되지 않은 상태로 표시되는 텍스처
downState : 버튼이 터치되는 상태로 표시되는 텍스처
scaleWhenDown : 터치되어있는 상태 텍스처의 표시 비율

upState과 downState가 각 상태로 표시하는 텍스처를 설정하는 속성이다. (upState는 생성자에서 지정 필수) 성능의 관점에서 어느 텍스처도 같은 텍스처 아틀라스에 있는 것이 바람직할 것이다. 마지막 scaleWhenDown는 0에서 1 사이의 숫자를 지정한다. 이 값은 downState = null의 경우에만 사용할 수 있다.

위에서도 썼지만, 단순한 장식 추가가 필요한 경우, 2 개의 텍스처 이외에도 항시 표시 객체를 추가할 수 있다. 만약 동작을 변경하려면, 커스텀 버튼 클래스를 만드는 편이 빠를지도 모른다.


텍스트 표시
Starling의 버튼은 텍스처로 지정한 이미지에 텍스트를 표시할 수 있다. 텍스트는 생성자에서 지정하거나 인스턴스 생성 후, text 속성에 설정한다. textBounds 속성을 사용하여 텍스트의 위치를​​ 지정할 수도 있다.

text : 버튼에 표시되는 텍스트
textBounds : 텍스트 표시 영역을 Rectangle로 지정

텍스트 표시에 사용할 글꼴의 모양을 설정하는 속성도 있다. 거의 TextField의 경우와 동일하다.

fontName : 텍스트 표시에 사용할 글꼴 이름
fontSize : 텍스트 표시에 사용할 글꼴의 크기
fontColor : 글꼴 색상
fontBold : 글꼴을 굵게 표시 여부를 지정

포함된 글꼴과 비트맵 글꼴을 사용할 수 있다.


버튼 비활성화
버튼을 사용할 수 없는 상태라면 enabled 속성의 값을 false로 적용한다.

enabled : 버튼을 사용할 수 있는지 여부를 지정
alphaWhenDisabled : 버튼이 비활성화 때 알파 값

기본적으로 단추를 비활성화하면 버튼의 표시가 반투명하게 된다. 그 때 사용되는 알파 값은 alphaWhenDisabled에 설정된 값이다.


원본 : http://cuaoar.jp/2012/01/starling-button.html




package {
	import starling.events.Event;
	import starling.core.Starling;
	import starling.display.Sprite;
	import starling.display.Button;
	import starling.textures.Texture;
	import starling.display.DisplayObject;
	import flash.geom.Rectangle;
	import flash.display.Bitmap;

	public class Demo extends Sprite {

		[Embed(source="icon128.png")]
		private var MyBitmap:Class;
		
		private var myButton:Button;

		public function Demo() {
			// addedToStage 이벤트에 대한 리스너 추가
			addEventListener( Event.ADDED_TO_STAGE , onAddedToStage);
		}


		private function onAddedToStage(e:Event):void {
			var myBitmap:Bitmap = new MyBitmap() as Bitmap;
			var myTexture:Texture = Texture.fromBitmap(myBitmap);

			// 텍스처를 지정하여 단추의 객체를 생성
			myButton = new Button(myTexture);
			
			// 터치 상태일 때, 텍스처의 표시 비율
			myButton.scaleWhenDown = 0.95;
			
			myButton.fontColor = 0xFFFFFF;
			myButton.fontBold = true;
			myButton.fontSize = 24;
			myButton.text = "BUTTON";
			myButton.textBounds = new Rectangle(myButton.width-60>>1, 85, 60, 30);
			
			// 
			addChild(myButton);
			setAlign(myButton);
			
			// triggered 이벤트 수신기를 추가
			myButton.addEventListener(Event.TRIGGERED, onTriggered);
		}

		private function onTriggered(e:Event):void {
			// 이벤트를 발생 개체를 가져
			trace(e.target);
			myButton.fontColor = Math.random()*0xFFFFFF;
		}

		private function setAlign(inTarget:DisplayObject):void {
			inTarget.x = stage.stageWidth - inTarget.width >> 1;
			inTarget.y = stage.stageHeight - inTarget.height >> 1;
		}

		public override function dispose():void {
			removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			super.dispose();
		}
	}
}

    

설정

트랙백

댓글

[Starling-08] Starling에서 TextFiled의 사용

Programming/Framework 2012. 1. 9. 10:27
Starling에서는 문자를 표시하기 위해 TextField 라는 클래스가 제공하고 있다. 글꼴 종류, 크기, 색상, 위치 등을 지정하여 텍스트를 화면에 표시할 수 있다.

그렇다고해도, GPU에서 직접 글꼴을 취급할 수는 없다. 사실, 뒤에서 Flash Player의 TextFiled를 사용하여 CPU에서 그린 것을 비트맵화 하여 GPU에 업로드하는 형식으로 사용한다. 즉, Starling의 TextField가 제공하는 것은 주어진 텍스트 및 글꼴에서 동적으로 텍스처를 생성하는 기능인 것이다. 따라서 커서가 표시되는 입력 텍스트와 같이 문자를 선택하는 등의 작업은 할 수 없다.(비트맵이므로)

또한, 동적으로 생성할 이유가 없는 텍스트는 TextField를 사용하는 것보다는 사전에 텍스처로 준비하여 사용하는 것이 효율적이다.


TextField 인스턴스 생성
아래는 TextField의 ​​생성자 정의를 보여준다. 표시 영역의 너비와 높이, 표시할 텍스트의 3개의 인수가 필요하다.
TextField (width:int, height:int, text:String, fontName:String = "Verdana", fontSize:Number=12,
  color:uint=0x0, bold:Boolean=false);
//

어떤 값을 나중에 변경할 수 있지만 효율 측면에서 너비와 높이를 바꾸지 않는 것이 좋다. 아래는 Hello World를 표시하는 예제다. 글꼴 크기와 색상을 인스턴스 생성 후에 지정하고 있다.
import starling.text.TextField;

	private var myTextField:TextField;

	private function onAddedToStage(e:Event):void {
		// TextField 인스턴스를 생성
		myTextField = new TextField(160,80,"Hello World");

		// TextField 인스턴스에 속성을 지정
		myTextField.fontSize = 16;
		myTextField.color = 0x993333;
		myTextField.border = true;

		addChild(myTextField);
	}

border 속성 값을 true로 하면 TextField 영역을 눈으로 확인할 수 있기 때문에 개발시 유용하다. Starling의 TextField에는 지정된 너비와 높이에서 텍스트를 초과하지 않게 글꼴 크기를 자동 조정하는 편리한 기능이 있다.
myTextField.autoScale = true;

TextField 객체의 autoScale 속성을 true로 설정하면 전체 텍스트 표시가 글꼴 크기 지정보다 우선한다. Starling 유용한 클래스 Starling은 색상을 지정하는 Color라는 유용한 클래스가 있다. TextField의 color 속성의 지정에 사용할 수 있다.
import starling.utils.Color;
 
myTextField.color = Color.AQUA;

또한 텍스트 배치 값을 가진 클래스도 있다. 세로 배치는 HAlign, 가로 배치는 VAligin 다.
import starling.utils.HAlign ;
import starling.utils.VAlign ;
 
// TextField의 ​​왼쪽을 기준으로 문자를 배치
myTextField.hAlign = HAlign.LEFT;
myTextField.vAlign = VAlign.TOP;

HAlign에 정의되어 있는 값은 LEFT, CENTER, RIGHT 이렇게 3 종류이고 VAlign에 정의되어 있는 값은, TOP, CENTER, BOTTOM 이렇게 3 종류다. 글꼴 포함 Starling의 TextField에서 포함된 TrueType 글꼴 이용이 가능하다. 글꼴을 포함하면 표시 결과가 실행 환경에 의존하지 않기 때문에 권장한다. 다음은 글꼴 포함된 샘플이다. Ubuntu라는 글꼴을 포함하고 있다.
[Embed(source="Ubuntu-R.ttf",embedAsCFF="false", fontFamily="Ubuntu")]
	private static const UbuntuRegular:Class;

	private function onAddedToStage(e:Event):void {
		myTextField = new TextField(160,80,"Hello World"," Ubuntu ",16);
		myTextField.color = 0x993333;
		addChild(myTextField);
	}

Embed 지정 시에는 embedAsCFF 계정은 필수다. 비트맵 글꼴 사용 Starling의 TextField에서 비트맵 글꼴을 사용할 수 있다. 비트맵 글꼴은 문자를 비트맵으로 내보낸 것이다. 개별 문자 파일의 위치 정보 등은 별도 XML 형식으로 작성한다. XML 파일은 다음과 같은 형식으로되어 있다. 기본 정보, 문자 코드와 텍스처 관련, 그리고 옵션으로 커닝 정보다.

  
  
  
    
  
  
    
    
  
   
    
  


이러한 비트맵 글꼴 정보는 BitmapFont 클래스에 로드한다. 다음은 그 절차다. 먼저 각각의 파일을 포함한다. 여기는 텍스처 아틀라스와 동일한 절차다.
[Embed (source="desyrel.png")]
private static const DesyrelTexture:Class;
 
[Embed (source = "desyrel.fnt"mimeType = "application / octet - stream")]
private static const DesyrelXml:Class;
다음 BitmapFont 객체를 생성한다.
import starling.text.BitmapFont;
	import starling.textures.Texture;

	private function onAddedToStage(e:Event):void {
		
		// 비트맵 글꼴로드
		var texture:Texture = Texture.fromBitmap(new DesyrelTexture);
		
		// 문자 정보 가져오기
		var xml:XML = XML(new DesyrelXml);

		// BitmapFont 인스턴스 생성
		var myBitmapFont:BitmapFont = new BitmapFont(texture,xml);

		//... 앞으로는 아래에 계속
	}

생성한 BitmapFont객체는 사용하기 전에 registerBitmapFont() 메소드를 통해서 TextField 클래스에 등록한다. (registerBitmapFont()는 정적 메서드다) 그 후, TextField의 ​​fontName 속성에 비트맵 글꼴의 이름을 설정하면 표시된다. 글꼴 이름은 BitmapFont 객체의 name 속성에서 가져올 수 있다.
import starling.text.TextField;
	private function onAddedToStage(e:Event):void {
		//... 위에서 계속

		// TextField 클래스 비트맵 글꼴을 등록
		TextField.registerBitmapFont(myBitmapFont);

		// TextField 인스턴스를 생성;
		myTextField = new TextField(300,150,"Hello World");

		// 비트맵 폰트의 폰트 이름을 설정
		myTextField.fontName = myBitmapFont.name;

		addChild(myTextField);
	}

필요하지 않은 비트맵 글꼴은 unregisterBitmapFont() 메소드로 등록을 삭제할 수 있다. 인수에는 삭제할 글꼴 이름을 지정한다. 이 때 삭제된 BitmapFont 대해 dispose()가 실행된다. 이것을 피하고 싶은 경우에는 두 번째 인수에 false를 지정한다.
TextField.unregisterBitmapFont (myBitmapFont.name, false );

비트맵 글꼴 텍스처는 독립적인 파일이 아닌 일반 텍스처 아틀라스와 함께 파일에 추가하는 형태로 사용할 수 있다. 이는 텍스처 전환을 줄일 수 있다. 비트맵 글꼴 표시 설정 비트맵 글꼴을 제작시의 크기로 표시하고 싶을 때는 TextField 객체의 fontSize 속성 BitmapFont.NATIVE_SIZE를 지정한다.
// 비트맵 글꼴의 원래 크기로 보기
myTextField.fontSize = BitmapFont.NATIVE_SIZE ;

또한 비트맵 글꼴을 제작시 모양으로 표시하고 싶을 때는 TextField 객체의 fontSize 속성 Color.WHITE을 지정한다.
// 비트맵 글꼴 텍스처 그대로보기
myTextField.color = Color.WHITE ;

color 속성의 기본 값은 아무 것도 지정하지 않으면 검은색 텍스트가 렌더링된다. 마지막으로 비트맵 글꼴의 제작에는 다음과 같은 것을 권장하고 있다.

Windows : Bitmap Font Generator (Angel Code : 무료)
Mac OS : Glyph Designer (71squared : 유료)


원본 : http://cuaoar.jp/2011/12/starling-textfiled.html




package {
	import starling.events.Event;
	import starling.core.Starling;
	import starling.display.Sprite;
	import starling.text.TextField;

	public class Demo extends Sprite {

		private var _myTextField:TextField;

		public function Demo() {
			// addedToStage 이벤트에 대한 리스너 추가
			addEventListener( Event.ADDED_TO_STAGE , onAddedToStage);
		}
		private function onAddedToStage(e:Event):void {

			// TextField 인스턴스를 생성

			var len:int = 50;
			for (var i:int = 0; i<len; i++) {
				var myTextField = new TextField(160,80,"Hello World 한글" + i);

				// TextField 인스턴스에 속성을 지정
				myTextField.fontSize = 16;
				myTextField.color = Math.random()*0xFF0000+i;
				myTextField.border = true;

				addChild(myTextField);

				myTextField.x = stage.stageWidth >> 1;
				myTextField.y = stage.stageHeight >> 1;

				myTextField.alpha =  0.20;
				myTextField.rotation = i;
			}

			_myTextField = new TextField(160,80,"Hello World");
			_myTextField.fontSize = 24;
			_myTextField.color = 0xFFFFFF;
			//_myTextField.border = true;
			
			addChild(_myTextField);
			setAlign(_myTextField);

		}

		private function setAlign(inTarget:TextField):void {
			inTarget.x = stage.stageWidth - inTarget.width >> 1;
			inTarget.y = stage.stageHeight - inTarget.height >> 1;
		}

		public override function dispose():void {
			removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			super.dispose();
		}
	}
}

 
    

설정

트랙백

댓글

[Starling-07] MovieClip 클래스를 이용한 애니메이션

Project/Programming 2012. 1. 9. 00:49
Flash에서 애니메이션이라고 하면 역시 MovieClip이지만 Starling에도 MovieClip 클래스가 있다. 물론 애니메이션을 위한 클래스지만 Starling의 MovieClip은 화면에 표시할 수 있는 것이 비트맵 이미지 또는 색상을 지정한 사각형 뿐이다. 따라서 MovieClip라는 이름은 같지만 Starling의 MovieClip은 프레임마다 할당된 비트맵을 표시하는 클래스인 것이다.

또한 Starling MovieClip의 자식 객체를 관리하거나 프레임에 스크립트가 들어가는 기능은 없다. 이 점도 Flash Player의 MovieClip과는 크게 다르다. (Starling은 표시 목록의 관리는 Sprite의 책임이다. 한편, MovieClip은 Image 클래스에 타임 라인 기능을 더한 Image의 서브 클래스다. MovieClip이 Sprite의 하위 클래스인 Flash Player와는 달리, 양쪽의 역할은 분리되어 있다.)


스프라이트 시트와 TextureAtlas
MovieClip의 각 프레임을 볼 때 GPU는 표시 프레임에 할당된 텍스처, 셰이더에서 사용할 수 있도록 준비가 이루어진다. 이 때 텍스처가 프레임마다 물리적으로 다른 비트맵 파일이면 프레임을 진행할 때마다 텍스처 전환이 발생한다.

텍스처 전환 처리에는 당연히 시간이 걸린다. 또한 텍스처의 GPU에 업로드가 필요할 때 추가 오버헤드가 증가한다. 일반적으로 이 문제를 해결하기 위해 각 프레임의 텍스처를 하나의 파일에 정의한다. 이 것을 스프 라이트 시트라고  한다.

아래 그림은 Starling 샘플에 포함된 스프라이트 시트의 일부를 자른 것이다.




여러 프레임에 해당하는 텍스처가 1개의 파일로 되어 있으면 GPU를 이용해서 사용 위치를 바꾸는 것만으로 텍스처 자체를 전환하지 않고 렌더링 처리가 가능하다. 따라서 고속 프레임을 업데이트할 수 있다.

또한 Stage3D에서 취급할 수 있는 텍스처의 폭은 2의 계승이라는 규칙 때문에, 그 이외의 너비 텍스처는 Starling 내부에 여분의 사전 처리가 발생한다. 하지만 스프라이트 시트의 경우 표시되는 텍스처가 더 큰 텍스처(스프라이트시트)가 아니기 때문에 개별 텍스처 너비 사이즈를 걱정할 필요가 없다.

이 것을 최적화한 1단계가 TextureAtlas다. TextureAtlas는 여러 스프라이트시트를 하나의 파일에 정리한 것이다. 동시에 여러 애니메이션을 재생하는 경우 특히 유용하다. TextureAtlas를 만들기 위해, 차기 버전의 Flash Professional CS6에서 지원되는 것 같다. 벡터 애니메이션 스프라이트시트로 내보내기 기능을 기다리거나 Texture Packer 등의 도구를 이용하면 된다.


TextureAtlas 로드
TextureAtlas를 사용하여 프레임마다 각각 TextureAtlas의 어떤 영역을 표시할지 정보가 필요하다. 따라서 다음과 같은 형식으로 각 프레임의 텍스처 정보를 지정하게 되어 있다. 도구를 사용하여 TextureAtlas를 생성하는 경우 이러한 XML 파일도 동시에 생성된다.

  
  
  
  


TextureAtlas 태그 imagePath 속성은 TextureAtlas의 파일 이름이다. SubTexutre 태그의 name 속성은 애니메이션의 고유 이름 뒤에 프레임 번호를 추가한 것이다. 나머지 x, y, height, width에서 텍스처로 사용 영역을 지정한다. (실제로 SubTexture는 텍스처의 일부를 처리하는 클래스가 있다) TextureAtlas가 준비되면 다음과 같은 프로그램에 포함한다.
[Embed (source = "atlas.png")]
private static const MyBitmap:Class;
 
[Embed (source = "atlas.xml"mimeType = "application / octet - stream")]
private static const MyXml:Class;

이러한 정보는 TextureAtlas라는 클래스에서 함께 관리한다. TextureAtlas(PNG 파일)은 일단 Texture 클래스 로딩하면서 XML 파일과 함께 TextureAtras 생성자에 전달한다. TextureAtlas 객체에서 고유 이름을 지정하여 Texture(실제로는 SubTexture의) 벡터를 얻을 수 있다. 이 때 사용하는 메소드가 getTextures()다.
import starling.textures.TextureAtlas;

	private function onAddedToStage(e:Event):void {
		// 텍스처 아틀라스로드
		var myTexture:Texture = Texture.fromBitmap(new MyBitmap);
		// 텍스처 아틀라스의 영역 정보 가져오기
		var myXml:XML = XML(new MyXml);

		// TextureAtlas 인스턴스 생성
		var myTextureAtlas:TextureAtlas = new TextureAtlas(myTexture,myXml);
		// "walk_"를 식별 이름으로 가진 Texture 벡터 생성
		var frames:Vector. = myTextureAtlas.getTextures("walk_");

		// ... 앞으로는 아래에 계속
	}

벡터의 첫 번째 텍스처의 크기가 애니메이션의 영역을 결정한다. 애니메이션 여기까지 왔으면 나머지는 MovieClip의 인스턴스를 생성하면 된다. MovieClip 생성자의 인수에서 얻은 텍스처 벡터를 지정한다.
import starling.display.MovieClip;

	private var myMovieClip:MovieClip;

	private function onAddedToStage(e:Event):void {
		//... 위에서 계속

		// MovieClip 객체의 생성
		myMovieClip = new MovieClip(frames);

		// 애니메이션 재생 시작
		Starling.juggler.add(myMovieClip);
		addChild(myMovieClip);
	}

알겠지만, Tween뿐만 아니라 MovieClip의 재생도 Juggler을 사용한다. MovieClip도 IAnimatable의 서브클래스다. Juggler에 MovieClip을 추가하면 재생이 시작된다. 재생을 제어하는​​ 세 가지 메소드가 포함되어 있다.
myMovieClip.play();
myMovieClip.pause();
myMovieClip.stop();

pause()를 실행한 다음에 play()를 실행하면 현재 상태부터 재생되지만 stop()을 실행한 다음에 play()를 호출하면 처음 부터 다시 재생된다. 애니메이션은 default로 반복 재생된다. 이 설정은 loop 속성을 설정하여 바꿀 수 있다. 재생 여부 isPlaying 속성을 확인한다. 애니메이션이 끝까지 재생되면 movieComplete 이벤트가 발생한다. 재생이 완​​료되면 다음 작업으로 이동하고자하는 경우에 사용할 수 있을 것이다.
myMovieClip.addEventListener(Event.MOVIE_COMPLETED, onMovieComplete);

애니메이션이 반복되는 경우에는 재생이 완​​료될 때마다 movieComplete 이벤트가 발생한다. MovieClip의 부모 Sprite가 Stage에서 제거되면 MovieClip 재생을 중지해야한다. 그래서 다음과 같은 코드를 추가한다.
addEventListener(Event.REMOVED_FROM_STAGE,onRemovedFromStage);

	private function onRemovedFromStage(event:Event):void {
		Starling.juggler.remove(myMovieClip);
	}

Juggler의 remove() 메소드는 MovieClip뿐만 아니라 Tween도 삭제할 수 있다. 또 다른 MovieClip 사용 MovieClip의 생성자의 두 번째 파라미터에 임의의 프레임 속도를 지정할 수 있다.
// 40 fps를 지정
myMovieClip = new MovieClip (frames, 40);

MovieClip마다 다른 프레임 속도를 지정할 수 있다. 재생중인 프레임 속도는 fps 속성에서 가져올 수 있다. 또한 fps 속성 값을 설정하여 프레임 속도를 변경할 수도 있다. 그리고 모든 프레임에 대해 별도의 재생 시간을 지정할 수 있다. 아래는 5 번째 프레임을 2 초 동안 재생하도록 설정하는 예다.
myMovieClip.setFrameDuration(5, 2);

나중에 프레임을 추가하거나 삭제할 수도 있다. 이를 위해서 addFrameAt() removeFrameAt() 메서드를 사용한다. 아래는 5 프레임 애니메이션을 10번 째 프레임에 추가하거나 5 프레임을 제거하는 것이다. 
myMovieClip.addFrameAt(5, frames [10]);
myMovieClip.removeFrameAt(5);

프레임의 텍스처를 바꿀 수도 있다. setFrameTexture() 메소드를 사용하면 된다.
myMovieClip.setFrameTexture(5, frames [10]);

프레임에 소리를 연결할 수도 있다. setFrameSound() 메서드를 사용한다.
[Embed (source = "step.mp3")]

private static const StepSound:Class;
 
myMovieClip.setFrameSound (5, new StepSound() as Sound);

이제 5번 째 프레임이 표시되는 타이밍에 지정한 소리가 재생된다. 프레임에 직접 스크립트를 연결할 수는 없다. 그 대신 Juggler.delayCall() 메서드를 사용할 수 있다. 이상에서 Starling 애니메이션의 기본은 끝이다. Starling 표현의 유연성은 CPU 렌더링보다 미약하다. 그러나 빠른 렌더링을 안정적으로 해야할 경우에 선택하면 적당할 것이다.


원본 : http://cuaoar.jp/2011/12/movieclip-starling.html


 


package {
	import starling.events.Event;
	import starling.display.Sprite;
	import starling.display.DisplayObject;
	import starling.display.Image;
	import starling.textures.Texture;
	import starling.textures.RenderTexture;
	import starling.textures.TextureAtlas;
	import starling.display.MovieClip;
	import starling.core.Starling;

	public class Demo extends Sprite {

		[Embed(source = "patch.png")]
		private var MyBitmap:Class;

		[Embed(source = "patch.xml",mimeType = "application/octet-stream")]
		private var MyXml:Class;
		
		private var _arrMovieClips:Array;


		public function Demo() {
			// addedToStage 이벤트에 대한 리스너 추가
			addEventListener(Event.ADDED_TO_STAGE,onAddedToStage);
		}
		private function onAddedToStage(e:Event):void {

			// 텍스처 아틀라스로드
			var myTexture:Texture = Texture.fromBitmap(new MyBitmap());

			// 텍스처 아틀라스의 영역 정보 가져오기
			var myXml:XML = XML(new MyXml());

			// TextureAtlas 인스턴스 생성
			var myTextureAtlas:TextureAtlas = new TextureAtlas(myTexture,myXml);

			// "walk_"를 식별 이름으로 가진 Texture 벡터 생성
			var frames:Vector.<Texture>=myTextureAtlas.getTextures("patch_");

			// MovieClip 객체의 생성
			
			_arrMovieClips = [];
			var count:int = 20;
			for(var i:int=0;i<count;i++){
				var myMovieClip = new MovieClip(frames, 60);
				myMovieClip.x = 20+((stage.stageWidth-90)/count)*i;
				myMovieClip.y = stage.stageHeight - myMovieClip.height >> 1;
				Starling.juggler.add(myMovieClip);
				_arrMovieClips.push(myMovieClip);
				addChild(myMovieClip);
				
			}
			
		//	myMovieClip.setFrameDuration(5, 2);

		//	myMovieClip.addFrameAt(5,frames[10]);
		//	myMovieClip.removeFrameAt(5);
		}

		private function setAlign(inTarget:DisplayObject):void{
			inTarget.x = stage.stageWidth >> 1;
			inTarget.y = stage.stageHeight >> 1;
		}

		public override function dispose():void {
			removeEventListener(Event.ADDED_TO_STAGE,onAddedToStage);
			super.dispose();
		}
	}
}

    

설정

트랙백

댓글

[Starling-06] 비트맵을 표시하는 방법

Project/Programming 2012. 1. 8. 04:49
이번에는 비트맵(텍스처)을 표시하는 방법이다. Starling에서는 비트맵 또는 이전 포스트와 같이 사각형을 사용하여 화면을 구성한다. 기사의 뒷 부분에서 동적으로 텍스처 업데이트하는 방법도 소개한다. (참고 : 앞으로 내용에서 "텍스처 = 비트맵"으로 이해)


Image와 Texture 클래스
Starling 프레임워크는 비트맵을 표시하기 위하여 Image를 사용한다. Image는 Quad의 서브클래스다. 따라서 Quad에서 비트맵 처리 기능을 추가한 것이 Image 클래스가 되는 것이다. Flash Player 표시 객체는 Bitmap에 BitmapData가 있지만 Starling에서는 Image에 Texture가 있다. Texture에 로드할 수 있는 이미지 포멧은 PNG, JPEG, JPEG-XR, ATF 이렇게 4 종류이다. 각 형식마다 전용 읽기 함수가 포함되어 있다. 예를 들어, Bitmap 객체에서 Texture 객체를 만드는 경우 다음과 같다.
var myTexture:Texture = Texture.fromBitmap(myBitmap);

다음은 생성된 Texture에서 Image 객체를 생성하고 표시 목록에 추가하는 것만으로 화면에 비트맵이 표시된다. 아래는 myBitmap.png라는 파일을 표시하는 예제다. 포함된 비트맵 처리 부분을 제외하면 사각형을 표시하는 샘플 코드와 거의 동일하다.

package { import starling.events.Event; import starling.display.Sprite; import starling.display.Image; import starling.textures.Texture; import flash.display.Bitmap; public class Demo extends Sprite { // PNG 파일을 포함 [Embed(source = "icon128.png")] private var MyBitmap:Class; private var myImage:Image; public function Demo() { // addedToStage 이벤트에 대한 리스너 추가 addEventListener( Event.ADDED_TO_STAGE , onAddedToStage); } private function onAddedToStage(e:Event):void { var myBitmap:Bitmap = new MyBitmap() as Bitmap; // Bitmap에서 Texture 오브젝트를 생성 var myTexture:Texture = Texture.fromBitmap(myBitmap); // Image 객체를 생성 myImage = new Image(myTexture); // 표시 목록에 추가 addChild(myImage); } public override function dispose():void { removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage); super.dispose(); } } }

Starling의 Texture는 가로와 세로 픽셀 수가 2층(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048)을 전제로하고 있는 것 같다. 다른 크기의 비트맵에서 Texture를 생성하면 Starling은 자동으로 가장 가까운 크기에 맞게 Texture를 다시 만든다.


벡터 이미지를 텍스처로보기
Flash Player 표시 객체는 벡터 데이터를 비트맵화 하는 기능을 가지고 있다. 이것을 이용하면 AS3 및 Flash Professional 기능을 사용하여 그린 벡터 이미지에서 Image 개체를 생성할 수 있다. 처리 효율을 생각하면 일부러 런타임에 비트맵을 생성하는 것보다는 사전에 비트맵화해 두는 것이 좋을 것이다. 따라서 이 방법은 동적으로 텍스처를 생성해야하는 경우에 필요하다. 구체적인 예를 소개한다. 아래는 Sprite의 graphic 특성에 그린 원을 텍스처로 변환하여 Image 객체로 화면에 표시하는 예제다.

private function onAddedToStage(e:Event):void{ var radius:uint = 100; // Flash Player의 Sprite를 생성 var shape : flash.display.Sprite = new flash.display.Sprite(); // 임의의 색상을 결정 graphics 속성 원을 그린다 var color:uint = Math.random() * 0xFFFFFF; shape.graphics.beginFill(color); shape.graphics.drawCircle(radius, radius, radius); shape.graphics.endFill(); // Sprite를 BitmapData로 변환; var buffer : BitmapData = new BitmapData (radius * 2, radius * 2, true, color); buffer.draw(shape); // BitmapData에서 Texture를 생성 var myTexture:Texture = Texture.fromBitmapData(buffer); // Texture에서 Image를 만듭니다 myImage = new Image(myTexture); // 표시 목록에 추가 addChild(myImage); }

이 경우 코드에서 Flash Player 표시 객체를 사용하게되므로, Starling 표시 객체와 혼동하지 않도록 주의가 필요하다.


동적 텍스처의 업데이트
위의 방법을 사용하면 동적으로 생성한 비트맵을 볼 수 있다. 그러나 표시 비트맵을 업데이트하려면 벡터 이미지 만들기부터 다시 한다. 즉, CPU 그리기 및 GPU 렌더링이 모두 행해지는 것은 그다지 효율적 수단은 아닌 것 같다.(항상 피해야한다는 의미는 아니다.)

이럴 때는 RenderTexture 클래스가 유용하다. RenderTexture은 Texture의 서브 클래스에서, "Starling 표시 객체"를 기존의 Image 객체에 그리는 기능을 제공한다. 이는 GPU만을 사용하기 때문에 효율적이다. RenderTexture은 "Flash Player 표시 객체"를 취급하지 않기 때문에 이미 준비되어 있는 Image 객체를 비트맵으로 합성하는 방법이 기본이다. 특히 미리보기 그래픽을 알고 있는 경우에 유효하다. RenderTexture 생성자는 그리기 영역의 크기만을 지정한다. 이 시점에서 RenderTexture 아직 새하얀(투명)상태다.다음으로 RenderTextire 인스턴스를 사용하여 Image의 인스턴스를 생성하는 단계로 위 코드에서 보았던 방식 그대로다.

import starling.textures.RenderTexture; private var myRenderTexture:RenderTexture; private function onAddedToStage(e : Event):void { // RenderTexture 객체를 생성 myRenderTexture = new RenderTexture(320,480); // RenderTexture에서 Image를 만든다 var canvas:Image = new Image(myRenderTexture); // 표시 목록에 추가 addChild(canvas); }

이제 그리기 영역 지정이 완료되었다.
다음은 RenderTexture를 업데이트하면 화면 표시도 자동으로 업데이트된다. RenderTexuture에 Starling의 표시 객체를 그리려면, draw() 메서드를 사용한다. 그릴 표시 객체는 위치, 비율, 각도, 알파를 지정할 수 있다. 아래 예제에서는 RenderTexture의 x 좌표와 y 좌표를 지정하고 있다.

myImage.x = 10; myImage.y = 20; myRenderTexture.draw(myImage);

많은 표시 객체를 그리고 싶은 경우를 위해, drawBundled() 메소드도 포함되어 있다. 이것은 여러 표시 객체 그리기를 일괄적으로 실행하는 것으로, 처리 효율의 향상을 노린 것이다. GPU를 효율적으로 사용하기 위해서 GPU에 대한 그리기 요청 횟수를 줄이는 것은 중요하다. drawBundled()의 인수는 함수를 지정한다. 함수에서 draw()은 함께 처리된다. 아래는 이미지를 조금씩 회전시키는 예제다.
myRenderTexture.drawBundled(rot);
	private function rot():void {
		var count:int = 30;
		var diff:Number = 2 * Math.PI / count;

		for (var i:int = 0; i < count; ++i) {
			myImage.rotation = diff * i;
			myRenderTexture.draw(myImage);
		}
	}

행하면 아래와 같이된다.



이미지는 Starling 샘플에 포함된 것을 사용했다. RenderTexture에 그려진 내용을 모두 삭제하려면 clear() 메소드를 사용한다.


자원의 해제
불필요하게 된 텍스처가 있는 경우에는 dispose()가 리소스를 해제한다. 특히 RenderTexture은 일시적인 이용이 많다고 생각되므로 잊지 말아야한다.
public override function dispose():void {
		myRenderTexture.dispose();
		super.dispose();
	}

원본 : http://cuaoar.jp/2011/12/starling-flash-1.html


 
package {
	import starling.events.Event;
	import starling.display.Sprite;
	import starling.display.Image;
	import starling.textures.Texture;
	import flash.display.BitmapData;
	import flash.display.Bitmap;
	import starling.textures.RenderTexture;

	public class Demo extends Sprite {

		[Embed(source = "icon128.png")]
		private var MyBitmap:Class;

		private var myRenderTexture:RenderTexture;
		private var myImage:Image;

		public function Demo() {
			// addedToStage 이벤트에 대한 리스너 추가
			addEventListener( Event.ADDED_TO_STAGE , onAddedToStage);
		}
		private function onAddedToStage(e:Event):void {

			// RenderTexture 객체를 생성
			myRenderTexture = new RenderTexture(330,330);

			// RenderTexture에서 Image를 만든다
			var canvas:Image = new Image(myRenderTexture);

			canvas.x = stage.stageWidth- canvas.width >> 1;
			canvas.y = stage.stageHeight- canvas.height >> 1;
			// 표시 목록에 추가
			addChild(canvas);


			var myBitmap:Bitmap = new MyBitmap() as Bitmap;

			// Bitmap에서 Texture 오브젝트를 생성
			var myTexture:Texture = Texture.fromBitmap(myBitmap);

			// Image 객체를 생성
			myImage = new Image(myTexture);
			myImage.x = 165;
			myImage.y = 165;
			
			addEventListener(Event.ENTER_FRAME, run);

		}
		
		private function run(e:Event):void{
			myRenderTexture.drawBundled(rot);
		}

		private function rot():void {
			var count:int = 8;
			var diff:Number = (Math.random()*2) * Math.PI / count;

			for (var i:int = 0; i < count; ++i) {
				myImage.rotation += diff * i;
				myRenderTexture.draw(myImage);
			}
		}

		public override function dispose():void {
			removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			removeEventListener(Event.ENTER_FRAME, run);
			myRenderTexture.dispose();
			myImage.dispose();
			super.dispose();
		}
	}
}
 
    

설정

트랙백

댓글

[Starling-05] Tween 클래스를 이용한 애니메이션

Programming/Framework 2012. 1. 8. 02:57
이전 포스트에서 EnterFrame 이벤트를 사용하여 애니메이션을 구현하는 방법을 소개했다. 이번에는 Tween 클래스를 사용하는 방법이다. Tween을 사용한 경우의 특징 중 하나는 애니메이션의 시간을 초 단위로 지정하는 것이다. Tween은 지정된 시간이 지나는 과정에서 표시 객체의 속성 값, 예를 들어 x좌표를 최종 값에 도달하기까지 순차적으로 변화시킨다.

코드는 다음과 같다. 먼저 Tween 생성자에서 대상 객체와 시간을 지정하여 다음 animate() 메소드를 사용하여 변화하는 속성의 이름과 마지막 값을 설정한다. 여러 특성을 변화시키는 경우 animate()를 계속해서 부르면 된다. 

// myObject을 2 초 걸쳐 가로 50px, 세로 80px 이동하는 애니메이션 지정
var myTween:Tween = New Tween(myObject, 2.0); 
myTween.animate( "x", myObject.x + 50); 
myTween.animate( "y", myObject.y + 80); 


아래 예제는 onAddedToStage() 리스너 함수에 적용한 것이다. 사각형을 4초에 걸쳐 (0,0)에서 (220, 380) 좌표로 이동시키는 것이다.

package {
	import starling.animation.Tween;
	import starling.core.Starling;
	import starling.display.Quad;
	import starling.events.Event;

	private function onAddedToStage(e:Event):void {
		myQuad = new Quad(100,100);
		myQuad.color = 0x00FF00;

		// Tween 객체의 생성
		var myTween:Tween = new Tween(myQuad,4.0);

		// 변화시키는 속성 지정
		myTween.moveTo(220, 380);

		// Juggler에 Tween 객체를 추가하려면
		Starling.juggler.add(myTween);
	}
}


이 샘플에서는 animate() 메소드 대신 moveTo() 메소드를 사용했다. moveTo()는 x좌표와 y좌표를 동시에 이동 시킬 때 유용한 방법이다. 그 외에도 비슷한 방법으로 비율을 바꾸는 scaleTo()와 alpha를 바꾸는 fadeTo() 등이 제공되고 있다. 각도를 바꾸는 방법은 아직 없기 때문에 회전할 때는 animate()를 사용한다.

import starling.utils.deg2rad;
 
var myTween:Tween = new Tween (object, 2.0);
myTween.scaleTo(2);
myTween.fadeTo(0);
myTween.animate( "rotation", deg2rad (45));
Starling.juggler.add(myTween);

위 예제에서 사용한 deg2rad()는 각도를 라디안으로 변환하는 함수다. Starling 프레임워크에서 지원. Juggler 클래스 위 예제에서 살펴보면 Tween 인스턴스에 필요한 설정을 한 후, Tween 인스턴스를 Starling의 juggler이라는 속성에 추가했다. 이는 애니메이션의 시작을 알리는 신호라고 보면 된다. Juggler은 객체의 "시간을 진행하는" 클래스다.
그러나 IAnimatable이라는 인터페이스를 상속하는 객체에만 적용이 된다. Tween은 IAnimatable을 상속하고 있다. Juggler는 객체를 전달하면 해당 객체의 시간을 진행한다. 그리고 객체에 대해 지정된 시간이 지나면 객체에 대한 참조를 자동으로 해제한다. 그런데 Juggler는 delayCall()이라는 메소드가 있다. 이 것은 임의의 함수를 지정한 시간이 지나면 호출하도록 Juggler에게 지시하는 것이다. 호출 함수에 인수를 전달할 수도 있다.
아래는 1초 후에 myFunc()함수를 호출하면서 "Hello"라는 인수를 전달하는 예제다.

Starling.juggler.delayCall (myFunc, 1.0, "Hello");
 
private function myFunc (message:String):void{
  trace (message);
}

애니메이션의 시간과 함수의 실행 시점을 같은 Juggler을 통해서 관리함으로써 양자를 완벽하게 동기화시킬 수 있어 편리하다. Juggler 객체는 Starling 클래스를 제공하기 위해 일반적으로 이 것을 사용하여 애니메이션을 시작하면 충분하다. 단, 애니메이션을 개별적으로 제어하고 싶은 경우에는 Juggler 객체를 생성하는 것이 유용할 수 있겠다.
Juggler 객체를 직접 관리하는 경우 EnterFrame 이벤트에 대한 advanceTime() 메소드를 호출하도록 한다. 또한 dispose()에서 리소스 해제 처리가 필요할지도 모른다. easing 함수 지정 Tween에는 여분의 함수를 지정할 수 있다. easing 함수의 종류는 생성자의 3 번째 인수로 전달한다. 기본 값은 linear다. 생성자에서 설정한 easing 함수는 애니메이션이 시작한 이후에는 변경할 수 없다. Tween 객체의 transition 속성에서 값을 참조만 가능하다.

import starling.animation.Transitions;
var myTween:Tween = new Tween (myQuad, 4, Transitions.EASE_OUT_BOUNCE );
위 예제에서는 easing 함수 easeOutBounce를 지정하고 있다. 여기에 지정 가능한 값은 Transitions 플래스에 정의되어 있다.
아래는 Starling 저자의 사이트에 게재되어 있는 easing 함수의 동작 그래프다. 참고.



섬세한 조정은 허용하지 않는다. 이 점은 Edge 및 Flex와 같다. Tween 진행 상태 알림 Tween은 애니메이션의 시작, 진행, 종료를 알리는 함수를 설정할 수 있다. AS2의 이벤트 핸들러와 비슷하게 사용한다. 구체적인 함수 이름은 각각 onStart(), onUpdate(), onComplete()다. onStart()와 onComplete()는 한 번씩, onUpdate()는 업데이트 프레임 수만큼 실행한다. 아래는 3개의 함수를 설정한 예다.

private function onAddedToStage(e:Event):void {
		myQuad = new Quad(100,100);
		myQuad.color = 0x00FF00;

		var myTween:Tween = new Tween(myQuad,4,Transitions.EASE_OUT_BOUNCE);
		myTween.moveTo(220, 380);
		Starling.juggler.add(myTween);

		myTween.onStart = onStart;
		myTween.onUpdate = onProgress;
		myTween.onComplete = onComplete;

		addChild(myQuad);
	}

	private function onStart():void {
		trace("트윈이 시작되었습니다");
	}
	private function onProgress():void {
		trace("트윈 실행 중");
	}
	private function onComplete():void {
		trace("트윈이 완료되었습니다");
	}

애니메이션의 전처리와 후처리를 실시하고 싶은 경우에는 도움이 될 것이다. 다음에는 Starling의 텍스처의 사용법을 소개한다.

원문 : http://cuaoar.jp/2011/12/tween-starling.html



package {
	import starling.events.Event;
	import starling.core.Starling;
	import starling.display.Quad;
	import starling.utils.deg2rad;
	import starling.display.Sprite;
	import starling.animation.Tween;
	import starling.animation.Transitions;

	public class Demo extends Sprite {
		private var myQuad:Quad;

		public function Demo() {
			// addedToStage 이벤트에 대한 리스너 추가
			addEventListener( Event.ADDED_TO_STAGE , onAddedToStage);
		}
		private function onAddedToStage(e:Event):void {

			myQuad = new Quad(100,100);
			myQuad.setVertexColor(0, 0xFFFF00);
			myQuad.setVertexColor(1, 0xFF0000);
			myQuad.setVertexColor(2, 0x00FF00);
			myQuad.setVertexColor(3, 0x0000FF);
			
			myQuad.pivotX = myQuad.width >> 1;
			myQuad.pivotY = myQuad.height >> 1;

			// Tween 객체의 생성
			var myTween:Tween = new Tween(myQuad, 2.0, Transitions.EASE_IN_OUT);

			// 변화시키는 속성 지정
			myTween.moveTo(stage.stageWidth >> 1, stage.stageHeight >> 1);

			// Juggler에 Tween 객체를 추가하려면
			Starling.juggler.add(myTween);
			Starling.juggler.delayCall(myFunc, 2.0);


			addChild(myQuad);

		}	
		
		private function myFunc():void{
			var myTween:Tween = new Tween(myQuad,4.0, Transitions.EASE_OUT_ELASTIC);
			myTween.animate( "rotation", myQuad.rotation+deg2rad(90));
			myTween.onStart = onStartHandler;
			myTween.onUpdate = onUpdateHandler;
			myTween.onComplete = onCompleteHandler;
			Starling.juggler.add(myTween);
		}

		private function onStartHandler():void{
			var myTween:Tween = new Tween(myQuad,4.0, Transitions.EASE_OUT_ELASTIC);
			if(myQuad.scaleX == 2.0){
				myTween.scaleTo(1);
			}else{
				myTween.scaleTo(2);
			}
			
			Starling.juggler.add(myTween);
		}
		
		private function onUpdateHandler():void{
			trace("트윈 실행 중");
		}
		
		private function onCompleteHandler():void{
			myFunc();
		}

		public override function dispose():void {
			removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			super.dispose();
		}
	}
}

    

설정

트랙백

댓글

[Starling-04] EnterFrame 이벤트를 이용한 애니메이션

Programming/Framework 2012. 1. 8. 00:12
이번에는 이전 포스트에서 소개한 코드를 기반으로 사각형을 이동시켜본다. EnterFrame 이벤트를 사용한다. Starling의 표기 객체는 Flash Player 표시 객체와 같게, EnterFrame 이벤트를 지원한다. 따라서 EnterFrame 이벤트 수신기를 추가하면 새로운 프레임을 볼 때마다 리스너 함수가 실행된다. Starling의 이벤트 방식과 리스너 등록 방법도 FlashPlayer 표시 목록과 거의 동일하다.

이번에 소개하는 방법은 기존의 Flash 컨텐츠를 재사용하기 쉬운 방법이다. 이번 예제에서는 그라데이션으로 사각형에 색을 채우고 회전시켜 본다. Quad 클래스는 정점마다 색을 지정하는 메소드가 있어서 편리하다. 메소드는 setVertexColor() 이다. setVertexColor()의 첫 번째 인자는 정점의 번호다. 번호는 0부터 시작하여 왼쪽, 오른쪽 위 및 왼쪽 아래 오른쪽 아래 정점이다. 두 번째 인수는 색상을 지정한다.

// myQuad.color = 0xABCDEF; 대신 다음을 작성 
myQuad.setVertexColor (0, 0x000000); 
myQuad.setVertexColor (1, 0xFF0000); 
myQuad.setVertexColor (2, 0x00FF00); 
myQuad.setVertexColor (3, 0x0000FF); 


이렇게 지정하면 나머지는 자동으로 각 정점 사이의 픽셀의 색이 보완되기 때문에 사각형에 그라데이션이 입혀진다.


EnterFrame 이벤트 리스너 사용

본론으로 돌아가서 EnterFrame 이벤트 리스너를 추가하는 방법이다. 사용하는 Event 클래스가 Starling 프레이워크에 포함된 클래스라는 점에 주의가 필요하다. 그러나 지금까지 AS3의 이벤트 처리 코드를 구현해 봤다면 별 어려움 없이 사용할 수 있을 것이다. (리스너 함수 삭제 타이밍이 약간 다르다 : 아래)
아래는 EnterFrame 이벤트를 사용하여 프레임마다 사각형을 회전시키는 샘플이다. 이전 예제의 onAddedStage()를 수정한 것이다.
private function onAddedToStage(e:Event):void {
// Quad의 인스턴스를 생성
myQuad = new Quad(200,200);
 
// 각 정점의 색상을 지정 myQuad.setVertexColor(0,0x000000);
myQuad.setVertexColor(1,0xFF0000);
myQuad.setVertexColor(2,0x00FF00);
myQuad.setVertexColor(3,0x0000FF);

// Quad의 인스턴스를 중앙에 표시;
myQuad.x = stage.stageWidth - myQuad.width >> 1;
myQuad.y = stage.stageHeight - myQuad.height >> 1;

// Sprite에 Quad 인스턴스를 추가
addChild(myQuad);

// EnterFrame 이벤트 리스너 추가
myQuad.addEventListener( Event.ENTER_FRAME , onEnterFrame);
}

private function onEnterFrame(e:Event):void {
// Quad의 인스턴스를 회전
if (e.currentTarget as Quad) {
   myQuad.rotation += .01; }
}

프레임마다 rotation 값을 0.01씩 증가시키고 있기 때문에 위 코드를 실행하면 사각형이 시계 방향으로 회전한다. 이 때 회전의 중심점은 사각형의 왼쪽 상단 모서리가 된다. Starling 표시 객체에는 기준점을 지정하기 위한 속성 pivotX과 pivotY가 있다. 이들을 사용하면 사각형 내의 임의의 점을 기준으로 회전시킬 수 있다. pivotX와 pivotY의 초기값은 모두 0이다. 즉, 표시 객체의 기본 등록 포인트는 왼쪽 모서리가 된다. 여기서는 기준점을 사각형의 중심으로 변경해 보자.
// 기준점을 Quad 인스턴스의 중심으로 설정
myQuad.pivotX = myQuad.width >> 1;
myQuad.pivotY = myQuad.height >> 1;

이렇게 기준점을 변경하면 표시 위치의 기준도 다르기 때문에 표시 위치가 어긋난다. 이번 예에서는 사각형의 폭과 높이의 절반인 100 픽셀씩 왼쪽과 위로 이동한다.
// Quad의 인스턴스를 중앙에 표시
myQuad.x = (stage.stageWidth - myQuad.width >> 1) + myQuad.pivotX;
myQuad.y = (stage.stageHeight - myQuad.height >> 1) + myQuad.pivotY;

myQuad.pivotX = myQuad.width >> 1 이므로, 아래와 같이 축약할 수가 있을 것이다.
// Quad의 인스턴스를 중앙에 표시
myQuad.x = stage.stageWidth >> 1;
myQuad.y = stage.stageHeight >> 1;

이상으로 화면의 중앙에 위치하는 사각형을 중심점을 기준으로 회전해봤다.


자원의 개방(메모리 해제)

Starling 표시 객체에는 dispose()라는 메소드가 있다. 이는 표시 객체가 삭제되는 타이밍을 알리는 표시객체에서 사용하는 리소스를 해제하기 위한 메소드이다. Starling에서 표시 객체의 서브 클래스를 정의할 때 dispose() 실행을 잊지 않도록 한다. 그렇지 않으면 메모리 누수의 원인이 될 수도 있다.
아래 예제 코드는 dispose()를 사용하는 예다.
public override function dispose():void {			
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
myQuad.removeEventListener(Event.ENTER_FRAME, onEnterFrame);

super.dispose();
}

샘플은 이벤트 리스너를 제거하는 것이다. Starling 이벤트 리스너에 약한 참조를 사용할수 없기 때문에 삭제 타이밍에 확실히 삭제하도록 한다. 메소드의 마지막 행에서 super.dispose()를 호출한다. 이렇게 하면 객체에 addChild()로 추가된 모든 자식 객체에 대해 dispose()가 호출된다. 따라서 myQuad.dispose()는 명시적으로 기술할 필요가 없다. 기타 표시 목록에 추가되지 않은 객체가 있다면 dispose() 실행은 필수다.

또한 표시 목록에 추가할 수 없는 객체에서 리소스의 개방이 필요한 객체가 있다면 여기에 필요한 처리를 기술한다. 예를 들어, 다른 객체와 공유하는 전용 텍스처(여기서는 myTexture)를 참조하고 있다면 이 객체를 소멸한다면 myTexture.dispose()를 실행하여 myTexture가 확보한 비트맵 메모리 공간을 해제해야 한다.



원문 : http://cuaoar.jp/2011/12/enterframe-starling.html

package {
	import starling.events.Event;
	import starling.display.Quad;
	import starling.display.Sprite;

	public class Demo extends Sprite {
		private var myQuad:Quad;

		public function Demo() {
			// addedToStage 이벤트에 대한 리스너 추가
			addEventListener( Event.ADDED_TO_STAGE , onAddedToStage);
		}
		private function onAddedToStage(e:Event):void {

			// Quad의 인스턴스를 생성           
			myQuad = new Quad(200,200);

			// 각 정점의 색상을 지정         
			myQuad.setVertexColor(0,0xFFFFFF);
			myQuad.setVertexColor(1,0xFF0000);
			myQuad.setVertexColor(2,0x00FF00);
			myQuad.setVertexColor(3,0x0000FF);


			// 기준점을 Quad 인스턴스의 중심으로 설정
			myQuad.pivotX = myQuad.width >> 1;
			myQuad.pivotY = myQuad.height >> 1;

			// Quad의 인스턴스를 중앙에 표시
			myQuad.x = stage.stageWidth >> 1;
			myQuad.y = stage.stageHeight >> 1;

			// Sprite에 Quad 인스턴스를 추가            
			addChild(myQuad);

			// EnterFrame 이벤트 리스너 추가            
			myQuad.addEventListener( Event.ENTER_FRAME , onEnterFrame);
		}

		private function onEnterFrame(e:Event):void {
			// Quad의 인스턴스를 회전           
			if (e.currentTarget as Quad) {
				myQuad.rotation +=  .01;
			}
		}

		public override function dispose():void {
			removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			myQuad.removeEventListener(Event.ENTER_FRAME, onEnterFrame);

			super.dispose();
		}
	}
}
    

설정

트랙백

댓글

[Starling-03] Flash 컨텐츠 표시의 기본

Programming/Framework 2012. 1. 5. 01:50
Starling은 Stage3D를 이용한 빠른 2D 드로잉을 실현하기 위해 설계된 framework이다. 이전 기사에서 개요와 간단한 사용법을 소개했다. Starling에서는 3가지 방법으로 애니메이션을 사용할 수 있다. 이 방법을 여러 번에 나눠서 소개한다. 기존의 애니메이션 방법과 비교해 보자.

개발 환경 준비
Starling의 개발 환경은 Flash Player 11과 AIR 3가 필요하다. 툴은 Flash Builer 4.6을 권장한다. Flash Professional CS5 또는 CS5.5를 사용하는 경우 다음 문서에서 소개하는 기능확장이 편리하다.
Flash Professional CS5 or CS5.5에 Flash Player 11 설정 MXP

그리고 Starling framework는 github에서 구할 수 있다.
PrimaryFeather / Starling - Framework / zipball

위 링크에서 다운로드한 zip에 포함되어 있는 SWC 파일을 경로에 추가하면 Starling 애플리케이션을 개발 할 수 있다. 또한 혼합 모드에 direct를 지정하지 않으면 제작에 성공해도 화면에 표시할 수 없다. 따라서 SWF 경우 wmode = direct를, AIR일 경우 <renderMode> direct </renderMode> 로 지정하는 것을 잊지 말아야한다.

Starling 인스턴스 생성
Starling로 렌더링하려면 먼저 Starling의 인스턴스를 생성한 다음 start() 메소드를 호출한다. 이 부분은 어떤 Starling을 개발에도 그대로 사용할 수 있다. 아래가 가장 간단한 예제이므로 사용해보자. fla 파일에서 document class로 사용하는 것이 편하다.

package{
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import starling.core.Starling;

        public class StartStarling extends Sprite{
		private var myStarling:Starling;

		public function StartStarling(){
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;

			// Starling의 인스턴스를 생성
			myStarling = new Starling(MyStarlingSprite,stage);
			// 그리기 작업을 시작
			myStarling.start();
		}
	}
}

Starling의 생성자 첫 번째 인수는 Starling의 Sprite다. 이 Sprite의 내용이 실제 화면 그리기에 사용된다. 그리기 정보는 Flash Player의 Sprite와 마찬가지로 자식 객체의 목록 구조와 같이 유지된다. 두 번째 인수는 표기 객체의 그리기 stage다. Starling 생성자는 5개의 인수를 가지지만 3 번째 이후 인수는 기본값을 가지고 있기 때문에 일반적으로 지정할 필요가 없다. 명시적으로 소프트웨어에서 3D 렌더링을 사용하려는 경우에는 5개의 인수를 작성할 수 있다. 마지막 인수가 혼합 모드를 지정한다.

// 5 번째 째의 인수로 그리기 모드를 지정 myStarling = new Starling (Game, stage, null, null, Context3DRenderMode.SOFTWARE );

이렇게 할 경우, 어떤 환경에서도 GPU로 렌더링 되지 않고 CPU로 처리하게 된다. 만약 실행 중에 소프트웨어 렌더링으로 대체되어 있는지 확인하고 싶다면 Starling 인스턴스 context.driverInfo 속성을 통해서 확인할 수 있다. 다음은 context3DCreate 이벤트를 사용하여 Stage3D를 초기화 한 후, 소프트웨어 렌더링의 프레임 속도를 절반으로 설정하는 예를 보여준다.

stage.stage3Ds[0].addEventListener (Event.CONTEXT3D_CREATE,onContext3DCreate); private function onContext3DCreate (event : Event) : void { if (Starling.context.driverInfo.toLowerCase() indexOf ( "software ")!=- 1){ Starling.current.nativeStage.frameRate = 30; } }

Starling 런타임 오류 검사를 수행하려는 경우에는 start()를 호출하기 전에 다음 설정을 추가한다.
myStarling.enableErrorChecking = true;

그러나 오류 검사 및 성능에 미치는 영향이 크기 때문에 디버깅 이외에는 설정하지 않는 것이 좋다. 기타 Starling 클래스의 기능은 다음 기회에 소개할 예정이다. 우선 온라인 문서는 이 곳에서 확인할 수 있다. Starling @ Starling Framework Reference

사용자 정의 Sprite 만들기

(참고 : 앞으로 Sprite와 같은 클래스 이름은 설명이 없는 한 모두 Starling 프레임워크에 종속된 클래스다. 익숙해질 때까지 실수에 주의가 필요하다.)

다음은 Starling의 생성자의 첫 번째 인자로 지정하는 Sprite 사용자 정의 클래스를 만든다. 만드는 단계는, 표시 오브젝트를 작성하고 Sprite에 addChild() 메소드를 추가하는 기존의 방식과 비슷하다. Stage3D의 그리기 단위는 삼각형이지만 Starling은 삼각형 2개를 기본으로 한다. 따라서 사각형에 해당하는 Quad 클래스의 인스턴스를 표시하는 방법에서 시작한다. 아래의 샘플은 화면에 사각형을 표시하는 것을 수행한다.

package { import Starling.display.Quad; import Starling.display.Sprite; public class MyStarlingSprite extends Sprite { private var myQuad:Quad; public function MyStarlingSprite() { // Quad의 인스턴스를 생성 myQuad = new Quad(200,200); // 우선 채우기 색상을 지정 myQuad.color = 0xABCDEF; // Sprite에 Quad 인스턴스를 추가 addChild(myQuad); } } }

위 코드를 실행하면 사각형이 화면 왼쪽에 그려진다. 사각형을 화면 중앙에 표시하려면 다음과 같이 Quad의 좌표를 설정한다.

myQuad.x = stage.stageWidth - myQuad.width>> 1; myQuad.y = stage.stageHeight - myQuad.height>> 1;
단, 위의 코드는 stage 속성에 대한 액세스를 포함한다. 따라서 Sprite가 초기화가 끝나기 전에 실행되면 오류가 발생한다. 그래서 addedToStage 이벤트를 이용한다. 이 addedToStage 이벤트는 Starling 이벤트지만, Flash Player의 addedToStage 이벤트 처럼 Stage가 이용 가능하게 된 것을 알려준다.

package { import Starling.events.Event; import Starling.display.Quad; import Starling.display.Sprite; public class MyStarlingSprite extends Sprite { private var myQuad:Quad; public function MyStarlingSprite() { // addedToStage 이벤트에 대한 수신기를 추가 addEventListener( Event.ADDED_TO_STAGE , onAddedToStage); } private function onAddedToStage(e : Event ):void { // Quad의 인스턴스를 생성 myQuad = new Quad(200,200); myQuad.color = 0xABCDEF; myQuad.x = stage.stageWidth - myQuad.width >> 1; myQuad.y = stage.stageHeight - myQuad.height >> 1; // Sprite에 Quad 인스턴스를 추가 addChild(myQuad); } } }

원문 : http://cuaoar.jp/2011/12/starling-flash.html
    

설정

트랙백

댓글

[Starling-02] Starling 2D framework 소개

Programming/Framework 2012. 1. 4. 18:25
이전 포스트에서 이야기한 내용과 같이 Stage3D의 지원을 통해서 FlashPlayer 렌더링 기술은 확실히 진화했다. 오랜만에 느껴보는 진화다. Starling 외에도 ND2D와 같은 framework가 등장하고 있으니 앞으로 여러가지 다양하고 새로운 것들이 나타날 것 같은 예감이다.(Alchemy의 이야기와 FlashPlayer에서 다중스레드 지원 이야기 등등)

이번에는 조금 더 자세하게 Starling을 소개한다.

Starling 아키텍처
Starling은 Stage3D로 구축되어 있다. Stage3D는 데스크탑 환경에서 DirectX 및 OpenGL, 모바일 환경에서는 OpenGL ES2에 구축되어 있다. 따라서 OpenGL 등이 GPU의 API를 직접 호출하기 때문에 Starling이 두 계층 사이에서 GPU를 사용할 수 있는 것이다.

1. Starling
2. Stage3D
3. OpenGL, DirectX, OpenGL ES2
3. GPU


Starling은 약 80kb 용량으로 가볍지만 이 때문에 Starling에서는 기존의 플래시 표시객체의 모든 기능이 제공되지는 않고 한정적이다. 아무래도 주로 게임 용도를 염두에 두고 설계되었기 때문이라고 생각된다.(물론 게임 이외에도 사용할 수 있다.) Starling의 이벤트 모델, 클래스 계층 구조도 기존 플래시 구조와 비슷하다. 계층의 순서는 아래와 같다.

1. starling.events.EventDispatcher
2. starling.display.DisplayObject
3. starling.display.DisplayObjectContainer

이어서 DisplayObjectContainer 아래에 Button, Sprite, TextField등이 정렬된다.
MovieClip은 조금 다르다. Image class의 서브 클래스이다. 아래와 같은 계층관계를 가지고 있다.

1. starling.display.DisplayObject
2. starling.display.Quad
3. starling.display.Image
4. starling.display.MovieClip


Image의 서브 클래스인 MovieClip은 GPU를 활용하기 위해 최적화되어 있기 때문에 기존에 타임라인 애니메이션을 좋아하는 사람은 활용도가 높다. 그리고 Quad라는 새로운 클래스가 등장했는데 Quad는 사각형 영역을 그리기 위한 클래스다.

비트맵 이미지를 표시하려면 다음과 같다.
// 비트맵을 포함
[Embed (source = "myBitmap.png")]
private static const myBitmap:Class;

// 비트맵 텍스처를 생성
var texture:Texture = Texture.fromBitmap(new myBitmap());

// 텍스터를 사용하여 이미지 객체를 생성
var image:Image = new Image(texture);

// 이미지의 표시 위치를 지정
image.x = 300;
image.y = 150;

// 이미지를 표시
addChild(image);

기존의 DisplayObject와 Starling을 동시에 사용하는 경우
Stage3D는 기존의 표시객체와 다른 레이어에 그려진다. 참고로 GPU에서는 비디오 재생을 StageVideo(FlashPlayer 10.2에서 도입) 레이어에 별도로 그려진다. 각 레이어의 관계는 아래와 같다.

1. 표시목록
2. Stage3D
3. StageVideo


각각이 독립된 레이어로 다른 레이어의 display 데이터에 직접 액세스할 수 없다. 예를 들어, StageVideo에서 재생중인 영상을 표시객체에 붙이는 것은 현재는 할 수 없다. 표시 목록과 Starling(즉 Stage3D)를 동시에 사용할 경우, 표시 목록이 레이어이므로 모든 표시 객체는 Starling의 객체 위에 표시된다. Stage3D는 프레임마다 모든 영역을 다시 그린다. 그리고 현재 버전에서는 Stage3D 객체를 투과할 수 없다. 따라서 StageVideo 위에 객체를 올리기 위해서는 Starling객체가 아닌 표시객체를 사용해야 한다.


Stage3D를 사용할 수 없는 경우
Starling의 Stage3D를 사용하려면 wmode를 direct로 지정해야 한다. wmode가 지정되지 않았거나 wmode가 다른 값으로 설정되어 있으면 런타임 오류가 발생한다. Starling은 오류가 발견되면 wmode가 올바르게 지정되지 않았다는 메시지를 출력한다. 따라서 HTML에서 플래시가 제대로 임베드 되지 않았을 경우, 쉽게 발견할 수 있다. wmode가 올바르게 지정되어 있어도 드라이버의 버전, 또는 GPU를 사용할 수 없는 경우에는 Stage3D가 SwiftShader로 대체되어 실행되기 때문에 원하는 속도를 내기 어렵다. FlashPlayer 11버전이 설치되어 있더라도 느리다면 드라이버 설치 버전이 최신인지 확인이 필요하다.

원문 : http://cuaoar.jp/2011/09/starling-actionscript-3-1.html 
    

설정

트랙백

댓글

Starling에서 resize 적용

Programming/Framework 2012. 1. 4. 16:16
Starling를 이용하여 렌더링을 할 경우 stage의 width, height를 변경하더라도 렌더링 되고 있는 픽셀의 크기는 변경되지 않는다. 따라서 렌더링 되고 있는 Starling의 stage 사이즈를 변경하기 위해서는 아래와 같이 Starling.current.viewPort의 Rectangle 값을 변경해 줘야 한다.
package 
{
    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
	import flash.geom.Rectangle;
    
    import starling.core.Starling;
    import flash.events.Event;

    public class Startup extends Sprite
    {
        private var mStarling:Starling;
        
        public function Startup()
        {
            stage.scaleMode = StageScaleMode.NO_SCALE;
            stage.align = StageAlign.TOP_LEFT;
            
            mStarling = new Starling(Demo, stage);
            mStarling.enableErrorChecking = false;
            mStarling.start();

			stage.addEventListener(Event.RESIZE, onResizeHandler);
			addChild(new Gaze(true, "http://jasu.tistory.com"));
        }
		
		private function onResizeHandler(e:Event):void{
			var viewPortRectangle:Rectangle = new Rectangle();
			viewPortRectangle.width = stage.stageWidth;
			viewPortRectangle.height = stage.stageHeight;

			Starling.current.viewPort = viewPortRectangle;
		}
    }
}
이렇게 viewPort의 사이즈를 변경하면 resize 이벤트를 통해서 stage의 width, height 사이즈가 변경된 사이즈로 렌더링 된다. 그러나 렌더링되는 실제 해상도에는 변함이 없기 때문에 강제로 resize한 것처럼 스케일 비율이 무시된다. (stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; 로 설정을 했더라도 Starling(Stage3D)을 통해서 렌더링되는 영역은 별도) 따라서 아래와 같이 mStarling.stage의 stageWidth, stageHeight 값도 변경해야 실제 렌더링하려는 픽셀 사이즈를 확보할 수가 있다.
private function onResizeHandler(e:Event):void{
			var viewPortRectangle:Rectangle = new Rectangle();
			viewPortRectangle.width = stage.stageWidth;
			viewPortRectangle.height = stage.stageHeight;
			Starling.current.viewPort = viewPortRectangle;
 
			mStarling.stage.stageWidth = stage.stageWidth;
			mStarling.stage.stageHeight = stage.stageHeight;
		}
    

설정

트랙백

댓글

2009년 6월 18일 Tweener의 개발종료를 선언하다.

Programming/ActionScript 3.0 2009. 8. 20. 00:15

본인이 ActionScript 3.0을 처음 접할 때 사막의 오아시스처럼 큰 도움을 주었던 Tweener 라이브러리가 최종 버전을 끝으로 개발을 종료한다고 한다. 현재 본인은 TweenLite, TweenMax를 사용하고 있지만 ActionScript 3.0을 재미있게 공부하고, 연구할 수 있도록 나에게 동기를 준 멋진 라이브러리가 아닌가 생각한다.

MC Tween 시절부터 플래시의 발전 속에서 역사가 깊은 라이브러리이기에 여러 가지 생각이 머리 속에서 스쳐 지나간다. Zeh Fernando씨에게 박수를 보낸다. 아래는 원문을 번역한 내용이다. 명확히 알 수 없는 내용은 포함하지 않았으며 일부 문장은 나름대로 재 해석한 관계로 내용 전달이 정확하지 않을 수도 있지만 전체적인 요점은 파악할 수 있을 것이라 생각한다.


========================================================================================
원문 : Zeh Fernando Blog Archive Tweener, 4 years later - A post mortem

우선 시작부터 이야기 하자면 나는 몇 년 전에 Flash 개발 과정에서 애니메이션이 필요하여 MC Tween를 개발했다. MC Tween는 ActionScript의 기본적인 tween을 확장하여 사용했다. 당시에 뛰어난 tween 확장 기능이 존재하고 있었지만 모두 나의 취향과 맞지 않았다. API의 대부분이 너무 추상적이었고 내가 요구하는 것과 달랐기 때문에 prototype 형식을 채용하여 MovieClip의 오브젝트형에 새로운 기능을 추가해서 만들었다. MovieClip에 새로운 기능을 추가하는 형태에 찬사를 주는 사람들이 있었기 때문에 그만한 인기를 얻을 수 있었다.

그러나 2005년 해가 되면서 MC Tween의 변화가 필요하게 되었다. MC Tween은 의도대로 움직이고 있었지만 ActionScript의 문법이나 패러다임(특히 AS2의 등장)이 변화하고 객체지향프로그래밍을 이해하기 시작하면서 MC Tween은 이미 나의 개발 워크플로우에 맞지 않는다는 것을 깨닫게 되었다. 더욱이 MC Tween의 개발이 꽤 정체되어 있었다.

그러던 그 해 6월부터 나는 클래스를 사용하여 새롭게 tween 확장 기능을 실험적으로 개발하기로 했다. 개발 당초에는 인스턴스 베이스(tween 인스턴스를 생성)였지만 이후에 addTween() 이라는 하나의 메소드에 의해서 모든 tween을 생성하는 정적인 클래스 구조로 변경했다. 그리고 stopTween(), getTween()과 같은 부속 메소드를 사용하여 여러 가지 기능을 조작할 수 있도록 했다.

이후에도 클래스는 매우 많은 변경이 있었다. 클래스명이 바뀌거나(초기에는 Twina였던 것이 Tweener가 되고 ZTweener가 되었다가 다시 Tweener로 되돌아옴)  패키지의 위치가 바뀌거나(generic *에서 zeh.easing.*으로, 그리고 다시 caurina.transitions.*)  API가 변경되거나 인스턴스 베이스에서 정적 클래스로 변경한 것은 말할 것도 없고 그 외에도 내부 구조의 변경 등이 많이 있었다. 이러한 과정에서 스스로가 많이 배웠다는 것이 이 글의 취지이지만 자신을 위해서 무엇인가를 만드는 경우, 결과를 누군가가 보고 평가하거나 더욱이 그것을 누군가가 매우 소중한 일에 사용하지 않을 것이라고 생각하고 만든다면 결과적으로 많은 실수를 허용하게 된다. 그러나 그 과정에서 보다 좋은 방법을 찾아내게 되는 것이다.

내가 이 프로젝트를 시작했을 무렵, tween 확장 기능으로서 제일 유명했던 것은 Fuse Kit이였다. 나는 이것과 겨룬다는 생각은 없었다. 다만 나 자신을 위해서 무엇인가를 만들고 자신의 요구에 맞게 변경해 나가는 자유를 즐기고 있었다. Tweener는 긴 시간동안 비공개(나 자신만 사용) 였던 것이 그러한 이유다. 무엇보다 Gringo를 위한 프로젝트를 위해서 사용하고 있었지만 공개된 것은 2007년 1월 최초의 버전을 개발하고 나서 대략 2년 후였다. Nate Chatellier가 팀에 참가하여 AS3버전의 Tweener를 만들었었기에 이대로 비공개로 하는 것은 공정하지 않다고 생각했다. 더욱이 그 시점에서 생각하기에 앞으로 API에는 큰 변화가 있을 것 같지 않았기 때문에 다른 사람들로부터 피드백을 받고 싶은 생각도 있었다.

Tweener는 특별히 참신한 것도 아니고 API는 새로운 것이 없었다. Tweener가 채용한 새로운 tween생성 방식도 다른 tween의 확장에서도 채용되고 있었다. AS1 베이스 확장에서도 채용되고 있었다. 그렇지만 그것은 그 시기에 올바른 구문이었다. 그러한 형태는 인기가 있었고 다른 언어판까지 나오게 되었다.

이는 4년전의 이야기.(로그를 보면 Tweener은 2005년 6월 15일에 개발 개시한 것으로 되어 있다.) 현재는 이 밖에도 많은 tween 확장판이 등장하고 있고, 특히 유명한 것은 Go, TweenLite / TweenMax, GTween, BetweenAS3 등이 있다. 라고 하는 것은? 그래, 또 그 때가 찾아왔다고 하는 것이다. 현재와 같이 AS3버전이 있다고 해도 Tweener가 가지는 패러다임의 대부분은 이미 시대에 뒤떨어져 버렸다. 나는 점점 불안을 느끼게 되었다. 나는 그동안 많은 것을 배웠다. 이제 움직이기 시작할 때다.

바로 움직이기 시작할 수도 있었지만, 그 전에 되돌아보고, 잘 된 것, 가지 않았던 것을 되짚어 보려고 했다. 이 글은 말하자면 Tweener의 사망선고 글, 4년간 내가 무엇을 배웠고, Tweener와 같은 라이브러리가 어떻게 변화해 왔는가 하는 점에 대한 나름의 분석이다.

그런데 AS2에서 AS3로 이동하는 시점에 고려해야 할 중요한 포인트가 한 개 있다. ‘에러’다. AS2 에러는 null 오브젝트의 프로퍼티를 변경하는 스크립트를 실행해도 FlashPlayer는 그대로 지나쳐 버린다. 물론 오브젝트가 존재하지 않기 때문에 스크립트 자체는 기능하지 않지만 그것을 알려주는 에러 메시지가 없다.

이것은 엄밀한 동작이 기대되는 경우에는 문제가 된다. 취득한 데이터가 의도한 것인지를 알기 위해서는 몇 개의 레벨의 검증이 필요하고, 그렇게 해서 다른 방법으로 유저에게 경고를 보낼 수 있었다. Tweener의 AS2 버전에서는 유저에게 보다 안전하게 동작할 수 있도록 노력했다. 구체적으로는 tween 중에 대상이 되는 오브젝트가 존재하는지를 체크하고, tween 되고 있는 프로퍼티에 디폴트의 값이 설정되어 있는지를 체크하고 있다.

하지만 AS3 버전으로 만들면서 그 기능은 필요 없게 되었다. 존재하지 않는 오브젝트나 프로퍼티에 액세스 하려고 하면 코드의 실행은 중단되게 되었다. 이것은 좋은 일이다. 유저가 자신이 무엇인가 실수를 범하고 있고, 그것을 수정하지 않으면 안 된다고 하는 것을 이해하는데 도움이 되기 때문이다.

한편, AS3 버전으로 임포트하는 시점에 Tweener는 이러한 AS2의 패러다임을 계승해 버렸다. 조금 전에 쓴 것과 같이 체크 기능도 많이 남아 있다. 또한 존재하지 않는 프롭퍼티의 값을 tween하려고 하면 FlashPlayer의 에러가 아닌, Tweener 내에서 설정한 커스텀 에러를 표시하게 되어 있다.

if (rScopes[0][istr] == undefined) {
     printError("The property '" + istr + "' doesn't seem to be a normal object property of " + String(rScopes[0]) + " or a registered special property.");
}

속성을 업데이트하기 위한 반복 루프에서도 마찬가지다. 업데이트하는 개체가 있는지 확인하고, 속성이 존재하는지 확인하고 있다. 이 방식으로 인하여 성능이 저하되고, 크기가 증가라는 부작용도 제기됐다.

새로운 tween을 적용할 때, Tweener는 비슷한 tween (동일한 개체의 동일한 속성에 적용하는 tween)이 있는지를 찾아 그들을 제거하려고 한다. 별도로 애니메이션을 하기 위해 요구되는 행동이지만, 이로 인해서 2개의 문제가 발생한다. 먼저 tween 덮어쓰기를 강제로 실행하면서 옵션은 없다는 것, 그리고 새 tween을 생성할 때 성능을 크게 저하 시킨다는 것, 이미 많은 tween이 동일한 위치에 있는 경우에는 더욱 그러하다.

최근 tween 엔진 성능을 비교해보면 문제는 더 명백해 진다. 실제 tween 갱신에 소요되는 시간과 메모리 소비 등은 나쁘지 않지만, 생성 tween 양이 늘어나면 늘어날수록 Tweener 처리는 느려진다. 새로운 tween이 생성될 때마다 기존의 모든 tween과 충돌을 체크하기 때문에 tween 생성에 소요되는 시간이 증가하는 것이다. tween 수가 1000을 초과한 상태에서 새 tween을 생성하려고 하면, 애니메이션 자체의 소요 시간을 초과하거나 FlashPlayer가 잠깐 멈추는 경우도 종종 있다. Tweener는 tween 목록을 단지 하나의 배열에 관리하고 있기 때문이다. 더 유용한 AS3 기본 기술을 이용하여 위 사항은 해결할 수 있는지도 모른다. 어쨌든 Tweener은 너무 안전하게 작동하려고 한다. 사용자가 성능을 향상시키고 싶은 처리를 허용하지 않는다.

오늘 Tweener에 대해 언급하는 것은 더 이상 최적화 문제가 아니라고 생각하기 때문이다. 보완할 수는 있다. 몇 가지 검사하는 기능을 제거, 또는 Array 대신 Dictionary와 같은 AS3의 새로운 기능을 추가하여 목록을 관리하거나, Vector 기능을 추가하거나 할 수 있다. 하지만 솔직히 말해서 Tweener는 그 전성기가 끝났다고 나는 확신한다. 그렇기 때문에 그러한 변경을 해도 곧바로 모든 것이 단순히 해소될 수 없다. 그러니 더 이상 Tweener을 업데이트 하는 것은 무의미하다. 물론(특히 동시에 1000개 이상 같은 tween을 수행할 필요가 없는 경우) 현재도 작동하고, 앞으로도 계속 도움이 될 것이다.

숨어 있던 새로운 버그가 나타나지 않는다면 Tweener를 업데이트할 생각이 없지만 최근에 있었던 이슈들을 업데이트했다. 새로운 버전의 1.33.74 Google Code 프로젝트 페이지 subversion 서버에 공개된다. 이 업데이트는 기본 tween 덮어쓰기 내용은 남겨두면서 overwrite라는 새로운 매개 변수를 추가하고 (이 값을 true로 하면 그 동안의 기능과 같다.) autoOverwrite는 새로운 정적 속성을 추가했다.

Tweener Comparison

위 그림에서 파란색 그래프는 tween없는 상태를, 오렌지 그래프는 Tweener 1.31.74를, 노란색 그래프는 Tweener 1.33.74에서 overwriting을 false로 설정한 상황을 보여주고 있다.

대단한 일이 아닐지라도, 이것은 이 프로젝트에 참여했던 몇 년간 내가 받은 지원, 조언, 배움, 그리고 훌륭한 경험에 대한 감사의 표시로 받아들여 주길 바란다. 프로젝트를 직접 지원해 준 회원 뿐 아니라, 이 프로젝트를 다양한 측면에서 지원해 준 모든 분들에게 진심으로 감사한 마음이다.

내가 Tweener의 개발을 Google Code 사이트로 옮긴 후부터 집계해온 재미있는 그래프를 보여 주겠다. 이것은 버전별 안정 버전 Tweener 다운로드 비율(전체 다운로드 회수)을 비교한 것이다. AS3가 차지하는 비중이 늘고 있다는 것을 알 수 있다. 덧붙여서,

Tweener download statistics

오늘 출시 버전은 포함하지 않았다.

Tweener download statistics

후기로 여러분에게 전달하고자 하는 것이 있다. 나는 현재 tween에 있어서 개인적으로는 Tweener에 의해 소개된 것과 다른 접근을 사용하고 있다. 내 자신의 워크플로우는 조금 바뀌었다. 색 트윈 및 기타 특별한 지름길은 사용하지 않는다. 대신 독립적인 클래스와 getter / setter 및 decorator 등을 통한 특정 기능을 사용하게 되었다. 내가 Tweener를 개발한 이유는, 자신의 개발 흐름에 맞게 무언가를 적용하고, 수요가 있으면 다른 사람들이 사용할 수 있도록 하는 즐거움에 있었다. Tweener를 공개하는 데 많은 시간을 할애한 것은 그 때문이다. 나는 현재, 모든 사람의 요구에 부응하기 위해 만들어진 것을 사용하기보다는, 특정한 누구를 위해 만들어진 것을 사용하는 것을 선호한다.

분명한 것은, "Tweener2"나 그런 것은 나오지 않는다는 것이다.
다시 한번 감사합니다!

========================================================================================

세상의 모든 것들은 시간의 흐름에 따라 변화하고, 소멸하고, 다시 새로운 것이 탄생하기를 반복한다. 플래시의 경우도 예외가 아니다. 플래시는 1년이 멀다 하고 새로운 API와, 흥미로운 기능들이 추가되며 발전해 왔다. 하지만 그 화려한 변신에 가려진 개발자들의 눈물겨운 노력은 일반 사람들에게는 잘 알려지지 않는다. 더욱이 플래시라는 분야를 재미없는, 해야만 하는 일로 생각하는 개발자라면 그 정도는 더욱 심했을 것이다.

Zeh Fernando씨가 Tweener의 사망선고하는 글을 올리기까지 얼마나 많은 노력과 시간을 투자했을지, 그리고 스스로에게 의미가 있는 프로젝트를 종료하기까지 많은 고민과 생각을 했으리라. 다시 한번 멋진 프로젝트를 진행했던 Zeh Fernando씨에게 박수를 보낸다.

어쩌면 Zeh Fernando씨가 우리에게 도움을 준 것 보다 Tweener를 의미 있는 작업에 활용하며 피드백을 주었던 수 많은 사람들로부터 받은 관심이 Zeh Fernando씨가 불특정 다수에게 감사를 표하는 가장 큰 이유일 것이다. Tweener는 종료되었지만 앞으로도 더욱 다양한 작품으로 만날 것을 기대해 본다.

    

설정

트랙백

댓글

[UPL006] BitmapData를 이용한 드로잉

Project/UPL 2009. 8. 17. 03:57


1. stage에 마우스 클릭 후, 드로잉하면 30개의 라인을 화면에 그려준다.
1-1. 마우스 움직임의 속도에 따라 30개의 라인 넓이가 조정된다.
1-2. 라인의 alpha값은 0.16

2. 버튼 기능
2-1. '지우기' 버튼은 그려진 비트맵 데이터를 clear함.
2-2. '로컬 이미지 적용' 버튼은 로컬에 있는 이미지 파일을 적용하여 라인의 위치 색으로 설정함.
2-3. '그림 다운로드' 버튼은 현재까지 그려진 bitmap 이미지를 로컬에 저장함.
2-4. RGB 색 선택시 해당 색으로 배경 색을 변경함.

Bitmap을 이용한 라인 표현은 ActionScript 3.0을 Processing 언어와 유사하게 개발하고 있는 Frocessing 라이브러리를 이용함.






    

설정

트랙백

댓글

[AS3] DigiMix

Programming/ActionScript 3.0 2008. 7. 23. 13:27
    

설정

트랙백

댓글

[AS3] Andre Michelle의 AudioTool

Programming/ActionScript 3.0 2008. 7. 8. 23:03
요즘 Andre Michelle이 음향 관련 놀이를 자주 한다는 생각을 했는데 결국 이런 멋진 결과물을 만들어 냈다. 오디오나 음향 관련 지식이 부족한 나에게 이걸 가지고 놀아보라고 하면 아마도 헬리콥터 장난감을 물 속에서 가지고 놀지 싶다. 플래시와 자바를 가지고 개발 했다고 하는데 앙드레의 고집스런 뚝심을 따라가려면 아직도 멀었다는 생각이 든다.










사용자 삽입 이미지

http://www.hobnox.com/index.1056.en.html
    

설정

트랙백

댓글

사용자 경험과 관계- Powers of Information

User Interface/Web 2008. 4. 13. 04:15
일본의 한 미술관 매점 단말용 컨텐츠로 제작된 사이트라고 한다. 단말기의 최소 해상도가 1920x1080이기 때문에 그 이하 해상도에서는 짤려서 보이고, 로컬에서 서비스되기 때문에 로딩 처리가 되지 않아서 이미지가 뜨기까지는 약간의 시간이 필요하다.

심플한 디자인과 절묘하게 어울리는 효과음이 전체적으로 사이트의 느낌을 살리고 있다. 가장 훌륭한 점은 정보 설계로부터 플래시 컨텐츠의 효과를 1:1로 적절히 사용했다는 점이다.

사용자 경험은 관계에 영향을 많이 받는다고 생각한다. 여기서 관계라는 의미는 연결을 의미하는데, 예를 들면 화면 밖에 있는 오른쪽 이미지를 보기 위해 현재 이미지를 왼쪽으로 밀어서 사라지게 하는 행동은 우리의 머리 속에서 현재 사진과 오른쪽 사진은 보이지 않는 선으로 연결되어 있고 화면에 보이는 사진을 왼쪽으로 보내면 오른쪽에 있는 사진이 나타날 것이라는 추측에서 비롯된다. 이 사이트의 경우도 뎁스의 트리형태 정보구조를 표현함에 있어서 틀 속에 틀이라는 형태로 진행하고 있어서 정보의 전달이 명확하다고 볼 수 있다.

다만 아쉬운 점은 각 뎁스별 현재 위치(컨텐츠 그룹명)에 대한 정보 전달이 화면 모션으로만 이루어지고 있어서 사용자가 기억하고 있어야 한다는 점이다. 왼쪽의 Power of Information 텍스트를 일률적으로 할게 아니라 각각의 뎁스에 따라 정보구조명을 적용했더라면 하는 생각이 든다.

http://kiki.ex.nii.ac.jp/powers_of_information/

사용자 삽입 이미지

    

설정

트랙백

댓글

즐거운 만남 플래시 컨퍼런스....

Project/Programming 2008. 4. 8. 05:43
4월 5일, 땡굴이 형님이 운영하시는 액션스크립트 까페에서 1차 컨퍼런스 행사가 있었다. 집요한 문군애절한 부탁에 보헤형과 함께 스피커로 나서긴 했으나 이런 행사에서 스피커로 서는 것이 처음인지라 무엇을 어떻게 준비를 해야 할지 난감했다.

일단 ‘무엇을’ 준비해야 하는가에 대한 고민을 오래 한 것 같다. 무엇이든 일단 시작해 보자는 생각에 프리젠테이션을 위한 프리젠테이션 템플릿을 만들기 시작했다. 무엇보다도 내가 알고 있는 일의 작업 스타일에 대한 이야기를 하는 것이 설명하기도 편하고 오시는 분들도 도움이 될 듯싶었기 때문이다.

일단 무엇을 만들 것이라는 것이 결정되고 일주일 정도 지났을 때, 나는 작업량의 절반 정도를 진행하고 있었다. 그러던 어느 날 작업하던 flashDevelop 패키지 파일이 열리지가 않아서 각각 클래스들을 열어 봤더니 총 7개 정도의 클래스 파일이 깨져서 열리지 않거나 다른 클래스 소스와 짬뽕이 된 코드가 눈앞에서 펼쳐져 있더라는….쿨럭…

외장하드에 자료를 보관하고 있었는데 외장하드의 물리적인 트랙 에러가 발생한 듯싶었다. 일단 살아 있는 코드를 다른 하드에 저장 했다. 소실된 클래스들을 다시 만들 생각하니 힘이 쫙 빠졌다. 문제의 클래스(총 3개 정도는 파일이 열리지 않았었고 4개 정도의 파일이 회사 작업 클래스 코드들과 얽혀 있었다)들을 작성하는 데는 3시간 정도의 작업 시간이 걸린 것 같다.(했던 작업을 다시 하는 것인지라 3시간이 길게 느껴지긴 했다.)

사용자 삽입 이미지사진출처 : 문군


아무튼 그런 우여곡절 끝에 프리젠테이션 템플릿은 완성이 되었다. 하지만 이제는 ‘어떻게’가 문제였다. 어떤 내용으로 이것을 잘 포장하여 이야기를 풀어야 하는지는 생각조차 하지 않았기 때문에….

결국 내용은 평소에 보던 책과 인터넷을 헤집고 다니면서 얻은 자료들을 토대로 준비하게 되었다. 마지막 날에는 감기몸살까지 찾아와서 고생을 좀 했으니 내가 할 수 있는 노력은 어느 정도 했다고 생각하는데 이런 발표자의 마음이 전달 되었는지는 잘 모르겠다.

사실 컨퍼런스에 오신 분들의 작업 스타일, 하는 일에 대해서 충분히 고려하지 못했다는 생각이 든다. 너무 내 안에 있는 이야기만 일방적으로 한 것은 아닌가 하는 아쉬움이 남는다.

발표가 끝나고 1차, 2차, 3차까지 달렸는데, 살인적인 입담을 소유하고 있는 진우와, 앞 테이블(나에게는 뒷 테이블이어서 다행이었다. 쿠쿠) 연인의 행각에 어쩔 줄 몰라 하시는 땡굴이 형의 모습에 새벽 첫차를 타고 집에 도착할 때까지 턱이 아프도록 웃었다.
사용자 삽입 이미지사진출처 : 문군사용자 삽입 이미지사진출처 : 문군

다시 한번 궂은 일 마다하지 않고 컨퍼런스를 준비해 준 땡굴이형님과 그 아이들(문군포함 스텝님들)에게 고마움을 전한다. 그리고 결코 가볍지 않은 행사 후원을 해주신 단군소프트 관계자 분에게도 감사하다는 말을 전하고 싶다.

사용자 삽입 이미지사진출처 : 문군



비록 발표는 아쉬웠지만 내가 할 수 있는 일은 마무리하는 것이 좋을 것 같아서 컨퍼런스 때 발표했던 프리젠테이션 템플릿 소스와 UML등을 압축하여 올려 놓는다. 시간에 쫓기며 진행한 작업이니 잘못 된 부분도 있을 수 있고 좀더 최적화 해야 하는 부분에서 쉽게 쉽게 진행한 부분도 있으니 이해를 바란다.

다시 한번 노파심에서 말씀 드리지만 이 자료는 OOP 개념에 대한 이해의 목적으로 만들어진 자료이기 때문에 완벽하지 않을 수 있다. 하지만 OOP를 처음 접하거나 느낌이 슬슬 오기 시작하신 분들에게는 조금이나마 도움이 될 수 있지 않을까 싶다.

아무쪼록 사회생활을 준비하고 열심히 공부 하려는 후배들에게 플래시가 즐거운 공부와 놀이가 되었으면 한다. 파이팅~ ^^

ActionScript발표자료.alz

ActionScript발표자료.a01

ActionScript발표자료.a00


사용자 삽입 이미지



    

설정

트랙백

댓글

[AS3] Logger 그래프

Project/Programming 2008. 3. 1. 14:51

엑셀에서의 XML 스프레드시트를 저장하여 일련의 숫자 데이터를 LineGraph로 표현해주는 기능을 한다. 사내 회의 때 사용할 목적으로 만들게 되었다. 사용하는 XML 스프레드시트 데이터는 기본적으로 규칙을 가지고 있는데 아래와 같다.

하나의 셀에는 1뎁스, 2뎁스, 3뎁스까지 표현을 하고 그 이후 데이터들은 날자 별로 각각의 데이터가 들어가게 된다. 반듯이 지켜야 할 규칙은 1뎁스, 2뎁스, 3뎁스를 표현해야 하며 3뎁스의 첫번째 group의 [방문수, 절대 고유 방문자수, 페이지뷰, 평균 페이지뷰, 사이트 방문 시간] 5개의 데이터 타입을 아래에 group에서도 똑같이 적용을 하여야 한다.

위 최소한의 규칙을 적용한다면 cell의 가로 길이나 1뎁스, 2뎁스의 개수는 몇 개라도 상관이 없다.

이렇게 한 이유는 사용하고자 하는 데이터의 형태를 따르게 되었기 때문이다. 초기 작업 진행에 있어서 xml 스프레드시트 데이터의 형태가 트리구조의 형태를 갖지 못하기 때문에 데이터 표현에 있어서 어떠한 방법을 사용해야 하는지가 고민이었다. 1뎁스 데이터 안에 2뎁스와 3뎁스를 group화 할 경우에 각각의 데이터 비교에 있어서 하나의 그래프에 여러 개의 라인그래프를 넣어야 할 경우 불필요한 참조 형태이기 때문에 복잡한 데이터 구조를 조합하여 하나의 group데이터로 표현해야 하는 문제가 있었다. 이로 인해 CPU낭비와 구조화 작업에 있어서 어려움이 예상되었다.

그래서 뎁스에 따른 데이터를 group화 하지 않고 xml 스프레드시트의 각 라인별(cell단위)를 기준으로 하나의 데이터로 표현하고 AssetData 클래스를 통해서 각각의 cell 데이터를 검사하여 원하는 서비스별 데이터를 array로 받아올 수 있도록 하였다.

이렇게 데이터를 구분하였을 때 1뎁스, 2뎁스에서 원하는 데이터들을 멀티 선택하여 화면에 표현할 수 있게 되었다.

한 화면에서 보여질 수 있는 그래프는 위에서 언급한 것과 같이  [방문수, 절대 고유 방문자수, 페이지뷰, 평균 페이지뷰, 사이트 방문 시간] 5개의 그래프 컨테이너를 보여줄 수 있으며 각각의 그래프컨테이너에는 여러 개의 cell 데이터에 해당하는 라인그래프를 표현할 수 있다.

상단에 풀스크린을 지원하는 아이콘을 클릭할 경우 풀스크린으로 보여질 수 있으나 flashPlayer에서의 풀스크린을 할 경우 키보드 이벤트가 작동하지 않기 때문에 멀티선택을 할 수 없는 문제점이 있다. exe파일은 풀스크린이더라도 키보드 입력을 받을 수 있다.

exe파일 버전으로 올려 놓는다. xml데이터는 가상의 데이터 값을 넣어두었으니 필요하신 분은 비교 대상의 데이터를 직접 넣어서 사용해보면 좋을 것 같다. 플래시 안에서 data.xml 파일을 로드하게 해놓았으니 Logger.exe파일과 같은 폴더에 data.xml 데이터를 넣어서 사용하면 된다.


Logger.zip

http://dicaland.cafe24.com/blog/logger/Logger.swf

    

설정

트랙백

댓글

[AS3] FlashPlayer UPDATE3의 System.gc()

Programming/ActionScript 3.0 2008. 2. 9. 22:52
예전에 System.gc 내장 함수가 없었던 것으로 알고 있는데 업데이트 버전에서 생겨난 듯 하다. 기존에는 개발자가 강제로 CG를 실행시킬 수 없어서 완전한 메모리 테스트는 사실상 불가능 했다. 물론 강제로 많은 오브젝트를 생성하는 과정에서 일정한 메모리(FlashPlayer가 예상하는 적정 사용영역)을 벗어날 경우를 임의로 만들어서 확인할 수는 있었으나 이것 또한 어느 정도의 메모리 영역을 CG가 동작하는 시작점으로 보는가를 알 수 없기 때문에 어려움이 있었다.

System 클래스에서 지원하는 메소드에 gc가 있다. 이는 자바에서의 System.gc와 같이 이 함수를 실행하는 시점에서 강제로 CG가 동작하게 된다. 문제는 자바와 같이 플래시도 full gc를 할 경우 시스템 리소스 낭비가 예상된다는 것이다. System.gc 실행은 개발 테스트 과정에서 사용하되 작업물에서의 동적인 강제 실행은 피하는 것이 좋을 듯 싶으나 이는 이미 웹상에서는 System.gc가 작동하지 않는 듯 싶다. 경험상 flashPlayer9버전의 가비지콜렉터는 상당히 안정적이고 신뢰 할만 하다.

아래 예제로 만든 것을 보면 replay 버튼을 누름과 동시에 Event.ENTER_FRAME 이벤트가 등록된 sprite를 통해서 이벤트가 발생할 때마다 임의로 TextField를 생성과 소멸을 반복한다. 50개의 TextField가 생성되는 시점에서 Event.ENTER_FRAME가 등록된 sprite를 메모리해서 해제시킨다.

여기서 많은 개발자들이 Event.ENTER_FRAME 이벤트가 적용된 상태에서 removeEventListener로 이벤트를 해제하지 않고 sprite를 메모리 해제 시도를 했기 때문에 메모리에서 지워지지 않는다고 생각하는 듯 하다. 나도 예전에는 이 부분이 상당히 모호했다.  addEventListener로 강참조를 할 경우라도 역참조가 아닌 이상은 이벤트가 적용된 오브젝트가 메모리에서 해제하고 GC를 통해서 free memory가 되면 자동으로 등록되어 있는 이벤트도 발생하지 않는다.

여기서 혼돈했던 이유는 개발자가 강제로 가비지콜렉션을 실행하지 못하는 상황에서 sprite가 메모리에서 해제되지 않아서 이벤트가 계속 발생하는 것인지, gc가 동작하지 않아서 해제되지 않는 것인지 모호했기 때문이다.

아래의 예제에서 gc 동작버튼을 누르지 않더라도 일정한 시간이 지나면 flashplayer가 적당한 시점에서 gc를 가동하여 Event.ENTER_FRAME 이벤트가 등록된 sprite를 메모리에서 해제하면서 Event.ENTER_FRAME 이벤트도 발생하지 않게 된다. System.gc를 이러한 gc의 동작을 강제로 실행하므로써 개발자에게 즉시 free memory가 되었다는 것을 알려주므로 개발과정에서 요긴하게 사용될 듯싶다.

아래 swf상에서는 System.gc 함수가 실행되지 않는다. fla를 다운로드하여 로컬상에서 테스트 해보길 바란다.




    

설정

트랙백

댓글

[AS3] Tween Engine (TweenLite)

Programming/ActionScript 3.0 2008. 2. 5. 19:28
TweenBencher 을 이용해서 AS3용 Tween 엔진을 테스트 해 봤다. 1등은 단연 Simple AS3 Tween으로 나왔는데 이것은 따로 클래스화 되어 있는 것이 아니고 fl.motion.easing.Exponential 의 easeInOut 함수만을 따로 빼서 직접 width을 적용한 형태라서 빠를 수 밖에 없다. 테스트를 하지 않은 fl 기본 트윈 클래스나 기타 다른 것들은 비교할만한 속도를 내지 못하여 제외 하였다.

비교 대상이 되는 것들은 Tweener TweenLite이다. Tweener은 그 사용법과 Bezier 곡선 처리 기능을 제공하기 때문에 사용성면에서 좋은 엔진이지만 많은 기능들이 포함되어 있는 만큼 속도는 약간 떨어진다.








Benchmark results: Simple AS3 Tween
------------------
125 Sprites    ::    Start Lag: 0 seconds    ::    FPS: 57
250 Sprites    ::    Start Lag: 0 seconds    ::    FPS: 57
500 Sprites    ::    Start Lag: 0 seconds    ::    FPS: 55
1000 Sprites    ::    Start Lag: 0 seconds    ::    FPS: 47
2000 Sprites    ::    Start Lag: 0.01 seconds    ::    FPS: 38
4000 Sprites    ::    Start Lag: 0.06 seconds    ::    FPS: 26

Benchmark results: TweenLite
------------------
125 Sprites    ::    Start Lag: 0 seconds    ::    FPS: 61
250 Sprites    ::    Start Lag: 0 seconds    ::    FPS: 55
500 Sprites    ::    Start Lag: 0.01 seconds    ::    FPS: 40
1000 Sprites    ::    Start Lag: 0.01 seconds    ::    FPS: 31
2000 Sprites    ::    Start Lag: 0.02 seconds    ::    FPS: 23
4000 Sprites    ::    Start Lag: 0.18 seconds    ::    FPS: 19

Benchmark results: Tweener
------------------
125 Sprites    ::    Start Lag: 0.11 seconds    ::    FPS: 56
250 Sprites    ::    Start Lag: 0.02 seconds    ::    FPS: 61
500 Sprites    ::    Start Lag: 0.06 seconds    ::    FPS: 46
1000 Sprites    ::    Start Lag: 0.2 seconds    ::    FPS: 33
2000 Sprites    ::    Start Lag: 0.45 seconds    ::    FPS: 25
4000 Sprites    ::    Start Lag: 1.4 seconds    ::    FPS: 17

TweenLite는 filter에 관련된 기능들은 TweenFilterLite로 따로 빠져있다. 특별한 기능이 아닌 오브젝트의 모션 처리는 x,y,scaleX, scaleY, width, height, alpha 등과 추가하면 color 적용일 것이다. TweenLite는 tint 속성으로 그것을 대신하고 있다. 기본적인 사용법은 아래와 같다.

import gs.TweenLite;
TweenLite.to(mc, 1, {x:46, y:43, scaleX:1, scaleY:1, rotation:0, alpha:1, tint:0x3399ff});

사용법이 Tweener와 많은 부분 흡사하다. mc는 타겟이되는 Object, 1은 모션 time이고 {} 오브젝트 형태로 적용 속성들과 모션 함수를 적용할 수가 있다. ease 속성으로 모션 함수를 적용할 수가 있는데 함수는 fl.motion.easing 패키지 안에 있는 함수를 적용하게 되므로 fl.motion.easing 패키지를 import 시켜서 사용하면 된다. 그리고 Tweener에서와 같이 onStart, onUpdate, onComplete 를 지원한다. 아래 예,

        import gs.TweenLite;
        import fl.motion.easing.Back;
        TweenLite.to(mc, 5, {alpha:0.5, x:120, ease:Back.easeOut, delay:2,
                                        onComplete:onFinishTween, onCompleteParams:[5, clip_mc]});
        function onFinishTween(argument1:Number, argument2:MovieClip):void {
                trace("The tween has finished! argument1 = " + argument1 + ",
                and argument2 = " + argument2);
        }

[Flash] http://www.greensock.com/ActionScript/TweenLiteAS3/TweenLiteAS3_Sample_1.swf



USAGE

TweenLite.to(target:Object, duration:Number, variables:Object);

  • Description: Tweens the target's properties from whatever they are at the time you call the method to whatever you define in the variables parameter.
  • Parameters:
    1. target: Target MovieClip (or any object) whose properties we're tweening
    2. duration: Duration (in seconds) of the tween
    3. variables: An object containing the end values of all the properties you'd like to have tweened (or if you're using the TweenLite.from() method, these variables would define the BEGINNING values). Putting quotes around values will make the tween relative to the current value. For example, x:"-20" will tween x to whatever it currently is minus 20 whereas x:-20 will tween x to exactly -20. Here are some examples of properties you might include:
      • alpha: The alpha (opacity level) that the target object should finish at (or begin at if you're using TweenLite.from()). For example, if the target.alpha is 1 when this script is called, and you specify this parameter to be 0.5, it'll transition from 1 to 0.5.
      • x: To change a MovieClip's x position, just set this to the value you'd like the MovieClip to end up at (or begin at if you're using TweenLite.from()).

      Special Properties (**Optional**):

      • delay: The number of seconds you'd like to delay before the tween begins. This is very useful when sequencing tweens
      • ease: You can specify a function to use for the easing with this variable. For example, fl.motion.easing.Elastic.easeOut. The Default is Regular.easeOut.
      • easeParams: An array of extra parameter values to feed the easing equation. This can be useful when you use an equation like Elastic and want to control extra parameters like the amplitude and period. Most easing equations, however, don't require extra parameters so you won't need to pass in any easeParams.
      • autoAlpha: Same as changing the "alpha" property but with the additional feature of toggling the "visible" property to false if the alpha ends at 0. It will also toggle visible to true before the tween starts if the value of autoAlpha is greater than zero.
      • volume: To change a MovieClip's volume, just set this to the value you'd like the MovieClip to end up at (or begin at if you're using TweenLite.from()).
      • tint: To change a MovieClip's color, set this to the hex value of the color you'd like the MovieClip to end up at(or begin at if you're using TweenLite.from()). An example hex value would be 0xFF0000. If you'd like to remove the color from a MovieClip, just pass null as the value of tint. Before version 5.8, tint was called mcColor (which is now deprecated and will likely be removed at a later date although it still works)
      • onStart: If you'd like to call a function as soon as the tween begins, pass in a reference to it here. This can be useful when there's a delay and you want something to happen just as the tween begins.
      • onStartParams: An array of parameters to pass the onStart function.
      • onUpdate: If you'd like to call a function every time the property values are updated (on every frame during the time the tween is active), pass a reference to it here.
      • onUpdateParams: An array of parameters to pass the onUpdate function (this is optional)
      • onComplete: If you'd like to call a function when the tween has finished, use this.
      • onCompleteParams: An array of parameters to pass the onComplete function (this is optional)
      • overwrite: If you do NOT want the tween to automatically overwrite any other tweens that are affecting the same target, make sure this value is false.




TweenLite.from(target:Object, duration:Number, variables:Object);

  • Description: Exactly the same as TweenLite.to(), but instead of tweening the properties from where they're at currently to whatever you define, this tweens them the opposite way - from where you define TO where ever they are now (when the method is called). This is handy for when things are set up on the stage where the should end up and you just want to animate them into place.
  • Parameters: Same as TweenLite.to(). (see above)




TweenLite.delayedCall(delay:Number, onComplete:Function, onCompleteParams:Array);

  • Description: Provides an easy way to call any function after a specified number of seconds. Any number of parameters can be passed to that function when it's called too.
  • Parameters:
    1. delay: Number of seconds before the function should be called.
    2. onComplete: The function to call
    3. onCompleteParams [optional] An array of parameters to pass the onComplete function when it's called.




TweenLite.killTweensOf(target:Object, complete:Boolean);

  • Description: Provides an easy way to kill all tweens of a particular Object/MovieClip. You can optionally force it to immediately complete (which will also call the onComplete function if you defined one)
  • Parameters:
    1. target: Any/All tweens of this Object/MovieClip will be killed.
    2. complete: If true, the tweens for this object will immediately complete (go to the ending values and call the onComplete function if you defined one).




TweenLite.killDelayedCallsTo(function:Function);

  • Description: Provides an easy way to kill all delayed calls to a particular function (ones that were instantiated using the TweenLite.delayedCall() method).
  • Parameters:
    1. function: Any/All delayed calls to this function will be killed.


EXAMPLES


As a simple example, you could tween the alpha to 50% (0.5) and move the x position of a MovieClip named "clip_mc" to 120 and fade the volume to 0 over the course of 1.5 seconds like so:
  1. import gs.TweenLite;
  2. TweenLite.to(clip_mc, 1.5, {alpha:0.5, x:120, volume:0});



If you want to get more advanced and tween the clip_mc MovieClip over 5 seconds, changing the alpha to 50% (0.5), the x coordinate to 120 using the Back.easeOut easing function, delay starting the whole tween by 2 seconds, and then call a function named "onFinishTween" when it has completed and pass in a few parameters to that function (a value of 5 and a reference to the clip_mc), you'd do so like:
  1. import gs.TweenLite;
  2. import fl.motion.easing.Back;
  3. TweenLite.to(clip_mc, 5, {alpha:0.5, x:120, ease:Back.easeOut, delay:2, onComplete:onFinishTween, onCompleteParams:[5, clip_mc]});
  4. function onFinishTween(parameter1_num:Number, parameter2_mc:MovieClip):void {
  5.     trace("The tween has finished! parameters: " + parameter1_num + ", and " + parameter2_mc);
  6. }


If you have a MovieClip on the stage that is already in its end position and you just want to animate it into place over 5 seconds (drop it into place by changing its y property to 100 pixels higher on the screen and dropping it from there), you could:
  1. import gs.TweenLite;
  2. import fl.motion.easing.Elastic;
  3. TweenLite.from(clip_mc, 5, {y:"-100", ease:Elastic.easeOut});

FAQ

  1. Can I set up a sequence of tweens so that they occur one after the other?
    Of course! Just use the delay property and make sure you set the overwrite property to false (otherwise tweens of the same object will always overwrite each other to avoid conflicts). Here's an example where we colorize a MovieClip red over the course of 2 seconds, and then move it to a _y coordinate of 300 over the course of 1 second:
    1. import gs.TweenLite;
    2. TweenLite.to(clip_mc, 2, {tint:0xFF0000});
    3. TweenLite.to(clip_mc, 1, {y:300, delay:2, overwrite:false});

  2. Do the properties have to be in a specific order?
    Nope. The only thing that matters is that the first parameter is the object you're tweening, the second parameter is the time (in seconds), and the third parameter contains all the properties you want to tween (in any order). So TweenLite.to(clip_mc, 1, {scaleX:120, y:200, x:1}) is the same as TweenLite.to(clip_mc, 1, {x:1, y:200, scaleX:120});

  3. Why are TweenLite and TweenFilterLite split into 2 classes instead of building all the functionality into one class?
    1. File size. Only a portion of projects out there require tweening of filters. Almost every project I work on uses TweenLite, but only a few require tweening filters (TweenFilterLite). TweenLite is 2k whereas TweenFilterLite is 5k. Again, one of the stated purposes of TweenLite is to minimize file size & code bloat. If someone only wants to use TweenFilterLite, fine. But I think many people appreciate being able to use the most lightweight option for their needs and shave off the 3k when possible.
    2. Speed. Tweening filters is a more complex task. There are additional if/else statements and calculations in the rendering loop inside TweenFilterLite which could potentially slow things down a bit, even for non-filter tweens (I doubt anyone would notice a difference unless they’re running hundreds or thousands of simultaneous tweens, but I’m a big fan of keeping things as efficient & fast as possible)

  4. Do I have to pay for a license to use this code? Can I use it for commercial purposes?
    Feel free to take the code and use it as you wish, even for commercial purposes. Some people have requested the ability to donate money to reward the work I put into the class(es), so i put a PayPal "donate now" button at the top and bottom of the page, but you certainly don't need to donate anything. I'm just glad to help the Flash community.

  5. Are TweenLite and TweenFilterLite better than Tweener, Fuse, MC Tween, and all the other tweening engines out there?
    Maybe, maybe not. It all depends on your objectives, coding style, etc. I certainly don't claim that TweenLite & TweenFilterLite are superior to all other tweening engines, but in terms of the power-to-file-size ratio, I certainly haven't seen anything that comes close. Feedback has been overwhelmingly positive. I've used TweenLite for many years and it hasn't let me down. I never found myself needing features that are available in another tweening engine. But hey, to each his own.

[Flash] http://www.greensock.com/ActionScript/TweenFilterLiteAS3/TweenFilterLiteAS3_Sample.swf



OBJECTIVES

  • Minimize file size
  • Maximize flexibility and efficiency by extending the TweenLite class. That way, if you don't need to tween filters, you can just use TweenLite (about 2k); otherwise, this class will only add another 3k (5k total)
  • Minimize the amount of code required to initiate a tween
  • Maximize performance
  • Allow for very flexible callbacks (onComplete, onUpdate, onStart, all with the ability to pass any number of parameters)

FITLERS & PROPERTIES:

  • type:"Blur" -
    blurX, blurY, quality
  • type:"Glow" -
    alpha, blurX, blurY, color, strength, quality
  • type:"Color" -
    colorize, amount, contrast, brightness, saturation, hue, threshold, relative
  • type:"DropShadow" -
    alpha, angle, blurX, blurY, color, distance, strength, quality
  • type:"Bevel" -
    angle, blurX, blurY, distance, highlightAlpha, highlightColor, shadowAlpha, shadowColor, strength, quality

USAGE

TweenFilterLite.to(target:DisplayObject, duration:Number, variables:Object);

  • Description: Tweens the target's properties from whatever they are at the time you call the method to whatever you define in the variables parameter.
  • Parameters:
    1. target: Target DisplayObject whose properties we're tweening
    2. duration: Duration (in seconds) of the tween
    3. variables: An object containing the end values of all the properties you'd like to have tweened (or if you're using the TweenFilterLite.from() method, these variables would define the BEGINNING values). Putting quotes around values will make the tween relative to the current value. For example, x:"-20" will tween x to whatever it currently is minus 20 whereas x:-20 will tween x to exactly -20. Here are some examples of properties you might include:
      • blurX
      • blurY
      • color: An example for red would be 0xFF0000. Several filters use this property, like DropShadow and Glow
      • colorize: Only used with a type:"Color" tween to colorize an entire MovieClip.
      • amount: Only used to control the amount of colorization.

      Special Properties:

      • type: REQUIRED. A string that indicates what type of filter you're tweening. Possible values are: "Color" (for all image effects like colorize, brightness, contrast, saturation, and threshold), "Blur", "Glow", "DropShadow", or "Bevel"
      • delay: Number of seconds to delay before the tween begins. This can be very useful when sequencing tweens.
      • ease: You can specify a function to use for the easing with this variable. For example, fl.motion.easing.Elastic.easeOut. The Default is Regular.easeOut.
      • easeParams: An array of extra parameter values to feed the easing equation. This can be useful when you use an equation like Elastic and want to control extra parameters like the amplitude and period. Most easing equations, however, don't require extra parameters so you won't need to pass in any easeParams.
      • autoAlpha: Same as changing the "alpha" property but with the additional feature of toggling the "visible" property to false if the alpha ends at 0. It will also toggle visible to true before the tween starts if the value of autoAlpha is greater than zero.
      • volume: To change a MovieClip's volume, just set this to the value you'd like the MovieClip to end up at (or begin at if you're using TweenFilterLite.from()).
      • tint:To change a MovieClip's color, set this to the hex value of the color you'd like the MovieClip to end up at(or begin at if you're using TweenLite.from()). An example hex value would be 0xFF0000. If you'd like to remove the color from a MovieClip, just pass null as the value of tint. Before version 5.8, tint was called mcColor (which is now deprecated and will likely be removed at a later date although it still works)
      • onStart: If you'd like to call a function as soon as the tween begins, pass in a reference to it here. This can be useful when there's a delay and you want something to happen just as the tween begins.
      • onStartParams: An array of parameters to pass the onStart function.
      • onUpdate: If you'd like to call a function every time the property values are updated (on every frame during the time the tween is active), pass a reference to it here.
      • onUpdateParams: An array of parameters to pass the onUpdate function (this is optional)
      • onComplete: If you'd like to call a function when the tween has finished, use this.
      • onCompleteParams: An array of parameters to pass the onComplete function (this is optional)
      • overwrite: If you do NOT want the tween to automatically overwrite any other tweens that are affecting the same target, make sure this value is false.



TweenFilterLite.from(target:DisplayObject, duration:Number, variables:Object);

  • Description: Exactly the same as TweenFilterLite.to(), but instead of tweening the properties from where they're at currently to whatever you define, this tweens them the opposite way - from where you define TO where ever they are now (when the method is called). This is handy for when things are set up on the stage the way the should end up and you just want to tween them to where they are.
  • Parameters: Same as TweenFilterLite.to(). (see above)



TweenLite.delayedCall(delay:Number, onComplete:Function, onCompleteParams:Array);

  • Description: Provides an easy way to call any function after a specified number of seconds. Any number of parameters can be passed to that function when it's called too.
  • Parameters:
    1. delay: Number of seconds before the function should be called.
    2. onComplete: The function to call
    3. onCompleteParams [optional] An array of parameters to pass the onComplete function when it's called.




TweenFilterLite.killTweensOf(target:Object, complete:Boolean);

  • Description: Provides an easy way to kill all tweens of a particular Object/MovieClip. You can optionally force it to immediately complete (which will also call the onComplete function if you defined one)
  • Parameters:
    1. target: Any/All tweens of this Object/MovieClip will be killed.
    2. complete: If true, the tweens for this object will immediately complete (go to the ending values and call the onComplete function if you defined one).




TweenFilterLite.killDelayedCallsTo(function:Function);

  • Description: Provides an easy way to kill all delayed calls to a particular function (ones that were instantiated using the TweenFilterLite.delayedCall() method).
  • Parameters:
    1. function: Any/All delayed calls to this function will be killed.


EXAMPLES

As a simple example, you could tween the blur of clip_mc from where it's at now to 20 over the course of 1.5 seconds by:
  1. import gs.TweenFilterLite;
  2. TweenFilterLite.to(clip_mc, 1.5, {type:"Blur", blurX:20, blurY:20});

If you want to get more advanced and tween the clip_mc MovieClip over 5 seconds, changing the saturation to 0, delay starting the whole tween by 2 seconds, and then call a function named "onFinishTween" when it has completed and pass in a few arguments to that function (a value of 5 and a reference to the clip_mc), you'd do so like:
  1. import gs.TweenFilterLite;
  2. import fl.motion.easing.Back;
  3. TweenFilterLite.to(clip_mc, 5, {type:"Color", saturation:0, delay:2, onComplete:onFinishTween, onCompleteParams:[5, clip_mc]});
  4. function onFinishTween(argument1_num:Number, argument2_mc:MovieClip):void {
  5.     trace("The tween has finished! argument1_num = " + argument1_num + ", and argument2_mc = " + argument2_mc);
  6. }
If you have a MovieClip on the stage that already has the properties you'd like to end at, and you'd like to start with a colorized version (red: 0xFF0000) and tween to the current properties, you could:
  1. import gs.TweenFilterLite;
  2. TweenFilterLite.from(clip_mc, 5, {type:"color", colorize:0xFF0000});

FAQ

  1. Can I set up a sequence of tweens so that they occur one after the other?
    Of course! Just use the delay property and make sure you set the overwrite property to false (otherwise tweens of the same object will always overwrite each other to avoid conflicts). Here's an example where we colorize a MovieClip red over the course of 2 seconds, and then blur it over the course of 1 second:
    1. import gs.TweenFilterLite;
    2. TweenFilterLite.to(clip_mc, 2, {type:"color", colorize:0xFF0000, amount:1});
    3. TweenFilterLite.to(clip_mc, 1, {type:"blur", blurX:20, blurY:20, delay:2, overwrite:false});

  2. Do the properties have to be in a specific order?
    Nope. The only thing that matters is that the first parameter is the object you're tweening, the second parameter is the time (in seconds), and the third parameter contains all the properties you want to tween (in any order). So TweenFilterLite.to(clip_mc, 1, {type:"color", colorize:0xFF0000, amount:1}) is the same as TweenFilterLite.to(clip_mc, 1, {amount:1, colorize:0xFF0000, type:"color"});

  3. Can I use TweenFilterLite to tween things other than filters?
    Sure. It extends TweenLite, so you can tween any property you want. TweenFilterLite.to(my_mc, 1, {x:200}) gives you the same result as TweenLite.to(my_mc, 1, {x:200}). However, I'd recommend using TweenLite to tween properties other than filters for two reasons:
    1. In order to accommodate the specialized nature of filters, TweenFilterLite's code is a bit lengthier which translates into more work for the processor. It's doubtful that anyone would notice a performance hit unless you're tweening hundreds or thousands of instances simultaneously, but I'm a bit of an efficiency freak.
    2. TweenLite can tween any property of ANY object whereas TweenFilterLite tweens properties of DisplayObjects (like MovieClips, Sprites, etc.)

  4. Why are TweenLite and TweenFilterLite split into 2 classes instead of building all the functionality into one class?
    1. File size. Only a portion of projects out there require tweening of filters. Almost every project I work on uses TweenLite, but only a few require tweening filters (TweenFilterLite). TweenLite is 2k whereas TweenFilterLite is 5k. Again, one of the stated purposes of TweenLite is to minimize file size & code bloat. If someone only wants to use TweenFilterLite, fine. But I think many people appreciate being able to use the most lightweight option for their needs and shave off the 3k when possible.
    2. Speed. Tweening filters is a more complex task. There are additional if/else statements and calculations in the rendering loop inside TweenFilterLite which could potentially slow things down a bit, even for non-filter tweens (I doubt anyone would notice a difference unless they’re running hundreds or thousands of simultaneous tweens, but I’m a big fan of keeping things as efficient & fast as possible)

  5. Do I have to pay for a license to use this code? Can I use it for commercial purposes?
    Feel free to take the code and use it as you wish, even for commercial purposes. Some people have requested the ability to donate money to reward the work I put into the class(es), so i put a PayPal "donate now" button at the top and bottom of the page, but you certainly don't need to donate anything. I'm just glad to help the Flash community.

  6. Are TweenLite and TweenFilterLite better than Tweener, Fuse, MC Tween, and all the other tweening engines out there?
    Maybe, maybe not. It all depends on your objectives, coding style, etc. I certainly don't claim that TweenLite & TweenFilterLite are superior to all other tweening engines, but in terms of the power-to-file-size ratio, I certainly haven't seen anything that comes close. Feedback has been overwhelmingly positive. I've used TweenLite for many years and it has never let me down. I've never found myself needing features that are available in another tweening engine. But hey, to each his own.
    

설정

트랙백

댓글

[AS3] Linkage 클래스를 필요할때 참조

Programming/ActionScript 3.0 2008. 1. 29. 18:09

















public function getDefinitionByName(name:String):Object

플래시에서의 Public 함수 중에서 getDefinitionByName() 함수는 name 매개 변수로 지정된 클래스의 클래스 객체에 대한 참조를 반환해 준다.

var c:Class = getDefinitionByName("m"+2) as Class;  // 라이브러리에 있는 Linkage 클래스명 "m2"의 참조를 반환한다.

package {
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.utils.getDefinitionByName;

public class GetDefinitionByNameExample extends Sprite {
private var bgColor:uint = 0xFFCC00;
private var size:uint = 80;

public function GetDefinitionByNameExample() {
var ClassReference:Class = getDefinitionByName("
flash.display.Sprite") as Class;
var instance:Object = new ClassReference();
instance.graphics.beginFill(bgColor);
instance.graphics.drawRect(0, 0, size, size);
instance.graphics.endFill();
addChild(DisplayObject(instance));
}
}
}

    

설정

트랙백

댓글

[AS3] getTileColor 메소드를 이용한 이미지

Programming/ActionScript 3.0 2008. 1. 28. 19:11
BitmapData의 일정한 간격의 pixel 컬러를 추축하는 메소드를 작성하고 이미지를 뽑아 보았다. 땡굴이 형님도 비슷한 작업을 진행중인 듯 싶다. 원본 이미지의 사이즈와 상관없이 16x16픽셀 아이콘도 이러한 확대한 결과물을 만들 수 있어서 여러가지로 사용할 수 있을 듯 싶다.

랜덤한 형태에서 좀더 관련이 있는 부분들을 조합하면 불규칙적이지만 규칙이 있는 재질을 만들어 낼 수 있을 듯 싶다.









사용자 삽입 이미지

    

설정

트랙백

댓글

Flickr API UML - as3flickrlib

Programming/ActionScript 3.0 2008. 1. 28. 14:57

Project Page: http://code.google.com/p/as3flickrlib/
Project Group: http://groups.google.com/group/as3flickrlib

위 구글 코드에서 오픈되어 있는 flickr API adobe 소스를 UML로 변환해 보았다. 필요하신 분들은 참고하시면 좋을 듯 싶다. 기본적인 상속과 합성관계만 형성해 놓은 상태, 대부분 합성으로 페키지가 구성되어 있다.

참고. 새벽에 작성한 관계로 틀린 부분이 있을 수 있음.










사용자 삽입 이미지

    

설정

트랙백

댓글

Wise를 확장한 SimpleFanwise, SimpleArchwise 클래스 응용

Programming/ActionScript 3.0 2008. 1. 23. 13:53
예전에 만들었던 호 그리는 클래스를 응용하여 부채꼴, 활꼴 모양을 그리는 Shape를 만들고 응용해보았다.
아래 CREATE 버튼을 클릭하면 왼쪽은 SimpleFanwise를 이용한 것이고 오른쪽은 SimpleArchwise를 이용하여 20개 오브젝트 생성후 사라지는 모션을 적용해 봤다.














    

설정

트랙백

댓글

[AS3] CurveMotion

Project/Programming 2008. 1. 18. 17:49
기존에 만들었던 라인 모션 클래스에서 생성된 이후 모션처리기능을 추가하였다.















    

설정

트랙백

댓글

[AS3] Components

Project/Programming 2008. 1. 17. 13:09
Keith Peters가 만들었던 미니컴포넌트를 Event형태로 변형하고 기능적인 요소들을 추가해 보았다. 기존의 RadioButton의 경우 static array에 등록하고 사용을 하게 만들었는데 한 플렛폼에서 여러 개의 그룹 RadioButton이 있을 수 있어서 RadioButtonContainer로 생성한 인스턴스를 통해서 그룹핑 하도록 하고 RadioButtonContainer.addEventListener(ComponentMouseEvent.MOUSE_DOWN, handler)를 통해서 클릭한 RadioButton을 evt.data로 넘겨 받도록 하였다.

기본 Style 클래스 내에서 컴포넌트 스킨을 적용하고 모든 컴포넌트 스킨 일괄 적용을 위해서 Component 클래스의 setStyle를 override 하도록 하였다.

심플한 Display 형태와 구조이지만 컴포넌트를 통해서 구조적 접근 방법을 좀더 다양화 할 수 있지 않을까 싶어서 만들어 보았다.





사용자 삽입 이미지


    

설정

트랙백

댓글

[AS3] private, protected, internal, public을 어떻게 결정하면 좋은가

Programming/ActionScript 3.0 2007. 12. 31. 03:07
AS3의 private, protected, internal, public을 어떻게 결정하면 좋은가

일본의 ASer의 포스트을 보고 나를 포함한 많은 플래시 작업자들이 개념적으로는 이해 하고 있지만 실전에서 흐지부지 하게되는 것을 지양하기 위해서 그 분의 포스트을 토대로 접근자들을  정리해 본다.

각 접근자의 개념은 아래와 같다.

내부 이용자(자기 자신)               -> private
계승이용자(서브 클래스)             -> protected
외부 이용자(동일 패키지의 제삼자) -> internal
외부 이용자(다른 패키지의 제삼자) -> public
 




이하에 패키지 A_package의 클래스 A_class를 예로 들어 아래와 같을 경우, A_package 패키지 내에서는 모두 접근이 가능하다.
package A_package {
public class A_class {

private var p1:uint;
protected var p2:uint;
internal var p3:uint;
public var p4:uint;

public function A_class() {

p1 = 1; // OK
p2 = 2; // OK
p3 = 3; // OK
p4 = 4; // OK

}
}
}
동일 패키지의 상속 클래스는 private를 제외한 속성들에 접근이 가능하다.
package A_package {
public class B_class extends A_class {

public function B_class() {

v1 = 1; // error
v2 = 2; // OK
v3 = 3; // OK
v4 = 4; // OK

}
}
}
동일 패키지의 다른 클래스는 protected 속성에 액세스할 수 없지만 internal에는 액세스할 수 있다.
package A_package {
public class C_class {

public function C_class() {

var a:A_class = new A_class();

a.v1 = 1; // error
a.v2 = 2; // error
a.v3 = 3; // OK
a.v4 = 4; // OK

}
}
}
다른 패키지의 상속 클래스에서는 protected에는 액세스할 수 있지만 internal에는 액세스할 수 없다.
package B_package {

import A_package.A_class;

public class D_class extends A_class {

public function D_class() {

v1 = 1; // error
v2 = 2; // OK
v3 = 3; // error
v4 = 4; // OK

}
}
}
다른 패키지의 다른 클래스에서는 public밖에 액세스할 수 없다.
package B_package {

import A_package.A_class;

public class E_class {

public function E_class() {

var a:A_class = new A_class();

a.v1 = 1; // error
a.v2 = 2; // error
a.v3 = 3; // error
a.v4 = 4; // OK

}
}
}
예전에는 이런 구분 자체가 내 머리속을 어지럽게 하여 private와 public만을 사용했었다. AS3로 넘어오면서 상속, 합성, 오버라이드를 이용한 작업이 늘어나면서 유기적인 클래스들과의 관계 중심으로 구조를 설계하다보니 클래스 간에 접근 규정을 코멘트로 달아놓지 않는 한 스스로 혼란스럽게 되었다. 보통 private로 해두고 protected→internal→public 방향으로 작업을 하면 되겠으나 이것 또한 중간중간 에러체크를 감당해야 하는 부담을 지울 수가 없다.

확실히 private, protected, internal, public을 구분해서 작업 하는 것이 현재 작업자에게도 큰 도움이 된다. 가장 바람직한 방법으로는 작은 프로젝트라도 작업에 들어가기 전에 구조를 설계하고 노트에 UML 비스무리한 낙서를 하고 시작하는 것이 좋을 것 같다.

 

    

설정

트랙백

댓글

[AS3] CurvePointMotion

Project/Programming 2007. 11. 30. 00:55
    

설정

트랙백

댓글