Archive for the 'Flash-Tip' Category

Page 3 of 4

Label Statements

ActionScript 3 introcuduces labels, new identifiers that can be associated with loop blocks. Why would you want to identify a loop block? Because you can use that identifier as a target for break and continue commands. Consider two loops where one is nested in the other. If at some point you want to exit both loops while in the nested loop, you can’t. The break command only exits the current block. A common workaround is to use a flag variable to be able to check that, when in the first loop, if that should be exited as well

중첩된 loop의 경우 기존에는 한번에 loop를 벗어나는것은 할수 없었다.

다만 flag를 이용해 벗어나는 경우가 유일한 방법이다. 이젠 그럴필요 없다.

As3.0 에서는 Label Statements 를 이용해 전체 루프를 빠져나올수가 있다.

As 2.0 ActionScript Code:

var i:Number;
var j:Number;
var exit:Boolean = false;
 
for (i=0; i<10; i++) {
	for (j=0; j<10; j++) {
          if (i >3 && j> 3) {
		  exit = true;
		  break;
          }
     }
	if (exit) {
	   break;
	}
 
}

—–> exit 라는 flag 변수를 이용해 체크한다.

As 3.0 ActionScript Code:

var i:Number;
var j:Number;
 
mainLoop: for (i=0; i<10; i++) {
	for (j=0; j<;10; j++) {
		if (i > 3 && j > 3) {
          break mainLoop;
		}
    }
}

——> mainLoop 의 label 을 지정해 한번에 loop 탈출…..지저분하게 변수를 사용하지 않는 명확한 방법이다.

Easing motion in Frame

프레임 모션에 easing 값을 넣어서 적용하는 방법…
프레임의 길이가 적어도 200 frame 이상이 되여야만 어느정도 부드러운 효과를 기대할수 있다.
일반적인 트윈같은 경우 action 으로 하는 경우가 훨씬 자연스럽지만 프레임 모션을 사용해야할경우
이 방법을 사용하면 action 같은 frame 모션이 가능하다.

import mx.transitions.Tween;
import mx.transitions.easing.*;
 
mc._frame = mc._currentframe;
 
var myTween:Tween = new Tween(mc, "_frame", Strong.easeOut, mc._currentframe, 300, 1, true);
 
myTween.onMotionChanged = function() {
mc.gotoAndStop(Math.round(mc._frame));
};
myTween.onMotionFinished = function() {
this.yoyo();
};

프레임 속성을 동적으로 할당해서 Tween class 를 사용하여 easing function 를 적용하여 구현.

The delete Keyword

The delete keyword in Flash is used to remove variable definitions. It doesn’t delete objects from memory (this happens behind the scenes using something called the “Garbage Collector”), it just takes a variable you’ve created and gets rid of it so that it is no longer accessible and is no longer present through iteration (for..in loops, etc.).

Internally, the Garbage Collector, or GC for short, knows when to physicially delete objects in memory when they no longer have any variables that reference them. So, for example, if you have two variables A and B and they both reference ObjectX, deleting variable A will not cause ObjectX to be removed from memory by the GC because variable B still references it. However, if you delete both variables A and B, there will be no more references to ObjectX and the GC will recognize that it needs to be removed from memory

ActionScript Code:

var a:Object = new Object();

var b:Object = a; // reference same new Object();

delete a;

trace(b); // [object Object] – still exists in memory

delete b; // GC will mark object for deletion from memory

This works practically the same way for Flash 8 and Flash 9 (ActionScript 1, 2, and 3), though some changes were made in 8 to improve the GC. (Note: GC deletion from memory is not immediate.)

Though the GC has not really changed much with ActionScript 3 and the new virtual machine that runs it, what has changed is the behavior of the delete keyword. Now, the delete keyword only works for dynamic properties of a class instance and not declared class memebers (variables or methods). With ActionScript 1 and 2, delete could be used for anything. ActionScript 3 only lets you delete dynamic variables and locks those which are not.

// ActionScript 2

class DeleteVarClass {

public var myVar:Number;

function DeleteVarClass() {

myVar = 1;

trace(myVar); // 1

delete myVar;

trace(myVar); // undefined

}

}

// ActionScript 3

package {

public class DeleteVarClass {

public var myVar:Number;

public function DeleteVarClass() {

myVar = 1;

trace(myVar); // 1

delete myVar;

trace(myVar); // 1

}

}

}

Because myVar in the above example was declared as part of the class definition, it cannot be deleted using delete in ActionScript 3.

Since you cannot delete class members in ActionScript 3, if you want to cause a variable to no longer reference an object or value in memory you should set your variable’s value to null instead of deleting it.

Garbage Collectors는 참조값이 없는한 사용되지 않는 변수에 대한 메모리를 자동으로 찾아서 소거해주는 메모리 소거 프로세스이다. 기능상으로는 AS2.0 이나 AS3.0 이나 크게  달라진 부분은 없지만 한가지, AS3.0 에서는 클래스 맴버변수로 선언된 변수는 제거할수 없게 바뀌었다.

Detecting When the Mouse Leaves

One thing about previous versions of ActionScript was that you could never tell when the user no longer had his or her mouse over the Flash movie. This made it hard for people to know whether or not the user is still interacting with their movie or if they’ve given up and moved on to something more interesting. This was especially a problem for custom cursors where, if the user moved the cursor off the Flash movie, the custom cursor would still remain in the Flash movie not moving while the real cursor could be seen moving around every where else. ActionScript 3 now allows you to detect when the mouse has left the flash movie using the stage’s mouseLeave event. This event happens whenever the mouse exits the Flash movie. There is no mouseEnter event, but you can use mouseMove for that since mouseMove only occurs in Flash (for the stage, or really any, object) when the mouse is within the bounds of the movie.

html에서의 플래시 영역 밖으로 마우스 커서를 옮겼을경우 이전에는 정확히 그것을 알아낼 방법이 없었다. 마우스 커서가 안보인다 하더라도 엄연히 플래시 오브젝트 안에 남아서 실행되고 있었는데

이것을 as3.0 에서는 체크할수 있게 되었다.

package {
 
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.ui.Mouse;
 
    public class Test extends Sprite {
 
        private var cursor:Sprite = new Sprite();
 
        public function Test() {
 
            cursor.graphics.beginFill(0xFF);
            cursor.graphics.drawRect(0, 0, 25, 25);
 
            addChild(cursor);
 
            stage.addEventListener(Event.MOUSE_LEAVE, cursorHide);
            stage.addEventListener(MouseEvent.MOUSE_MOVE, cursorFollow);
 
            Mouse.hide();
        }
 
        public function cursorHide(evt:Event):void {
            cursor.visible = false;
        }
 
        public function cursorFollow(evt:MouseEvent):void {
 
            if (!cursor.visible) cursor.visible = true;
            cursor.x = stage.mouseX;
            cursor.y = stage.mouseY;
 
            evt.updateAfterEvent();
        }
    }
}

ActionScript 3.0 Tip of the Day

[퍼온글] 출처 : http://www.kirupa.com/forum/showthread.php?t=223798

The release of Flex Builder 2 is around the corner and though the next version of Flash is still a ways away, ActionScript 3 will be a big part of Flex 2 and the impending release of Flash Player 9 (which arrives with Flex). ActionScript 3 is the next step forward and to help with the transition (for those of you deciding to make it), I thought, since I’ve been working with AS3 a bit lately, I’d make a new Tip of the Day thread for ActionScript 3 to help people prepare. So here we go:

ActionScript 3 Tips and Tricks:

  1. 06-19-06: Change the frame rate of your movie
  2. 06-20-06: Class scope is now bound to class methods
  3. 06-21-06: Graphics Object and the Drawing API
  4. 06-22-06: New Variable Types
  5. 06-23-06: Display Objects
  6. 06-24-06: New Import Directive
  7. 06-25-06: Type Casting and the as Operator
  8. 06-26-06: Unique Class Variables
  9. 06-27-06: New MouseMove Behavior
  10. 06-28-06: The delete Keyword and Class Members
  11. 06-29-06: The Dictionary Class
  12. 06-30-06: Label Statements
  13. 07-01-06: Detecting When the Mouse Leaves the Movie
  14. 07-02-06: SimpleButton Instances
  15. 07-03-06: Commas in Shorthand Array Definitions
  16. 07-04-06: Package Block
  17. 07-05-06: Same-file Helper Classes
  18. 07-06-06: Access Attributes
  19. 07-07-06: Abstract Classes
  20. 07-08-06: The override Keyword
  21. 07-09-06: Using prototype
  22. 07-10-06: Regular Expression (RegExp) Support
  23. 07-11-06: Approach to Depth Sorting
  24. 07-12-06: Deep Object Copies with ByteArray
  25. 07-13-06: Similarly Named Instance and Static Properties
  26. 07-14-06: EventDispatcher
  27. 07-15-06: Events and Event Types
  28. 07-16-06: Writing Inline XML
  29. 07-17-06: Determine Instance Class or Superclass
  30. 07-18-06: super() Placement (Now Anywhere)
  31. 07-19-06: Determining Current Frame Label
  32. 07-20-06: Multiple Arguments in trace()
  33. 07-21-06: Calling Event Handlers without Events
  34. 07-22-06: URLRequest for URL Strings
  35. 07-23-06: XML vs. XMLDocument
  36. 07-24-06: Loading Text and XML with URLLoader
  37. 07-25-06: is Operator (vs instanceof)
  38. 07-26-06: Flash 9: Timelines as Classes
  39. 07-27-06: RegExp: Email Validation
  40. 07-28-06: Render Event
  41. 07-29-06: XML: @ Operator for Attributes
  42. 07-30-06: Event Propagation Support
  43. 07-31-06: Get Sound Spectrum Information
  44. 08-01-06: Number() Conversion No Longer Interprets Octals
  45. 08-02-06: Garbage Collection: Reference Counting & Mark and Sweep
  46. 08-03-06: Weak References
  47. 08-04-06: Flash 9: BitmapData and Bitmaps from the Library
  48. 08-05-06: Changes in typeof
  49. 08-06-06: getBounds() vs getRect()
  50. 08-07-06: for..in and for each..in

_______________________________________

Additional Resources:

Download:

ExternalInterface bug (Firefox)

Just a quick warning to people using ExternalInterface. When you are calling Javascript functions that open new windows your Flash movie will lose all mouse interaction (no rollovers etc) and the button you pressed to open the popup will stick on its “over” state. This is only in Firefox, (and possibly only when the popup contains a Flash movie, tbc).

flash8 에 새로운 External API. 인 ExternalInterface…..

실무에 적용하여 사용한적은 없는것 같다. 그다지 쓰이지 않아서 그런진 몰라도…

Firefox에서 새로운 팝업창에서의 플래시 무비가 전혀 마우스 반응을 하지 못하는 버그가 있다.

팝업창을 사용하지 않는것이 좋겠지만 어쩔수 없이 사용해야할 경우, 그리고 꼭 firefox에서도 지원해야할경우

이때는 간단히 getURL 로 javascript 호출하면 된다.

Alpha Gradiant Masks

flash8 이 출시된지 반년 이상이 지났다.
정말 출시전에는 엄청난 기능상의 변화, 그리고 놀라운 퍼포먼스의 향상과 같은 프리뷰 내용으로 잔뜩 기대감에 부풀어 있었지만 정작 뚜껑을 열어보고 사용해보니 기대가 너무 컸던 탓일까…
지금에 와서는 좀 아쉬는 생각이 든다.
플래시에서도 photoshop과 같은 필터효과를 줄 수 있다라는 말에 정말 이젠 플래시로 표현 못하는것이 없겠구나 하는 했지만….원하는 정도의 효과를 사용한다면 너무 느려지는 퍼포먼스로 인해 도저히
봐줄수 없는 상태……

물론 BitmapData 의 도입으로 기존에는 할수 없었던 것들을 할수있다.
하지만 게으름때문인지는 몰라도 이런 위의 문제점으로 성능상에 문제가 있을거야 하는 내나름의 한계를 그어버리는 건지도 모른다. as3.0이 본격적으로 사용되면 최대 9배 이상의 성능향상이 있다고 한다. 그렇게 되면 핑계도 없어질텐데….
정말 해봐야 할것 많은데…몸이 따라주질 않는다..

전에 한번 flash 8 에서 비트맵을 지원해서 Mask 에서도 alpha 값을 사용할 수도 있다는 내용을 본적이 있어 이것저것 테스트 해보았는데 정말 alpha gradiant 를 Mask 에서도 사용할수 있었다.

maskee.cacheAsBitmap = true;
maskMC.cacheAsBitmap = true;

actionscript 에서 적용하려면 mask 무비클립과 mask 되어지는 무비클립에 cacheAsBitmap 을 적용해 비트맵으로 전환한다.
그리고 alpha gradiant  를 적용할 mask를 제작하여 적용하면 된다.

movieclip property 창에서 적용할 수도 있다. Use runtime bitmap caching 을 체크해주면 위와 똑같은 기능을 한다.

flash를 사용할때면 alpha 값이 적용된 mask를 꼭 한번 사용할 일이 있을것이다.
그때 잊지말고…..

Alcon – ActionScript Logging Console

Alcon is a lightweight external output console for Flash ActionScript that allows developers to view debugging information without relying on the Flash IDE. SWF files can be debugged and monitored no matter if they are in the web browser, Flash Player or a standalone executable. While that Alcon tries to keep inclusion into projects as simple as possible. In fact all that needs to be done is importing the Debug class into a project and you are ready to send debug information to the console with a simple Debug.trace() command.

Included into a project Alcon keeps a small footprint and takes less than a Kilobyte of filesize while still offering some other helpful features.

Please note: Alcon is now hosted at the Flash Game Programming Wiki (fgpwiki.corewatch.net/wiki/alcon)! New versions are downloadable from there

다운로드하기

정말 이전부터 꼭 필요했던 건데…특히 다른 곳과 함께 작업할 시에 강력한 힘을 발휘할듯..
간단한 디버거를 만들어 쓰긴했지만 원하는 log level 수준까지 걸러서 다른 색으로 가독성 높게 표현해준다..

이젠 웹브라우저에서도 디버깅이 가능할듯 싶다…

alcon

Global Security Settings panel

플래시 8의 로컬 보안 변경사항에 따라 로컬상의 테스트를 html 상에서 하려면

경고창이 떠서 아주 성가셨다.

전역보안설정패널에서 c 드라이브 통채로 설정해 놓으면 된다.

전역 보안 설정 패널 가기

Clearing All setIntervals

객체를 삭제하거나 무비클립을 unload 해도 setInterval Id 값은 전역속성으로서 그대로 메모리에 남아 지우지 않는한 계속실행된다. 전에 이걸 모르고 코드를 작성했다가 엄청난 멍멍이고생을 했던기억이 새록새록 난다.
과연 어떻게 클래스에 상관없이 모든 객체내에 쓰인 setInterval 을 몽땅 없애버릴수 있을까?…
나이스한(?) 방법을 하나 발견했다..

  function clearAllIntervals() {
    var topID = setInterval(function () {}, 100);
    for (i=0; i&lt;=topID; i++) {
     clearInterval(i);
    }
  }

Id 값이 순차적으로 증가한다는 사실에 착안…새로운 인터벌 생성후 그 이전 아이디 값을 몽땅지운면 끝….