Eversince the release of Flash 8, I’ve rarely published a Flash projectwith a HIGH stage quality. If you know why, then you can skim this postand leave me a high-five in the comments, if not then read on …
So what’s stage quality I hear some of you asking? Well, you may ofseen it feature within the default context menu of the Flash Player.And this small setting defines how certain elements areanti-aliased/smoothed within your Flash application.
Here are the four available quality settings:
StageQuality.LOW - Graphics are not anti-aliased, and bitmaps are not smoothed.
StageQuality.MEDIUM - Graphics are anti-aliased using a 2 x 2 pixel grid, but bitmaps are not smoothed.
StageQuality.HIGH - Graphics are anti-aliased using a 4 x 4 pixel grid, and bitmaps are smoothed if the movie is static.
StageQuality.BEST - Graphics are anti-aliased using a 4 x 4 pixel grid and bitmaps are always smoothed.
So, HIGH and BEST sounds really awesome right? Think again! Let’s take a brief look at (vector) graphics:
Vector graphics (also called geometric modeling orobject-oriented graphics) is the use of geometrical primitives such aspoints, lines, curves, and polygons, which are all based uponmathematical equations to represent images in computer graphics. It isused in contrast to the term raster graphics (also know as a Bitmap),which is the representation of images as a collection of pixels, andused as the sole graphic type for actual photographic images.
When Flash renders a vector graphic, the bitmap result of the vectordata is calculated on the fly. This can be awfully taxing on the usersmachine depending on how complex the vector graphic drawing is. A largepart of this calculation goes on smoothening-out all of the lines andedges so that you end up with something that doesn’t look jaggy, andthis is where the quality setting comes into play. You can think of thequality setting as accuracy level of anti-aliasing. So, the higher theaccuracy, the more work has to be done when rendering.
So what changed in Flash 8?. Well, Bitmaps staged a military coupand took the crown away from vector graphics of course (err). Firstoff, we got the cacheAsBitmap flag, this took a lot of stress ofrendering complex vectors away such as UI components. Then we got theawesome BitmapData class (its like a freaking Swiss army knife!), andfinally we got Advanced embedded text rendering. The new text renderingis the most important reason for not using HIGH anymore as it does notsuffer from jaggies in lower modes.
Back in 2005, I created my first Flash 8 website while working at Sparkart for Mike Shinoda’s side project, Fort Minor (http://fortminor.com/site.php).I really wanted to dip my toes into as many Flash 8 features aspossible. So, in the site you’ll see blend modes, blurs, vp6,BitmapData (used for image flattening) and advanced text. But the bestthing about all of this is that the site stage quality is set to LOW!Now, this site wont win any awards for usability and the code is rushed(~2.5 week project) but you’ll see how I was able to push the speed ofthe animation by setting the quality to LOW without really loosinganything visually. An important thing to note from this is that thesite has no vector graphics, its all bitmap based.
This brings me briefly onto Papervision 3D developers who actually inspired me to write this post. Today, I came across the papervision based game “Downtown Maze Master”from Nissan. I noticed that the game was running in HIGH mode throughthe games context menu as my MacBooks core was running at 77% and mylaptops fan soon fired up. Thanks again to the context menu, I took thesetting down to LOW and immediately watched my core usage go down to54% without any anything visually bad happening in the game. I’dusually expect papervision3d developers to be close on the bleedingedge of Flash, so I wonder why the quality setting was forgotten. Andthis site is only once of many papervision3d sites guilty of this sin.End of rant, spread the word :).
Bitmaps rock your sock in Flash, but what about if you need toresize bitmap elements? Well in my world today, I work mainly oncreating application UIs vs website experiences, and my best friend is9 slice bitmap scaling. To read more about 9 slice resizing, check here.But what about if you still need to utilize vector graphics and runwith a LOW setting? Well, you may still need to use the HIGH setting ifyour vector is quite dynamic and/or shape tweened. But if your onlyplaning to pan your vector around the stage, then you might be able touse LOW successfully if you “flatten” the vector to a Bitmap in HIGHmode, then switch back to LOW.
// ActionScript 3
stage.quality = StageQuality.HIGH;
var shape:Shape = new Shape();
shape.graphics.lineStyle(2,0xcc00cc);
shape.graphics.drawCircle(100,100,100);
var bitmapCanvas:BitmapData = new BitmapData(200,200,true,0xffffff);
bitmapCanvas.draw(shape)
stage.quality = StageQuality.LOW;
var circleImg:Bitmap = new Bitmap(bitmapCanvas);
addChild(circleImg)
The result will be a wonderfully anti-aliased circle shown in LOWmode. This method also works well for cutting down the number ofelements on stage in general, just think of it as an uneditablecacheAsBitmap.
The lesson I want you to take from this post is to always play withyour default quality mode before pushing your site live. You just mightget a pleasant surprise :).
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.
한동안 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입니다. 이러한 상황은 훨씬 더 복잡해질 수 있으며(a가 c를 참조하고, 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를따라온 것이고, 녹색 객체는 표시된 것이고, 흰색 객체는 할당 해제될 것입니다.
그림 1. Flash Player에서 표시 및 회수 방법을 통해 활성 참조가 없는 객체 식별
표시 및 회수는 매우 정확합니다. 그러나 Flash Player가 전체 객체 구조를 검토해야 하므로 CPU 사용 관점에서볼 때 이 프로세스에는 비용이 많이 듭니다. Flash Player 9에서는 표시 및 회수를 반복적으로 수행하고(동시에 모든프레임이 아니라 여러 프레임씩 나누어 프로세스 진행) 이 프로세스를 가끔 실행함으로써 이 비용을 줄입니다.
가비지 수집기의 지연 및 불확정성
Flash Player 9에서는 가비지 수집기의 작동이 지연됩니다. 이것은 매우 중요한 개념으로서 반드시 이해해야 합니다.모든 활성 참조가 삭제되더라도 객체가 즉시 제거되지 않고, 향후 불확정적인 시간에 제거됩니다(개발자 관점에서 볼 때). 가비지수집기는 일련의 추론을 사용하고 무엇보다도 RAM 할당 및 메모리 스택의 크기를 관찰하여 실행 시기를 결정합니다. 개발자입장에서는 비활성 객체가 언제 할당 해제될지 알 수 없다는 사실을 받아들여야 합니다. 또한 가비지 수집기가 비활성 객체의 할당을해제할 때까지 비활성 객체가 계속해서 실행될 수 있다는 점을 인식해야 합니다. 따라서 할당이 해제되기 전에는 코드도 계속실행되고(enterFrame 이벤트가 계속 발생), 사운드도 계속 재생되고, 로드도 계속 발생하며, 기타 이벤트도 계속 일어나게됩니다.
Flash Player의 가비지 수집기가 객체의 할당을 해제하는 시기를 개발자가 전혀 제어할 수 없다는 사실을 기억하는것이 매우 중요합니다. 개발자라면 게임과 애플리케이션을 완료할 때 그곳의 객체를 최대한 자신이 원하는 대로 제어하고 싶을것입니다. 이러한 프로세스의 관리 전략은 필자의 동료가 작성한 Flash Player 9의 리소스 관리 전략 기술문서에 소개되어 있습니다.
다음 가비지 컬렉션 시뮬레이션에서 전체 메모리의 톱니 모양을 살펴보십시오(그림 2 또는 아래 링크 클릭). 수집기가 회수를수행할 때 하강이 발생합니다. 차트를 자세히 보려면 클릭하십시오. 일시 중지하거나 다시 시작하려면 스페이스바를 누르고, 실행되는동안 메모리 사용 추세를 변경하려면 위/아래 화살표를 누르십시오.
불충분한 참조에 대한 자세한 내용을 살펴보거나 필자가 작성한 보조 클래스를 다운로드하려면 필자의 블로그 gskinner.com을 방문하십시오.
저자 소개
Grant Skinner는 Flash 개발 및 컨설팅 업체인 gskinner.com*의CEO이자 아키텍트 부문의 책임자로 선도적인 신생 미디어 에이전시와 진취적인 기업 클라이언트와 함께 첨단 애플리케이션과 게임,멀티미디어 구성 요소를 제작하고 있습니다. 인터페이스 디자인, 유용성, 마케팅 및 비즈니스 로직에 코딩을 적용하는 전문성을 통해국제적인 명성을 얻고 있는 그는 FITC 2005의 Best Canadian Developer를 비롯하여 업계의 권위 있는 상을여러 번 수상했습니다. Grant는 gskinner.com/blog/*에서 블로그를 운영하며 incomplet.org*에 그의 실험적 작품을 전시하고 있습니다.
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=newCube(materialList,100,100,100); var cone:Cone=newCone(newWireframeMaterial(0xFF0000)); var sphere:Sphere=newSphere(newWireframeMaterial(0xFF0000));
가
장 빠른 성능을 보이지만 기본으로 제공하는 이외의 형태를 만들지 못하기 때문에 UI 나 Navigation 이 외에는 활용성
면에서는 조금 부족하지 않나 싶다. 결국 사용자화된 오브젝트를 쓰기 위해서는 외부파일을 로드 해야만 한다.
2. AS3 Geom Class Exporter
이
는 3D MAX 에서 AS3 Geom Exporter라는 Max Script를 설치하여서 각 라이브러리 별 .as파일로 바로
export하는 방법이다. 이 방법 또한 각 라이브러리에 맞게 .as파일을 만들어 주기 때문에 성능면에서는 좋지만 이름에서 처럼
Geom 에 대한 데이터만 만들어 주기 때문에 위치나 맵핑에 관한 정보없이 단순한 오브젝트만 만들어 주는 것같다. 결국
애니메이션과 맵핑을 위해서 손이 한번 더 가야 한다.
test =newTest(newWireframeMaterial(0xFF0000));
3. Collada
collada
는 뒤에 좀 더 자세히 설명하겠지만 간단히 말해서 3D데이터를 표준 XML 로 만들어주는 프로젝트이다. 확장자는 .dae 를
사용한다. 이 방법은 PV3D에서 기본으로 지원하던 collada 클래스를 이용하는 방법이다.
collada =newCollada("test.DAE", materialList);
4. DAE
이
방법은 위의 방법과 .dae 파일을 사용한다는 점에서 동일하나 .dae 파일을 파싱하는 클래스가 Collada 가 아닌 DAE
이다. 두 파일의 차이는 DAE는 ASCollada 프로젝트의 파일을 PV3D에 합친것으로 이는 PV3D 2.0a 이후 버전에
적용되었다. 또한 위의 방법과 결정적 차이는 .dae파일의 Animation 을 컨트롤 할 수 있다는 점이다.
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 같은 플러그인을
별도로 설치 해야한다.
flash로 직접 데이터를 불러올 수도 있지만 동기식인 flash의 특성상 효율성이 떨어질 수 있다.
따라서 데이터 처리를 위한 파일을 따로 만들어 주고 그 정보를 flash에 넘기는 방식을 취하여
효율적인 데이터 처리를 할 수 있는데 그럴 경우 많이 쓰이는 것이 xml이다.
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:
1.varcam: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:
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.
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.
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:
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:
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:
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:
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:
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.
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":
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:
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.
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.
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.
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.
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:
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
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.