Study/Actionscript 3.02010. 1. 19. 15:35
출처
http://love2motion.tistory.com/entry/ActionScript-3-Tip-%EB%AA%A8%EC%9D%8C


ActionScript 3 is the next step forward in Flash scripting and to help with the transition (for those of you deciding to make it), I thought I'd make a new Tip of the Day thread for ActionScript 3.0 to help people prepare (after 100 tips, they will no longer be provided daily).

Note: Many of these tips were created prior to the release of Flash and pertain to AS-only projects. Others were for use with the Alpha version of Flash (released prior to the full release of Flash). Most of these are noted as being for "Flash 9". Though much has changed in Flash CS3, most of those tips should still apply to it as well.

To code AS3, you'll need one of the following:

ActionScript 3 Tips and Tricks:

Latest Additions
(All categories are ordered from oldest (top) to newest (bottom))
General
Language Elements/Behavior and Syntax
New Classes
Regular Expressions
Proxy Class
XML
Events
Errors and Error Handling
Display Objects (MovieClips)
Flash Authoring

Additional Resources:
Samples:
Posted by chacolina
Study/Actionscript 3.02010. 1. 19. 15:03
출처
http://www.adobe.com/kr/devnet/flashplayer/articles/garbage_collection.html#



Flash Player 9에서의 가비지 컬렉션 이해

Grant Skinner

Grant Skinner

CEO 겸 아키텍트 부문 책임자
gskinner.com*

작성일:
2007년 4월 9일
사용자 수준:
고급

한동안 ActionScript 3.0을 사용해본 결과 필자는 이제 그 기능에 완전히 매료되었습니다. 자체의 순수한 실행속도만으로도 많은 가능성을 제공합니다. E4X, 소켓, 바이트 배열, 새 디스플레이 목록 모델, RegEx 메서드, 형식화된이벤트 및 오류 모델, 기타 훌륭한 여러 기능을 맘껏 사용하며 상당히 흥미로운 혼합 툴을 만끽할 수 있습니다.

강한 힘에는 그만큼의 책임이 따른다는 말은 ActionScript 3.0에 딱 어울리는 말입니다. 완전히 새로워진 이컨트롤의 단점이 있다면 그것은 가비지 수집기가 언제 자동 정돈을 수행할지를 더 이상 예측할 수 없다는 것입니다. 즉,ActionScript 3.0을 사용하는 Flash 개발자는 가비지 수집기의 작동 방식과 효과적인 사용 방법에 대해 매우 잘알고 있어야 한다는 뜻입니다. 이러한 지식이 없으면 단순한 게임이나 애플리케이션을 만들더라도 마치 여과기처럼 모두 새나가는SWF가 만들어져 모든 시스템 리소스(CPU/RAM)를 독차지하고 시스템 오류, 심지어 컴퓨터를 강제로 다시 부팅해야 하는상황이 발생할 수 있습니다.

ActionScript 3.0에 맞게 코드를 최적화하는 방법을 이해하려면 우선 Flash Player 9에서 가비지수집기가 작동하는 방식을 이해해야 합니다. Flash에는 사용되지 않는 객체를 찾고 이를 제거하는 두 개의 프로세스가 있습니다.본 기술문서에서는 이 두 가지 기법에 대해 살펴보고 이들이 코드와 어떤 관계가 있는지에 대해 설명합니다.

본 기술문서 끝부분에서는 여기서 설명한 개념을 실제로 보여주는 Flash Player 9의 가비지 수집기 시뮬레이션이 제공됩니다.

가비지 수집기

가비지 수집기는 애플리케이션에서 더 이상 사용하지 않지만 객체에서 사용하고 있는 메모리의 할당을 해제하는 역할을 담당하는,배후에서 작동하는 프로세스입니다. 비활성 객체란 자신을 참조하는 기타 활성 객체가 없는 객체를 말합니다. 이를 이해하려면 기본유형이 아닌 유형(Boolean, String, Number, uint, int 이외의 유형)으로 작업할 때 항상 객체에 객체자체가 아니라 참조를 전달한다는 것을 깨닫는 것이 중요합니다. 변수를 삭제하면 객체 자체가 아니라 참조가 제거되는 것입니다.

다음 코드를 보면 이것을 쉽게 이해할 수 있습니다.

// create a new object, and put a reference to it in a:
var a:Object = {foo:"bar"}
// copy the reference to the object into b:
var b:Object = a;
// delete the reference to the object in a:
delete(a);
// check to see that the object is still referenced by b:
trace(b.foo); // traces "bar", so the object still exists.

위의 예제에서 코드를 업데이트하고 동시에 "b"를 삭제한다면 객체의 활성 참조가 없어져서 가비지 컬렉션용으로 비워지게됩니다. ActionScript 3.0 가비지 수집기는 활성 참조가 없는 객체를 찾기 위해 두 가지 방법, 즉 참조횟수(reference counting) 및 표시 회수(mark sweeping)를 사용합니다.

참조 횟수

참조 횟수는 활성 객체를 추적하는 가장 간단한 방법 중 하나이며 ActionScript 1.0부터 Flash에서사용되었습니다. 객체에 대한 참조를 만들면 참조 횟수가 증가합니다. 참조를 삭제하면 참조 횟수가 감소합니다. 객체의 참조 횟수가0이 되면 가비지 수집기에 의해 삭제됩니다.

예를 들면 다음과 같습니다.

var a:Object = {foo:"bar"}
// the object now has a reference count of 1 (a)
var b:Object = a;
// now it has a reference count of 2 (a & b)
delete(a);
// back to 1 (b)
delete(b);
// the reference count down is now 0
// the object can now be deallocated by the garbage collector

참조 횟수는 단순하면서 CPU 오버헤드를 크게 높이지 않기 때문에 대부분의 상황에 적합합니다. 그러나 순환 참조의 경우에는참조 횟수가 가비지 컬렉션을 위한 최적의 방법이 아닙니다. 순환 참조란 객체가 서로를 교차 참조하는 상황을 말합니다(다른 객체를통해 직접 또는 간접적으로). 애플리케이션이 해당 객체를 더 이상 사용하지 않더라도 참조 횟수가 0보다 큰 상태로 유지되므로가비지 수집기가 해당 객체를 제거하지 않습니다. 다음 코드는 이러한 경우를 보여줍니다.

var a:Object = {}
// create a second object, and reference the first object:
var b:Object = {foo:a};
// make the first object reference the second as well:
a.foo = b;
// delete both active application references:
delete(a);
delete(b);

위 코드에서는 활성 애플리케이션 참조 두 개가 모두 삭제되었습니다. 이제 애플리케이션에서는 이 두 객체에 전혀 액세스하지 않지만 두 객체는 서로를 참조하므로 참조 횟수가 1입니다. 이러한 상황은 훨씬 더 복잡해질 수 있으며(ac를 참조하고, c는 b를 참조하고, 또 b는 a를참조하는 등) 코드에서 다루기 힘들어질 수 있습니다. Flash Player 6과 7에는 XML 객체의 순환 참조와 관련된문제가 있었습니다. 자식과 부모 모두를 참조하는 각 XML 노드가 있어 이들의 할당이 해제되지 않는 문제였습니다. 다행히도Flash Player 8에는 표시(mark) 및 회수(sweep)라는 새로운 가비지 컬렉션 기법이 추가되었습니다.

표시-회수

ActionScript 3.0(및 Flash Player 8) 가비지 수집기에서 비활성 객체를 찾기 위해 사용되는 두 번째전략은 표시 및 회수라는 방법입니다. Flash Player는 애플리케이션의 루트 객체에서 시작하여(ActionScript3.0에서는 편리하게 "루트"라고 함) 그 내부의 모든 참조를 거치면서 발견되는 모든 객체를 표시합니다.

그런 다음 Flash Player는 표시된 각 객체를 반복합니다. Flash Player는 애플리케이션의 전체 객체 트리를검토할 때까지 이 동작을 재귀적으로 계속 수행하며, 활성 참조를 통해 도달할 수 있는 모든 것을 표시합니다. 이 프로세스가끝나면 Flash Player는 메모리에 있으면서 표시되지 않은 모든 객체는 더 이상 활성 참조가 없으므로 안전하게 할당 해제할수 있다고 가정할 수 있습니다. 그림 1은 이것의 작동 방식을 보여줍니다. 녹색 참조는 표시하는 동안 Flash Player를따라온 것이고, 녹색 객체는 표시된 것이고, 흰색 객체는 할당 해제될 것입니다.

Flash Player에서 표시 및 회수 방법을 통해 활성 참조가 없는 객체 식별

그림 1. Flash Player에서 표시 및 회수 방법을 통해 활성 참조가 없는 객체 식별

표시 및 회수는 매우 정확합니다. 그러나 Flash Player가 전체 객체 구조를 검토해야 하므로 CPU 사용 관점에서볼 때 이 프로세스에는 비용이 많이 듭니다. Flash Player 9에서는 표시 및 회수를 반복적으로 수행하고(동시에 모든프레임이 아니라 여러 프레임씩 나누어 프로세스 진행) 이 프로세스를 가끔 실행함으로써 이 비용을 줄입니다.

가비지 수집기의 지연 및 불확정성

Flash Player 9에서는 가비지 수집기의 작동이 지연됩니다. 이것은 매우 중요한 개념으로서 반드시 이해해야 합니다.모든 활성 참조가 삭제되더라도 객체가 즉시 제거되지 않고, 향후 불확정적인 시간에 제거됩니다(개발자 관점에서 볼 때). 가비지수집기는 일련의 추론을 사용하고 무엇보다도 RAM 할당 및 메모리 스택의 크기를 관찰하여 실행 시기를 결정합니다. 개발자입장에서는 비활성 객체가 언제 할당 해제될지 알 수 없다는 사실을 받아들여야 합니다. 또한 가비지 수집기가 비활성 객체의 할당을해제할 때까지 비활성 객체가 계속해서 실행될 수 있다는 점을 인식해야 합니다. 따라서 할당이 해제되기 전에는 코드도 계속실행되고(enterFrame 이벤트가 계속 발생), 사운드도 계속 재생되고, 로드도 계속 발생하며, 기타 이벤트도 계속 일어나게됩니다.

Flash Player의 가비지 수집기가 객체의 할당을 해제하는 시기를 개발자가 전혀 제어할 수 없다는 사실을 기억하는것이 매우 중요합니다. 개발자라면 게임과 애플리케이션을 완료할 때 그곳의 객체를 최대한 자신이 원하는 대로 제어하고 싶을것입니다. 이러한 프로세스의 관리 전략은 필자의 동료가 작성한 Flash Player 9의 리소스 관리 전략 기술문서에 소개되어 있습니다.

다음 가비지 컬렉션 시뮬레이션에서 전체 메모리의 톱니 모양을 살펴보십시오(그림 2 또는 아래 링크 클릭). 수집기가 회수를수행할 때 하강이 발생합니다. 차트를 자세히 보려면 클릭하십시오. 일시 중지하거나 다시 시작하려면 스페이스바를 누르고, 실행되는동안 메모리 사용 추세를 변경하려면 위/아래 화살표를 누르십시오.

가비지 컬렉션 시뮬레이션

그림 2. 가비지 컬렉션 시뮬레이션

다음 시뮬레이션에서는(그림 3 또는 아래 링크 클릭) 객체(둥근 직사각형) 및 객체에 대한 참조를 드래그하십시오. 그런다음 참조 횟수 또는 표시 및 회수를 실행하여 어떤 객체가 수집되는지 살펴보십시오. 객체에 있는 숫자는 해당 객체의 참조 횟수를나타냅니다.

가비지 컬렉션 시뮬레이션: 표시(mark) 및 회수(sweep)

그림 3.가비지 컬렉션 시뮬레이션: 표시(mark) 및 회수(sweep)

다음 단계로

가비지 컬렉션에 대한 이해는 Flash 프로젝트가 사용자의 컴퓨터에 최소한의 영향을 주며 실행될 수 있도록 보장하는 최적화된 코드를 작성하기 위한 가장 중요한 단계입니다. 필자의 동료가 작성한 기술문서, Flash Player 9의 리소스 관리 전략을 읽어보고 Flash 개발자 센터Flash Player 개발자 센터를 방문하십시오.

불충분한 참조에 대한 자세한 내용을 살펴보거나 필자가 작성한 보조 클래스를 다운로드하려면 필자의 블로그 gskinner.com을 방문하십시오.

저자 소개

Grant Skinner는 Flash 개발 및 컨설팅 업체인 gskinner.com*의CEO이자 아키텍트 부문의 책임자로 선도적인 신생 미디어 에이전시와 진취적인 기업 클라이언트와 함께 첨단 애플리케이션과 게임,멀티미디어 구성 요소를 제작하고 있습니다. 인터페이스 디자인, 유용성, 마케팅 및 비즈니스 로직에 코딩을 적용하는 전문성을 통해국제적인 명성을 얻고 있는 그는 FITC 2005의 Best Canadian Developer를 비롯하여 업계의 권위 있는 상을여러 번 수상했습니다. Grant는 gskinner.com/blog/*에서 블로그를 운영하며 incomplet.org*에 그의 실험적 작품을 전시하고 있습니다.


Posted by chacolina
Study/Actionscript 3.02010. 1. 19. 11:38
Study/Actionscript 3.02010. 1. 19. 11:15
2008/07/14 18:09 PAPERVISION3D/TIP
I. 3D in Flash

Adobe 가 Flash 를 인수하면서 새롭게 바뀐 것 중에 하나가 바로 ActionScript(AS) 이다. 이전 AS가 단순히 모션에 도움을 주는 Script 였다면 최근 AS3는 Language 에 더 가까워 지고 있는 것 같다. 이는 FLEX나 AIR를 통해 더욱 확실히 알 수 있다. 이런 변화를 통해 AS를 이전까지는 힘들게 여겨지던 기술들도 속속 AS3를 통해서 등장하고 있다. 그 중 하나가 플래쉬를 이용한 3D이다. 예전부터 이러한 시도는 꾸준히 있어왔는데 사실 AS2 의 한계로 실제 필드에서 사용하기에는 무리가 많았다. 하지만 최근 여러 3D라이브러리가 나오면서 불가능하게만 여겨지던 3D영역이 손쉽게 개발되고 있다.

현 재 널리 알려져 있는 라이브러리로는 Sandy3D, Papervision3D, Away3D 등이 있는데 각각 장단점이 있는 것 같으나 전부 속속들이 들여다 보지는 못해서 아직 정확한 성능의 차이나 사용상의 용이성등의 평가는 어렵다. 이번 글에서는 셋중 실제 홈페이지에 가장 많이 적용되고 있는 Papervision3D (PV3D)를 기준으로 작성하였다. PV3D는 실무에서도 많이 쓰이고 있을 뿐 아니라 개발 또 한 활발히 이뤄지고 있어 앞으로 더욱 기대되는 라이브러리 이다. 참고로 사용된 PV3D의 버전은 2.0a GreatWhite 이다.


II. Object Build Solution

이 번에 테스트 해본 오브젝트 생성 방법은 총 4가지 이다. 첫번째는 PV3D에 기본으로 있는 Object Class를 이용한 방법이고, 두번째는 AS3 Geom Class Exporter를 이용한 방법, 세번째는 DAE 파일을 PV3D의 기본 collada 클래스로 생성한 방법이고 마지막은 같은 DAE 파일을 ASCollada의 DAE 클래스로 생성한 방법이다.

1. 기본 내장 클래스
PV3D 는 기본적으로 org.papervision3d.objects 패키지에서 오브젝트를 선언하고 있다. 하위로 종류별로 parsers, primitives, spceial로 구분되며 이 구문에서는 primitives 안의 기본 오브젝트들로 생성하였다.

var cube:Cube = new Cube(materialList, 100, 100, 100);
var cone:Cone = new Cone(new WireframeMaterial(0xFF0000));
var sphere:Sphere = new Sphere(new WireframeMaterial(0xFF0000));

 
가 장 빠른 성능을 보이지만 기본으로 제공하는 이외의 형태를 만들지 못하기 때문에 UI 나 Navigation 이 외에는 활용성 면에서는 조금 부족하지 않나 싶다. 결국 사용자화된 오브젝트를 쓰기 위해서는 외부파일을 로드 해야만 한다.


2. AS3 Geom Class Exporter
사용자 삽입 이미지
이 는 3D MAX 에서 AS3 Geom Exporter라는 Max Script를 설치하여서 각 라이브러리 별 .as파일로 바로 export하는 방법이다. 이 방법 또한 각 라이브러리에 맞게 .as파일을 만들어 주기 때문에 성능면에서는 좋지만 이름에서 처럼 Geom 에 대한 데이터만 만들어 주기 때문에 위치나 맵핑에 관한 정보없이 단순한 오브젝트만 만들어 주는 것같다. 결국 애니메이션과 맵핑을 위해서 손이 한번 더 가야 한다.

test = new Test(new WireframeMaterial(0xFF0000));


3. Collada
collada 는 뒤에 좀 더 자세히 설명하겠지만 간단히 말해서 3D데이터를 표준 XML 로 만들어주는 프로젝트이다. 확장자는 .dae 를 사용한다. 이 방법은 PV3D에서 기본으로 지원하던 collada 클래스를 이용하는 방법이다.

collada = new Collada("test.DAE" , materialList);


4. DAE
이 방법은 위의 방법과 .dae 파일을 사용한다는 점에서 동일하나 .dae 파일을 파싱하는 클래스가 Collada 가 아닌 DAE 이다. 두 파일의 차이는 DAE는 ASCollada 프로젝트의 파일을 PV3D에 합친것으로 이는 PV3D 2.0a 이후 버전에 적용되었다. 또한 위의 방법과 결정적 차이는 .dae파일의 Animation 을 컨트롤 할 수 있다는 점이다.

dae = new DAE();
dae
.animate = true;
dae
.load("test.DAE", materialList);



III. Collada

collada의 정의를 홈페이지에서 보면 다음과 같이 규정하고 있다. 'COLLADA is an open digital-asset exchange schema for the interactive 3D industry' collada 에는 대부분의 3D 데이터가 저장되는데 특히 맵핑과 애니메이션이 매우 유용하다. 3D MAX 와 같은 프로그램에서 모델링과 맵핑을 하고 이를 collada로 export 한 후 PV3D 를 통해 Flash 에 바로 적용 할 수 있기 때문이다. 참고로 3D MAX 에서 collada 파일을 export 하기 위해서는 ColladaMax 같은 플러그인을 별도로 설치 해야한다.


IV. Example



위 에서 말한 4가지 방법으로 예제를 만들어 보았다. 아래 소스를 보면 알 수 있겠지만 똑같은 조건하에 오브젝트만 생성하고 있는데 생성되어지는 기본값이 조금씩 상이한 것을 알 수 있다. 특히 같은 .dae 파일을 사용하는 Collada 와  DAE 클래스의 다른 점을 눈여겨 볼 필요가 있을 것 같다.

전체 소스 보기



V. Results

사용자 삽입 이미지
위 의 결과표는 매우 주관적인 견해라는 것을 꼭 기억해주기 바란다. 기본클래스를 이용한 경우에도 따로 추가해주면 맵핑과 애니메이션이 가능하다. 또 한 COLLADA를 이용하는 클래스도 사용성이 꼭 나쁘다고 할 수는 없다. 다만 위의 표는 각 방법에 대한 차이를 좀더 쉽게 이해하기 위해서 만들었으니 차이에 대해 참고 정도의 역활이었으면 한다.

확실히 플래쉬에서 구현되는 3D는 많은 제약을 가지고 있다. 특히 하드웨어 가속을 받지 않기 때문에 성능이나 기능 면에서 현란한 3D게임 같은 화면을 기대 하는 것은 무리가 있다. 하지만 날로 좋아지는 컴퓨터의 성능과 AS3의 성능 향상으로 플래쉬에서 3D를 이용한 다양한 시도가 가능 할 것으로 기대 된다. 조만간 웹에서 Coverflow 와 같은 화려한 UI 나 스페셜포스 같은 FPS 게임을 경험하게 될 지도 모른다.


VI. Links

Papervision3D : http://pv3d.org/
Collada : http://www.collada.org/mediawiki/index.php/Main_Page
ColladaMax : http://www.feelingsoftware.com/content/view/65/79/lang,en/
AS3 Geom Exporter : http://seraf.mediabox.fr/showcase/as3-geom-class-exporter-for-3ds-max-english/
ASCollada : http://ascollada.org/
Posted by chacolina
Study/Actionscript 3.02010. 1. 14. 17:37
flash로 직접 데이터를 불러올 수도 있지만 동기식인 flash의 특성상 효율성이 떨어질 수 있다.
따라서 데이터 처리를 위한 파일을 따로 만들어 주고 그 정보를 flash에 넘기는 방식을 취하여
효율적인 데이터 처리를 할 수 있는데 그럴 경우 많이 쓰이는 것이 xml이다.

아래 링크는 기본 문법을 설명해 놓은 페이지이므로 참고하길 바란다.

http://help.adobe.com/ko_KR/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7e6b.html
Posted by chacolina
Study/Actionscript 3.02009. 12. 8. 14:09

출처 http://www.flashmagazine.com/Tutorials/detail/away3d_basics_the_cameras/

 

 

The camera is what you view the 3D world through. Just as a real camera, the virtual 3D camera applies perspective to your models by adjusting properties such as zoom, focus and position. In this tutorial you'll learn how to use the 3 cameras available in Away3D.

No matter what you want to do in Away3D, there's some things that you'll always need to set up. The "Basic" tutorials will explain the Scene, View, Camera, Primitives, Textures and explore some of the possibilities. Each example in the series will be organized as Actionscript Classes so they can be used in both Flash and Flex.

If you are new to 3D on computers, you might want to read our introduction that explains the core 3D concepts. This tutorial also contains the source for 6 other Away3D projects that may be worth checking out. To run the example files, you will first need toset up Away3D on your computer. When you have the Away3D source files and your software is set up, you can open, explore and export the examples in this tutorial by just placing them in your project directory. 3D is processor intensive, so all the examples use a file called Cover.as that you must also download to your project directory to be able to run the examples.

Away3D Cameras

Away3D offers 3 different cameras: Camera3D, TargetCamera3D and HoverCamera3D. All the cameras offer settings for zoom, focus, depth of field, pan, tilt and position.

All of these cameras have properties that can be set in the constructor like this:

 

 

<PRE>
1.var cam:Camera3D = new Camera3D({zoom:5,focus:200});
</PRE>

 

 

They can also be set or changed using the properties directly like this:

 

 

<PRE>
1.var cam:Camera3D = new Camera3D({zoom:5,focus:200});cam.zoom = 5;
2.cam.focus = 200;
</PRE>

 

 

If you have a SLR camera or even a simple camera that has a proper lens, you will know how the zoom works. The focus property on the other hand decides the focal length of the camera (angle of view). To try this out, take a look at this example:

movie: Camera.as

Here you can see that the focus works together with the zoom to decide how you view the Scene. Lower focus values will move the "rendering plane" closer to the camera. Higher values wil move it away from it. Tartiflop has written a great tutorial that explains zoom and focus settings for Papervision. For Away3D it's the same, so if you want to learn more, check it out.

 

<PRE>
1.cam.pan = 45;cam.tilt = -10;
</PRE>

 

Pan and Tilt will do as they say, they will rotate the camera around what it is looking at in either horisontal or vertical direction. You can set both positive and negative values. I initially  mentioned the Depth Of Field. When combined with 2D sprites, this can be used to create depth effects. We'll look closer at this in a later tutorial.

All these properties are all considered when rendering the View. The process of figuring out what triangles are visible though the View/Camera is called Culling. Calculating how something should look in 3D requires a lot of CPU and culling make sure only what is visible to the Camera is calculated.

The 3 cameras work a little differently, so here's a breakdown of each of them and how you use them.

Camera3D

Camera3D is the basic, free form camera. You can move and point it in any direction.

movie: Basic04Camera3D.as

Use the keys A, D, W, S and arrow up/down to navigate the 3D space. In this movie, we use a set of standard movement methods available to all Away3D objects:

 

 

<PRE>
1.camera.moveUp(10);camera.moveDown(10);camera.moveLeft(10);camera.moveRight(10);
2.camera.moveForward(10);camera.moveBackward(10);
</PRE>

 

 

These functions are pretty self explanatory. Note that a new Camera3D is by default positioned in the centre of the 3D world (0,0,0), meaning that if you add a Sphere you will not see anything since the camera is actually inside it. By default, a sphere is only viewable from the outside, so to see the sphere, we either have to invert the sphere ( sphere.invertFaces(); ) or move the camera outside the sphere by setting the cameras Z property like this:

 

 

<PRE>
1.camera.z = -1000;
</PRE>

 

 

Here we pull the camera back one thousand units, towards us. Setting the x/y/z properties of the camera will make it move, but remember that any camera must also point to a certain location. By default, the camera will look at the center coordinates of our 3D Scene. To point the camera somewhere else, we use the "lookAt" command:

 

 

<PRE>
1.camera.lookAt( new Number3D(x,y,z) );
</PRE>

 

 

This tells the camera to look at the coordinate x/y/z in our virtual 3D world. You can also make the camera Pan, Tilt and rotate along any of the three axes.

A word of warning about setting the x/y/z properties - make sure you always set the camera position before asking it to "lookAt" something. If you first "lookAt" something and then change the position, the camera will still be looking in the direction set initially. To solve this, always update your "lookAt" reference after positioning the camera or use one of the other cameras that make targeting objects much easier.

TargetCamera3D

TargetCamera3D has all the properties of Camera3D, but it has a special ability to "target" other objects or positions in the 3D world:

movie: Basic05TargetCamera3D.as

Use the navigation keys as for the above movie. Using a TargetCamera3D, the methods for moving the camera about get a new meaning. Here the camera is always looking at the target object, so camera.moveLeft actually rotates the camera around the targeted object.

By default, this camera is looking at the center of the coordinate system, but we can change this to any other position by changing the target:

 

 

<PRE>
1.camera.target = sphere;
</PRE>

 

 

To see how the targeting works, just click any of the primitives in the example above.

HoverCamera3D

HoverCamera3D has all the properties that TargetCamera3D has, but adds methods that are useful for circling around an object by setting the desired pan and tilt. It also hovers the camera, so that it moves softly from one position to another. You are not limited to circle around objects though, so this is maybe the most versatile camera of them all.

movie: Basic06HoverCamera3D.as

Instead of using the move-methods, we now use two custom properties in the HoverCamera3D:

 

 

<PRE>
1.camera.targetpanangle = 0;camera.targettiltangle = 0;
</PRE>

 

 

These are the angles from 0 to 360 that the camera will Pan and Tilt to. These values are relative to the current values:

 

 

<PRE>
1.camera.panangle = 0;camera.tiltangle = 0;
</PRE>

 

 

These are the starting point for the "hover", so when we create the new camera, we also set these to zero. The "hover" is effectively a tween of the position that is performed over a predefined number of "steps":

 

 

<PRE>
1.camera.steps = 16;
</PRE>

 

 

By increasing this from the default 8 steps, we'll get a slower and smoother transition from one angle to another. You can also reduce this number, all the way down to zero steps. This will move the camera instantly to it's new position. Note that for the HoverCamera3D to actually "hover", we need to add a little something to our EnterFrame method:

 

 

<PRE>
1.camera.hover();view.render();
</PRE>

 

Unless you call camera.hover() the camera will just stand still. Now it's time to put these properties to use and see how they work.

Orbiting your scene using the Mouse

One of the most classic ways to display a 3D scene is to just move the camera back from the scene center and let the user rotate around the scene using the mouse as in the example below.

 

movie: Triaxe2.as

I'll now explain what happens in this code. We start by defining some variables that we'll need later.

 

<PRE>
1.private var View:View3D;private var swfStage:Stage;private var cover:Cover;
2.// HoverCam controlsprivate var camera:HoverCamera3D;
3.private var lastMouseX:Number;private var lastMouseY:Number;
4.private var lastPanAngle:Number;private var lastTiltAngle:Number;
5.private var move:Boolean false;
</PRE>

 

We then add a HoverCamera3D and set our view to use that rather than the default camera.

 

<PRE>
1.camera = new HoverCamera3D({zoom:2, focus:100, distance:250});
2.View = new View3D({camera:camera,x:250, y:200});
</PRE>

 

We set some pan and tilt values on the camera so it opens at an angle a little different from the default:

 

<PRE>
1.camera.targetpanangle = camera.panangle = 45;
2.camera.targettiltangle = camera.tiltangle = 20;camera.mintiltangle = -90;
</PRE>

 

Note that we have to set both the angle and the accompanying targetangle at once, or the camera will start by rotating towards the target angle. Also note that we set 'mintiltangle' to minus ninety. This allows us to rotate below the scene, something that is prevented by default.

Next, we add some objects to our Scene and set the scene to render on EnterFrame.

 

<PRE>
1.addEventListener(Event.ENTER_FRAME, onEnterFrame);
</PRE>

 

To grab the values from the Mouse, we define two more listeners and tell these to call functions when they occur:

 

<PRE>
1.this.stage.addEventListener(MouseEvent.MOUSE_DOWN, MouseDown);
2.this.stage.addEventListener(MouseEvent.MOUSE_UP, MouseUp);
</PRE>

 

In our MouseDown handler, we'll need to save the current pan and tilt values of the camera as well as the position of the mouse. We'll use these to calculate the speed of the camera later.

 

<PRE>
1.private function MouseDown(event:MouseEvent):void{
2. lastPanAngle = camera.targetpanangle; lastTiltAngle = camera.targettiltangle;
3. lastMouseX = stage.mouseX; lastMouseY = stage.mouseY; move = true;}
</PRE>

 

Note that we're also setting the boolean variable 'move' to true. This variable will tell us if the mouse is down or up, so when the mouse is released, we'll unset it.

 

<PRE>
1.private function MouseUp(event:MouseEvent):void{ move = false;}
</PRE>

 

The last bit we need is where 'the magic' happens, in the EnterFrame handler.

 

<PRE>
1.private function onEnterFrame(e:Event):void// rerender viewport
2. var cameraSpeed:Number = 0.3; // Approximately same speed as mouse movement.
3. if (move) {
4. camera.targetpanangle = cameraSpeed*(stage.mouseX - lastMouseX) + lastPanAngle;
5. camera.targettiltangle = cameraSpeed*(stage.mouseY - lastMouseY) + lastTiltAngle;
6. } camera.hover(); View.render();}
</PRE>

 

The goal of this function is to calculate a small value that we can add to the target pan and tilt values. We know the previous mouse position ('lastMouseX/lastMouseY') since we saved these in our MouseDown handler. By subtracting the current values, we'll know how far the Mouse have moved. We multiply this with a speed factor ('cameraSpeed') and add the result to the existing values (lastPanAngle/lastTiltAngle). We finish off by calling the hover and render functions to make the view update.

If you want the inverse of this - so the mouse moves in the opposite direction of dragging, you just swap the parameters around:

 

<PRE>
1.camera.targetpanangle = lastPanAngle - cameraSpeed*(stage.mouseX - lastMouseX);
2.camera.targettiltangle = lastTiltAngle - cameraSpeed*(stage.mouseY - lastMouseY);
</PRE>

 

This is just one of many possible solutions to rotating around an object and there's many ways you can improve on this. How about adding scrollwheel support for zooming (camera.zoom)? We'll get back to camera movement in many of the following tutorials, so just keep reading to learn more




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

카메라만 잘 구현해도 에펙 부럽지 않은 비주얼을 만들 수 있을 것이다.


열공!

Posted by chacolina
Study/Actionscript 3.02009. 12. 6. 20:48
http://www.smashingmagazine.com/2009/08/10/discovering-papervision3d-best-design-practices-and-tutorials/


PV3D 관련자료 입니다.
이미 유명한 사이트들이지만...스크렙을 해놓지 않으면 잊어버리기 때문에...가끔씩 들어가서 원리를 생각해보는 것도 좋은 복습인것 같습니다.
Posted by chacolina
Study/Actionscript 3.02009. 12. 6. 17:52

Implicit coercion of a value with static type

 

자주 보게 되는 에러들이다

 

1118: Implicit coercion of a value with static type flash.display:DisplayObjectContainer to a possibly unrelated type flash.display:MovieClip.
1118: Implicit coercion of a value with static type Object to a possibly unrelated type loadLayer.

 

이 에러들은 반환되는 값이 명확하지 않기때문에 생기기때문에 명확하게 해주자

 

_layer_block.addEventListener("CompleteLoadLayer", LoadClipInfo);

 

private fuction LoadClipInfo(e:Event):void

trace(_layer_block);  //결과 [object loadLayer]

trace(e.target);         //결과 [object loadLayer]

trace(e.target == e.target);   //결과 true

 

하지만

아래함수로 호출하게 되면

loadload(_layer_block);          //결과 이상없음

loadload(e.target);                 //결과 . 1118에러

 

private function loadload(layer:loadLayer):void

 

e.target으로 호출하면 에러가 난다

그럴땐 강제로 반환되는 형을 맞춰 주자

loadload(e.target as loadLayer);




Posted by chacolina
Study/etc.2009. 11. 30. 00:44





오래걸려서 외면 당했나 싶었는데.....답이 왔다.
선행 경험자들의 의견에 따르면 느리고 복잡하다던데....
궁금하니까....해보긴 해봐야지
Posted by chacolina
Study/etc.2009. 11. 19. 22:18

알리바바와 40인의 도둑은 과연 어떻게 되었을까요?
최근에 관심가질만한 UX 주제들을 하나씩 꺼내어, 이에 대해서 여러분들과 즐겁고 뜨겁게,
같이 이야기 나눠보는 시간을 가지고 싶습니다.

Reagan Hwang.



프로젝트만 회원여러분. 간만에 인사드립니다. 어느덧 겨울의 문턱에 와있습니다.
이 가을의 끝을 잡고, 오래 기다리고 성원해주셨던 여러분들을 위해 8번째 세미나를 오픈합니다.

한국마이크로소프트에서 눈부신 활약을 하시고, 업계에서도 유명하시며, 겸손하신
황리건 과장님께서, 위의 말처럼 UX에 대해 좋은 이야기를 많이 해주시고, 나누실 것 같네요.

예로 아래와 같은 내용들이 동굴속의 보물처럼 들어있을지도 모르겠네요.

- 아이디어나 영감을 얻는 체험여행이나 문화생활 노하우
- IDEO 디자인 씽킹(디자인 방법론)을 내 업무에 적용하는 방법 또는 경험
- 필드리서치를 업무에 활용하는 방법
- 멀티터치 마우스가 가져올 인터페이스의 변화
- 3~4 스크린 환경에서의 디지털 경험(그리고 우리가 준비해야 하는 것)
- 회사 내 UX팀의 허와 실
- 웹 이후의 세계에서의 웹에이전시가 나아갈 길과 그 속에서의 내 일
- SNS 등에서 웹사이트에서 소셜한 경험을 디자인할 때의 고려사항
- 클라우드 컴퓨팅 시대에 사용자 환경의 변화를 예측하기
- 기타 등등등


늘 그랬듯이 프로젝트만의 강의/세미나는 형식과 구태의연한 스타일과는 거리가 멉니다.
약간은 말랑말랑하게, 약간은 치열할 정도로 진지하게, 실무의 궁금증과 갈등을 해결해주고,
인간적인 이야기가 넘쳐나는 스릴넘치고 강렬하지만, 따스한 시간 그리고 공간.

40인의 도둑이 아니라 UX에 관심이 있으신 40분들을 초대합니다.

- 초대 인원수 : 40명 (프리티켓 소지자는 금번에 해당 되지 않습니다)
- 세미나 강사 : 황리건 과장 (강사소개 보기)
- 세미나 타이틀 및 내용은 위에 언급한대로
- 세미나 일시 : 2009년 11월 28일(토요일) 오후 3시 - 6시
- 프로그램 일정 : 아래와 같음

   1. 참석자 확인/입장
   2. 황선배의 오프닝
   3. 리건 과장님의 약간열린 세미나
   4. 팀플레이(이벤트) 그리고 선물배포
   5. 단체사진 촬영과 안녕~~

- 세미나 장소 : 논현동의 멋진 포토 스튜디오 스타일임팩트 (소개보기)
  * 이번에는 특별히 포토그래퍼 배지환 실장님계서 장소를 지원해주셨습니다.


================================
오랜만에 프로젝트 만에서 좋은 소식을 전해주셔서 기분이 좋습니다.
저는...얼마 전까지 UI 기획일을 하다가 현재는 뜻하는 바가 있어....잠시 한눈을 팔고 있는 사람이랍니다.
저에 대한 자세한 사항은 rezume 에서 확인 하실 수 있사옵니다.

일찍부터 황리건씨가 운영하시는 UX factory를 보고 있으며...몇 번 글을 남기기도 했답니다....항상 좋은 이야기와
신선한 피들이 모여있어서 그런지 재미있게 놀다 왔던 기억이 나네요.

아무튼 이번 기회를 통해서
황리건씨가 말하는 ux 이야기를 듣고 싶고요...
온라인을 통해서만 뵙던 모습을....실제로 확인(?) 할 수 있는 기쁨도 경험했으면 좋겠네요....

제가 만약 뽑히게 된다면...
팩토리에...멋있는 글...하나 올리겠습니다..하하하하하하하하....

!!!!!!!!!!!!!!!!!!!.......

고맙습니다!


Posted by chacolina