Formation ActionScript 2.0 Intermédiaire

turnmarySoftware and s/w Development

Jul 5, 2012 (5 years and 6 months ago)

427 views

New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Formation ActionScript 2.0 Intermédiaire
Présenté par
Martin Legris
New Commerce Solutions Inc.
mlegris (à) newcommerce (point) ca
http://www.newcommerce.ca
31 Octobre 2006
1
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Table of Contents
Formation ActionScript 2.0 Intermédiaire
.................................................................................................
1
La librarie, les noms d'instance, l'export vers ActionScript et l'association avec une classe
.....................
6
Le MovieClip et ses événements
................................................................................................................
7
Le concept des 'depths', et ses particularités
..............................................................................................
9
Environnement de développement avec FlashDevelop
..........................................................................
10
Exemple 1 : Utilisation d'XRay
...............................................................................................................
11
Introduction
.........................................................................................................................................
11
Site Web
..............................................................................................................................................
11
Tutoriel
................................................................................................................................................
11
ScreenShot
...........................................................................................................................................
11
Programmation Orientée Objet
...............................................................................................................
12
Tutoriels
...............................................................................................................................................
12
Organisation par 'packages'
.....................................................................................................................
13
Utilisation du MVC
..................................................................................................................................
14
Manipulation des Color Values (involves bit shifting & Bitwise operators)
..................................................................................................................................................................
15
API de dessin
...........................................................................................................................................
16
Sample Advanced Drawing Methods
.......................................................................................................
18
Méthode doArc
....................................................................................................................................
18
Méthode drawThickArc
......................................................................................................................
19
Méthode squiglyLineTo
......................................................................................................................
19
Méthode drawSquiglyRect
..................................................................................................................
21
SharedObject
............................................................................................................................................
25
Propriétées
...........................................................................................................................................
25
Méthodes
.............................................................................................................................................
25
Exemple
...............................................................................................................................................
25
Tutoriel
................................................................................................................................................
26
Gestion des erreurs
...................................................................................................................................
27
MovieClipLoader
.....................................................................................................................................
28
Tutoriel
................................................................................................................................................
29
Exemple 2 – Preloader
.............................................................................................................................
30
Exemple 3 – Utilisation du Custom Easing Tool
.....................................................................................
36
Custom Easing Tool
............................................................................................................................
36
Exemple d'utilisation
...........................................................................................................................
37
Delegate
...................................................................................................................................................
39
Exemple d'utilisation
...........................................................................................................................
39
Tutoriel
................................................................................................................................................
39
EventDispatcher
.......................................................................................................................................
40
Méthodes
.............................................................................................................................................
40
Exemple d'utilisation
...........................................................................................................................
40
2
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Tutoriel
................................................................................................................................................
41
ASBroadCaster
.........................................................................................................................................
42
Méthodes
.............................................................................................................................................
42
Exemple d'utilisation
...........................................................................................................................
42
Tutoriel
................................................................................................................................................
42
Dynamic Registration
..............................................................................................................................
43
Méthodes
.............................................................................................................................................
43
Propriétés
.............................................................................................................................................
43
Exemple d'utilisation
...........................................................................................................................
43
setInterval
.................................................................................................................................................
45
Signature
..............................................................................................................................................
45
Exemple
...............................................................................................................................................
45
Tutoriel
................................................................................................................................................
45
Loading MovieClips & Images
................................................................................................................
46
Propriétés d'un TextField
..................................................................................................................................................................
47
Les propriétés d'un objet Textfield
......................................................................................................
48
Pour utiliser une police embedded
......................................................................................................
51
Propriétés d'un police 'embedded'
...................................................................................................
51
Les propriétés de l'objet TextFormat
...................................................................................................
51
Le Constructeur de TextFormat
..........................................................................................................
53
Les fonctions qui utilisent le TextFormat
............................................................................................
53
Tutoriel
................................................................................................................................................
53
FuseKit
.....................................................................................................................................................
54
Installation
...........................................................................................................................................
54
Premier Tutoriel
..................................................................................................................................
54
Exemple simpliste
...............................................................................................................................
54
Définition
.............................................................................................................................................
54
La signature des fonctions dites 'shortcut' (ZigoEngine) http://laco.wz.cz/
.................................
54
Usage
..............................................................................................................................................
54
Parameters
.......................................................................................................................................
54
Exemple
..........................................................................................................................................
55
Function as animType
.....................................................................................................................
55
Object as animType
........................................................................................................................
55
object as callback
........................................................................................................................................................
56
Do not add spaces between argumets
.............................................................................................
58
Returns
............................................................................................................................................
58
Référence des propriétés qu'on peut modifier
.....................................................................................
58
Exercice - FuseKit
...............................................................................................................................
59
Première Étape
................................................................................................................................
59
Deuxième Étape
..............................................................................................................................
60
Exemple 4 – Premier Compoment
...........................................................................................................
61
Préalable
..............................................................................................................................................
61
Fichiers de départ
................................................................................................................................
61
3
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
MenuItem.as
........................................................................................................................................
61
MenuContainer.as
................................................................................................................................
63
Code dans le FLA
................................................................................................................................
68
Example 5 – Slide Panel Component
.......................................................................................................
70
Prérequis
..............................................................................................................................................
70
Objectif
................................................................................................................................................
70
Aperçu du résultat & Code Source
......................................................................................................
70
SlideGallery.as
....................................................................................................................................
70
AMFPHP – ActionScript Messaging Format avec PHP
..........................................................................
82
Introduction
.........................................................................................................................................
82
Tutoriels
...............................................................................................................................................
82
Documentation
....................................................................................................................................
82
Site principal
........................................................................................................................................
82
Important
.............................................................................................................................................
82
Exemple 6 – Un service de messagerie avec Flash, AMFPHP, PHP et MySQL
....................................
83
Introduction
.........................................................................................................................................
83
Exemple et code source
.......................................................................................................................
83
Base de donnée MySQL
......................................................................................................................
83
Voici le schéma
...............................................................................................................................
83
Et le code SQL pour la créer
...........................................................................................................
83
PHP - Le côté serveur
..........................................................................................................................
85
cinqetdemi.remoting
............................................................................................................................
88
code pour [frame 1] [premier layer]
....................................................................................................
89
code pour [frame 1] [troisième layer]
..................................................................................................
93
code pour [frame 2] [troisième layer]
..................................................................................................
94
code pour [frame 3] [troisième layer]
..................................................................................................
95
Appendix A – Practical UML
..................................................................................................................
97
Use Case Diagrams
.............................................................................................................................
97
Class Diagram
...................................................................................................................................
100
Composition and aggregation
.......................................................................................................
102
Class information: visibility and scope
.........................................................................................
102
Dependencies and constraints
.......................................................................................................
103
Interfaces and stereotypes
.............................................................................................................
104
Packages and object diagrams
...........................................................................................................
105
Sequence diagrams
............................................................................................................................
107
Collaboration diagrams
.....................................................................................................................
109
Statechart diagrams
...........................................................................................................................
109
Concurrency and asynchronization in statechart diagrams
...............................................................
111
Activity diagrams
..............................................................................................................................
111
Component and deployment diagrams
..............................................................................................
113
Appendix B - Understanding Try/Catch in ActionScript
.......................................................................
114
By: Joey Lott
....................................................................................................................................
114
Understanding try/catch
....................................................................................................................
114
Using try/catch
..................................................................................................................................
119
4
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Handling Specific Errors
...................................................................................................................
121
Using finally
......................................................................................................................................
123
Conclusion
.........................................................................................................................................
126
Appendix C – Using MTASC
................................................................................................................
127
Introduction
.......................................................................................................................................
127
Ressources
.........................................................................................................................................
127
MTASC GUI for Windows
..........................................................................................................
127
MTASC Home
..............................................................................................................................
127
Tutorials
.............................................................................................................................................
127
5
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
La librarie, les noms d'instance, l'export vers

ActionScript et l'association avec une classe

Un MovieClip est représenté dans la librarie

Il porte un nom dans la librairie

Une fois glissé sur le Stage, il devient une instance de l'objet dans la librairie et peut

porter un nom d'instance

Un MovieClip peut contenir une quantité presque infinie d'autre movie clips à

l'intérieur de lui-même

Chaque instance a une depth

Chaque MovieClip contient sa propre timeline

On peut associer un item dans la librairie à une classe, pour lui donner une

fonctionnalité standard chaque fois qu'il est instantié.

Pour utiliser la fonction 'attachMovie' on doit exporter un item de la librairie et lui

donner un nom unique qu'on utilisera pour l'identifier en ActionScript.
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
6
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Le MovieClip et ses événements
onData
= function() {}
Invoked when a movie clip receives data from a
MovieClip.loadVariables()
call

or a
MovieClip.loadMovie()
call.
onDragOut
= function() {}
Invoked when the mouse button is pressed and the pointer rolls outside the

object.
onDragOver
= function() {}
Invoked when the pointer is dragged outside and then over the movie clip.
onEnterFrame
= function() {}
Invoked repeatedly at the frame rate of the SWF file.
onKeyDown
= function() {}
Invoked when a movie clip has input focus and user presses a key.
onKeyUp
= function() {}
Invoked when a key is released.
onKillFocus
= function(newFocus:Object) {}
Invoked when a movie clip loses keyboard focus.
onLoad
= function() {}
Invoked when the movie clip is instantiated and appears in the timeline.
onMouseDown
= function() {}
Invoked when the mouse button is pressed.
onMouseMove
= function() {}
Invoked when the mouse moves.
onMouseUp
= function() {}
Invoked when the mouse button is released.
onPress
= function() {}
Invoked when the user clicks the mouse while the pointer is over a movie clip.
onRelease
= function() {}
Invoked when a user releases the mouse button over a movie clip.
7
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
onReleaseOutside
= function() {}
Invoked after a user presses the mouse button inside the movie clip area and

then releases it outside the movie clip area.
onRollOut
= function() {}
Invoked when a user moves the pointer outside a movie clip area.
onRollOver
= function() {}
Invoked when user moves the pointer over a movie clip area.
onSetFocus
= function(oldFocus:Object) {}
Invoked when a movie clip receives keyboard focus.
onUnload
= function() {}
Invoked in the first frame after the movie clip is removed from the Timeline.
Pour les utiliser, il suffit de faire:
var mc:MovieClip = _root.createEmptyMovieClip(“mc”, getNextHighestDepth());
mc.onRollOut = function(){
trace(“mc.onRollOut”);
}
8
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Le concept des 'depths', et ses particularités

Dans un MovieClip en particulier, on ne peut avoir qu'un seul MovieClip sur chaque

'depth'.

Il existe 3 différentes sections dans les possibilités de depth, les voici:
Zone
Range
Note
Timeline
-16 384 to -1
Handled by timeline with

Flash, dynamic removal

disabled
Dynamic
0 to 1 048 575
Most dynamically accessible,

allows dynamic removal
Reserve
1 048 576 to 2 130 690 045
Overflow – ignored by

timeline, dynamic removal

disabled

Flash permet jusqu'à 16 000 instance d'être rendu simultanément sur l'écran.

Voici une liste des différentes méthodes (fonctions) qui sont reliés au 'depths' :
Method
Works on
duplicateMovieClip
MovieClip
attachMovie
MovieClip
createEmptyMovieClip
MovieClip
createTextField
TextField
swapDepths
MovieClip, TextField
getDepth
MovieClip, TextField
removeMovieClip
MovieClip
removeTextField
TextField
getNextHighestDepth
MovieClip

voir la doc sur chacune de ses fonctions...

pour plus d'informations voir
http://www.senocular.com/flash/tutorials/depths/
9
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Environnement de développement avec FlashDevelop

Environnement de développement open-source pour plateforme Windows.

Supporte AS2 & AS3

Intégration de MTASC (pas couverte dans ce cours)

Complète le code

'Search in files' & 'search and replace' supportent les expressions régulières

Explorateur de projet, et d'objet

URL:
http://www.flashdevelop.org/
cliquez sur
Releases
& 2.0
Final Release
.

Introduction sur l'environnement, examples..

Parler d'OSFlash (X-Ray par exemple)... Démontrer Xray


Documentation:
http://www.gotapi.com
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
10
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Exemple 1 : Utilisation d'XRay
Introduction
XRay permet d'obtenir un 'snapshot' complet du l'état de votre application flash (toute

les variables, tous les movieclips, tous les objets en utilisation) à n'importe quel moment.

En utilisant un object nommé 'LocalConnection', le «

XRay connector

» transmet à

l'application «

XRay Interface » toute la structure des informations dans votre application

Flash au moment ou vous le désirez.
Site Web
http://osflash.org/xray
Tutoriel
http://labs.blitzagency.com/wp-content/xray/videos/tutorials/indexFlash.html
ScreenShot
11
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Programmation Orientée Objet

La syntaxe (import, class, extends, private, public, constructeurs, static, interface,

implements, dynamic, intrinsic)

Déclaration d'objets avec {x: 31249, y:2394832, func:funcProto};

Hériter, simple.

Typage des objets, typage de retour de fonction

'Type Casting'

Prototypes (exemple de Math.toRad())

Les design patterns (Singleton, Factory, Delegate, Queue... )

Example d'utilisation du mx.utils.Delegate, concept d'événements

Pourquoi utiliser un singleton (demande à la classe)?

Structure de donnée : Tree, LinkedList, XMLNode

Introduction UML (voir Appendice A)

http://www.gmodeler.com


Utilisation du mx.utils.Delegate
Tutoriels
Singleton (
http://www.newcommerce.ca/as20/SingletonDoc.swf
)
Singleton [suite] (
http://www.simonwacker.com/blog/archives/000079.php
)
Yahoo! Design Pattern Library (
http://developer.yahoo.com/ypatterns/index.php
)
Design Patterns (
http://www.simonwacker.com/blog/archives/cat_design_patterns.php
)
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
12
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Organisation par 'packages'

On organise par packages pour mieux se retrouver.

/ca/newcommerce/controls/BaseControl.as

On doit importer toutes les classes même si elles font parties du même package.

Il est possible de faire : new ca.newcommerce.gui.ControlInfo() ou

import ca.newcommerce.gui.ControlInfo; .... new ControlInfo()
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
13
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Utilisation du MVC

M pour Modèle (les données reçus, transmises, entrés)

C pour Contrôle (contrôle du timeline, des dites données, des événements)

V pour Visualisation (rendu de l'interface, adaptation de cette interface)

Dans chaque composante d'un logiciel il y a un peu de chacun. Le but c'est de bien

distinguer entre chacun; de bien séparer.

Relation avec le corps humain, et la cellule.

Macro MVC, micro MVC

Dans une application typique; le rôle de chacun.

Diagrammes + explications.

Organisation optimale d'une application Flash.
14
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Manipulation des Color Values (involves bit shifting &

Bitwise operators)

Les valeur de couleur en ActionScript sont en format hexadecimal : 0xRRGGBB

Voici une petite fonction qui permet de manipulaler une valeur de couleur en la

décomposant en ses valeurs de RR, GG, BB :
public static function brightenColor(color:Number, perc:Number):Number
{
var colorTrans:ColorTransform = new ColorTransform();
colorTrans.rgb = color; var factor:Number;
var blueOffset:Number = color % 256;
var greenOffset:Number = ( color >> 8 ) % 256;
var redOffset:Number = ( color >> 16 ) % 256;
if(perc > 50 && perc <= 100)
{
factor = ( ( perc-50 ) / 50 );
redOffset += ( 255 - redOffset ) * factor;
blueOffset += ( 255 - blueOffset ) * factor;
greenOffset += ( 255 - greenOffset ) * factor;
}
else if( perc < 50 && perc >= 0 )
{
factor = ( ( 50 - perc ) / 50 );
redOffset -= redOffset * factor;
blueOffset -= blueOffset * factor;
greenOffset -= greenOffset * factor;
}
return (redOffset<<16|greenOffset<<8|blueOffset);
}
15
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
API de dessin

les fonctions de l'API de dessin sont:
Method
Description
beginBitmapFill
(bmp:BitmapData,

[matrix:Matrix], [repeat:Boolean],

[smoothing:Boolean]) : Void
Fills a drawing area with a bitmap image.
beginFill
(rgb:Number, [alpha:Number]) :

Void
Indicates the beginning of a new drawing

path.
beginGradientFill
(fillType:String,

colors:Array, alphas:Array,

ratios:Array, matrix:Object,

[spreadMethod:String],

[interpolationMethod:String],

[focalPointRatio:Number]) : Void
Indicates the beginning of a new drawing

path.
clear
() : Void
Removes all the graphics created during

runtime by using the movie clip draw

methods, including line styles specified with

MovieClip.lineStyle()
.
curveTo
(controlX:Number,

controlY:Number, anchorX:Number,

anchorY:Number) : Void
Draws a curve using the current line style

from the current drawing position to

(
anchorX
,
anchorY
) using the control point

that (
(controlX
,
controlY
) specifies.
endFill
() : Void
Applies a fill to the lines and curves that

were since the last call to
beginFill()
or

beginGradientFill()
.
lineGradientStyle
(fillType:String,

colors:Array, alphas:Array,

ratios:Array, matrix:Object,

[spreadMethod:String],

[interpolationMethod:String],

[focalPointRatio:Number]) : Void
Specifies a line style that Flash uses for

subsequent calls to the
lineTo()
and

curveTo()
methods until you call the

lineStyle()
method or the

lineGradientStyle()
method with

different parameters.
lineStyle
(thickness:Number,

rgb:Number, alpha:Number,

pixelHinting:Boolean,

noScale:String, capsStyle:String,

jointStyle:String,

miterLimit:Number) : Void
Specifies a line style that Flash uses for

subsequent calls to the
lineTo()
and

curveTo()
methods until you call the

lineStyle()
method with different

parameters.
16
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Method
Description
lineTo
(x:Number, y:Number) : Void
Draws a line using the current line style

from the current drawing position to (x, y);

the current drawing position is then set to

(x, y).
moveTo
(x:Number, y:Number) : Void
Moves the current drawing position to (x,

y).
Pour utiliser le beginGradientFill() voir ceci:
http://www.joshbuhler.com/tutorials/drawingAPI/gradientFill.html
Pour les méthodes d'advanced drawing de Ric Ewing:
http://www.adobe.com/devnet/flash/articles/adv_draw_methods.html
Other advanced drawing methods:
http://www.kssupply.net/curve_fit_etc.html
Filled Arcs (
http://mentalaxis.com/words/2005/02/
)
17
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Sample Advanced Drawing Methods
Méthode doArc
(par Martin Legris)
MovieClip.prototype.doArc = function(centerX:Number, centerY:Number,

radius:Number, startAngle:Number, arcSpan:Number, doMove:Boolean):Void
{
//trace("doArc(centerX:"+centerX+", centerY:"+centerY+", radius:"+radius+",

startAngle:"+startAngle+", arcSpan:"+arcSpan+")");
var cx:Number = 0;
var cy:Number = 0;
var theta:Number = 0;
var segs:Number = Math.ceil(Math.abs(arcSpan/45));
//trace("segs:"+segs);
var theta = (arcSpan / 180 * Math.PI) / segs;
var ctrlXRadius:Number = radius / Math.cos(Math.abs(theta/2));
var ctrlYRadius:Number = radius / Math.cos(Math.abs(theta/2));
//trace("theta:"+theta+", ctrlYRadius:"+ctrlYRadius+",

ctrlXRadius:"+ctrlXRadius);
var angleRadians = startAngle * Math.PI / 180;
var sx:Number = Math.cos(angleRadians)*radius + centerX;
var sy:Number = Math.sin(angleRadians)*radius + centerY;
if(doMove) {
this.moveTo(sx, sy);
}
if(segs > 0)
{
for(var i:Number = 0; i < segs; i++) {
var angleDebut:Number = angleRadians + i * theta;
var angleFin:Number = angleRadians + (i+1) * theta;
var destX:Number = Math.cos(angleFin)*radius + centerX;
var destY:Number = Math.sin(angleFin)*radius + centerY;
var cx:Number = Math.cos(angleFin - theta/2)*ctrlXRadius + centerX;
var cy:Number = Math.sin(angleFin - theta/2)*ctrlYRadius + centerY;
this.curveTo(cx, cy, destX, destY);
18
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
}
}
}
Méthode drawThickArc
(par Martin Legris)
MovieClip.prototype.drawThickArc = function(centerX:Number, centerY:Number,

radius:Number, startAngle:Number, arc:Number, thickness:Number):Void
{
// move pen to center
var outerRadius:Number = radius + thickness;
var endAngle:Number = startAngle + arc;
var radians:Number;
var xPos:Number;
var yPos:Number;
this.doArc(centerX, centerY, radius, startAngle, arc, true);
// draw line out to outer arc
radians = Math.PI / 180 * (startAngle + arc);
xPos = centerX + (radius + thickness) * Math.cos(radians);
yPos = centerY + (radius + thickness) * Math.sin(radians);
this.lineTo(xPos, yPos);
this.doArc(centerX, centerY, outerRadius, endAngle, -arc, false);
// draw line back to center arc
radians = Math.PI / 180 * startAngle;
xPos = centerX + radius * Math.cos(radians);
yPos = centerY + radius * Math.sin(radians);
this.lineTo(xPos, yPos);
}
Méthode squiglyLineTo
(par Martin Legris)
MovieClip.prototype.squiglyLineTo = function(startx, starty, endx, endy, len,

width) {
19
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
// ==============
//
// mc.squiglyLineTo() - by Martin Legris (mlegris@newcommerce.ca) version

1.0 - 15.08.2006
//
// built on top of :
// mc.dashTo() - by Ric Ewing (ric@formequalsfunction.com) - version 1.2 -

5.3.2002
//
// startx, starty = beginning of dashed line
// endx, endy = end of dashed line
// len = length of dash
// width = the maximum distance of the squiggles
// ==============
//
// if too few arguments, bail
if (arguments.length < 6) {
return false;
}
// init vars
var halfLengthX, halfLengthY, segs, cx, cy, radians, deltaX, deltaY, delta;
// calculate the length of the dashed line
deltaX = endx - startx;
deltaY = endy - starty;
delta = Math.sqrt((deltaX * deltaX) + (deltaY * deltaY));
// calculate the number of segments needed
segs = Math.floor(Math.abs(delta / len));
// get the angle of the line in radians
radians = Math.atan2(deltaY,deltaX);
// start the line here
cx = startx;
cy = starty;
// add these to cx, cy to get next seg start
deltaX = Math.cos(radians)*len;
deltaY = Math.sin(radians)*len;
halfLengthX = deltaX / 2;
halfLengthY = deltaY / 2;
// loop through each seg
20
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
for (var n = 0; n < segs; n++) {
var lclAngle = n*-1*Math.PI/2 + radians;
var lclWidth = Math.random()*(width-0.5)+0.5;
var ctrlX:Number = Math.sin(lclAngle)*lclWidth + cx + halfLengthX;
var ctrlY:Number = Math.cos(lclAngle)*lclWidth + cy + halfLengthY;
this.moveTo(cx,cy);
this.curveTo(ctrlX, ctrlY, cx + deltaX, cy + deltaY);
cx += deltaX;
cy += deltaY;
}
// handle last segment as it is likely to be partial
this.moveTo(cx,cy);
delta = Math.sqrt((endx-cx)*(endx-cx)+(endy-cy)*(endy-cy));
if(delta>len){
// segment ends in the gap, so draw a full dash
this.lineTo(cx+Math.cos(radians)*len,cy+Math.sin(radians)*len);
} else if(delta>0) {
// segment is shorter than dash so only draw what is needed
this.lineTo(cx+Math.cos(radians)*delta,cy+Math.sin(radians)*delta);
}
// move the pen to the end position
this.moveTo(endx,endy);
};
Méthode drawSquiglyRect
(par Martin Legris)
MovieClip.prototype.drawSquiglyRect = function(x, y, w, h, cornerRadius, len,

width) {
// ==============
// mc.drawSquiglyRect() - by Martin Legris (mlegris@newcommerce.ca) -

version 1.0 - 15.08.2006
//
// based on:
// mc.drawRect() - by Ric Ewing (ric@formequalsfunction.com) - version 1.1 -

4.7.2002
//
// x, y = top left corner of rect
// w = width of rect
// h = height of rect
// cornerRadius = [optional] radius of rounding for corners (defaults to 0)
21
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
// ==============
if (arguments.length<4) {
return;
}
// if the user has defined cornerRadius our task is a bit more complex. :)
if (cornerRadius>0) {
// init vars
var theta, angle, cx, cy, px, py;
// make sure that w + h are larger than 2*cornerRadius
if (cornerRadius>Math.min(w, h)/2) {
cornerRadius = Math.min(w, h)/2;
}
// theta = 45 degrees in radians
theta = Math.PI/4;
// draw top line
this.squiglyLineTo(x+cornerRadius, y, x+w-cornerRadius, y, len, width);
//angle is currently 90 degrees
angle = -Math.PI/2;
// draw tr corner in two parts
cx = x+w-
cornerRadius+(Math.cos(angle+(theta/2))*cornerRadius/Math.cos(theta/2));
cy =

y+cornerRadius+(Math.sin(angle+(theta/2))*cornerRadius/Math.cos(theta/2));
px = x+w-cornerRadius+(Math.cos(angle+theta)*cornerRadius);
py = y+cornerRadius+(Math.sin(angle+theta)*cornerRadius);
this.curveTo(cx, cy, px, py);
angle += theta;
cx = x+w-
cornerRadius+(Math.cos(angle+(theta/2))*cornerRadius/Math.cos(theta/2));
cy =

y+cornerRadius+(Math.sin(angle+(theta/2))*cornerRadius/Math.cos(theta/2));
px = x+w-cornerRadius+(Math.cos(angle+theta)*cornerRadius);
py = y+cornerRadius+(Math.sin(angle+theta)*cornerRadius);
this.curveTo(cx, cy, px, py);
// draw right line
this.squiglyLineTo(px, py, x+w, y+h-cornerRadius, len, width);
//this.lineTo(x+w, y+h-cornerRadius);
// draw br corner
angle += theta;
cx = x+w-
cornerRadius+(Math.cos(angle+(theta/2))*cornerRadius/Math.cos(theta/2));
cy = y+h-
cornerRadius+(Math.sin(angle+(theta/2))*cornerRadius/Math.cos(theta/2));
22
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
px = x+w-cornerRadius+(Math.cos(angle+theta)*cornerRadius);
py = y+h-cornerRadius+(Math.sin(angle+theta)*cornerRadius);
this.curveTo(cx, cy, px, py);
angle += theta;
cx = x+w-
cornerRadius+(Math.cos(angle+(theta/2))*cornerRadius/Math.cos(theta/2));
cy = y+h-
cornerRadius+(Math.sin(angle+(theta/2))*cornerRadius/Math.cos(theta/2));
px = x+w-cornerRadius+(Math.cos(angle+theta)*cornerRadius);
py = y+h-cornerRadius+(Math.sin(angle+theta)*cornerRadius);
this.curveTo(cx, cy, px, py);
// draw bottom line
this.squiglyLineTo(px, py, x+cornerRadius, y+h, len, width);
//this.lineTo(x+cornerRadius, y+h);
// draw bl corner
angle += theta;
cx =

x+cornerRadius+(Math.cos(angle+(theta/2))*cornerRadius/Math.cos(theta/2));
cy = y+h-
cornerRadius+(Math.sin(angle+(theta/2))*cornerRadius/Math.cos(theta/2));
px = x+cornerRadius+(Math.cos(angle+theta)*cornerRadius);
py = y+h-cornerRadius+(Math.sin(angle+theta)*cornerRadius);
this.curveTo(cx, cy, px, py);
angle += theta;
cx =

x+cornerRadius+(Math.cos(angle+(theta/2))*cornerRadius/Math.cos(theta/2));
cy = y+h-
cornerRadius+(Math.sin(angle+(theta/2))*cornerRadius/Math.cos(theta/2));
px = x+cornerRadius+(Math.cos(angle+theta)*cornerRadius);
py = y+h-cornerRadius+(Math.sin(angle+theta)*cornerRadius);
this.curveTo(cx, cy, px, py);
// draw left line
this.squiglyLineTo(px, py, x, y+cornerRadius, len, width);
//this.lineTo(x, y+cornerRadius);
// draw tl corner
angle += theta;
cx =

x+cornerRadius+(Math.cos(angle+(theta/2))*cornerRadius/Math.cos(theta/2));
cy =

y+cornerRadius+(Math.sin(angle+(theta/2))*cornerRadius/Math.cos(theta/2));
px = x+cornerRadius+(Math.cos(angle+theta)*cornerRadius);
py = y+cornerRadius+(Math.sin(angle+theta)*cornerRadius);
this.curveTo(cx, cy, px, py);
angle += theta;
23
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
cx =

x+cornerRadius+(Math.cos(angle+(theta/2))*cornerRadius/Math.cos(theta/2));
cy =

y+cornerRadius+(Math.sin(angle+(theta/2))*cornerRadius/Math.cos(theta/2));
px = x+cornerRadius+(Math.cos(angle+theta)*cornerRadius);
py = y+cornerRadius+(Math.sin(angle+theta)*cornerRadius);
this.curveTo(cx, cy, px, py);
} else {
// cornerRadius was not defined or = 0. This makes it easy.
this.squiglyLineTo(x, y, x+w, y, len, width);
//this.moveTo(x, y);
//this.lineTo(x+w, y);
this.squiglyLineTo(x+w, y, x+w, y+h, len, width);
//this.lineTo(x+w, y+h);
this.squiglyLineTo(x+w, y+h, x, y+h, len, width);
//this.lineTo(x, y+h);
this.squiglyLineTo(x, y+h, x, y, len, width);
//this.lineTo(x, y);
}
};
24
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
SharedObject
Le SharedObject est l'équivalent d'un Cookie spécifique à Flash.
Propriétées
Propriétés
Description
data
:Object
The collection of attributes assigned to the

data
property of the object; these

attributes can be shared and/or stored.
Méthodes
Signature
Description
clear
() : Void
Purges all the data from the shared object

and deletes the shared object from the

disk.
flush
([minDiskSpace:Number]) : Object
Object
Immediately writes a locally persistent

shared object to a local file.
Static
getLocal
(name:String,

[localPath:String],

[secure:Boolean]) : SharedObject
Returns a reference to a locally persistent

shared object that is available only to the

current client.
getSize
() : Number
Gets the current size of the shared object,

in bytes.
Exemple
// pour stocker
var so:SharedObject = SharedObject.getLocal(“as20”);
so.data[“nom”] = “Richard”;
so.data[“location”] = “Montréal”;
so.flush();
// pour récupérer
var so:SharedObject = SharedObject.getLocal(“as20”);
trace(“nom:”+so.data[“nom”]);
trace(“location:”+so.data[“location”]);
25
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Tutoriel
http://www.actionscript.org/resources/articles/118/1/SharedObjects/Page1.html
par Jesse Stratford
26
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Gestion des erreurs

Pas de runtime errors en Javascript

Try, Catch, Exception

Pourquoi Flash ne lance pas d'exceptions?

Voir Appendice B
27
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
MovieClipLoader

On crée un MovieClipLoader pour faire un suivit plus précis du processus de loading

des movieclips externes ou d'images .JPEG

On peut ajouter des 'listener' à un MovieClipLoader, en fait autant qu'on en veut. Ils

doivents implémenter au moins une des fonctions suivantes
Event
Description
onLoadComplete
=

function([target_mc:MovieClip],

[httpStatus:Number]) {}
Invoked when a file that was loaded with

MovieClipLoader.loadClip()
is

completely downloaded.
onLoadError
=

function(target_mc:MovieClip,

errorCode:String,

[httpStatus:Number]) {}
Invoked when a file loaded with

MovieClipLoader.loadClip()
has failed to

load.
onLoadInit
=

function([target_mc:MovieClip]) {}
Invoked when the actions on the first frame

of the loaded clip have been executed.
onLoadProgress
=

function([target_mc:MovieClip],

loadedBytes:Number,

totalBytes:Number) {}
Invoked every time the loading content is

written to the hard disk during the loading

process (that is, between

MovieClipLoader.onLoadStart
and

MovieClipLoader.onLoadComplete
).
onLoadStart
=

function([target_mc:MovieClip]) {}
Invoked when a call to

MovieClipLoader.loadClip()
has begun

to download a file.

Les fonctions sont les suivantes:
Signature
Description
addListener
(listener:Object) : Boolean
Registers an object to receive notification

when a
MovieClipLoader
event handler is

invoked.
getProgress
(target:Object) : Object
Returns the number of bytes loaded and

the total number of bytes of a file that is

28
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Signature
Description
being loaded by using

MovieClipLoader.loadClip()
; for

compressed movies, returns the number of

compressed bytes.
loadClip
(url:String, target:Object) :

Boolean
Loads a SWF, JPEG, progressive JPEG,

unanimated GIF, or PNG file into a movie

clip in Flash Player while the original movie

is playing.
removeListener
(listener:Object) :

Boolean
Removes the listener that was used to

receive notification when a

MovieClipLoader
event handler was

invoked.
unloadClip
(target:Object) : Boolean
Removes a movie clip that was loaded by

using
MovieClipLoader.loadClip()
.
Tutoriel

http://www.senocular.com/flash/tutorials/preloading/
29
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Exemple 2 – Preloader
Cet exemple démontre l'utilisation de certaines fonctions du drawing API, du

MovieClipLoader ainsi que la fonction OnEnterFrame. C'est un diaporama avec un

preloader. Il suffit de mettre tout le code sur le premier frame du .FLA. Ensuite créez sur

un autre layer 2 champs textes. Nommer les instances comme suit:

speedLbl (contiendra la vitesse du téléchargement en kb/s)

percentLbl (contiendra le pourcentage du téléchargement)
L'exemple dépend du package appelé 'Laco Tweening Engine'. Il doit être downloadé et

installé avant d'entreprendre l'exercise. (
http://laco.wz.cz/tween
)
#include "lmc_tween.as"
stop();

arProgress sert à stocker le progrès du téléchargement de chaque image (0 à 100)

arBytes sert à stocker les nombres de bytes téléchargées pour chaque image

arImages est un array qui contient le nom (url) des images

mcl est le MovieClipLoader
// INITIALISATION
var arProgress:Array = new Array();
var arBytes:Array = new Array();
var arImages:Array = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"];
var mcl:MovieClipLoader = new MovieClipLoader();
- cette boucle crée les movieclips qui contiendront les images un fois loadé, utilise le

MovieClipLoader pour le chargement des images, et initialise arProgress[n] et

arBytes[n] à 0.
for(var i:Number = 0; i < arImages.length; i++)
{
arProgress[i] = 0; // tend vers 100
arBytes[i] = 0;
var image:MovieClip = createEmptyMovieClip("image"+i,
getNextHighestDepth());
mcl.loadClip(arImages[i], image); //this['images'+i]);
//var progress:Object = mcl.getProgress(image);
//trace("bytesLoaded:"+progress.bytesLoaded+",
30
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
bytesTotal:"+progress.bytesTotal);
}
- Ici on initialise une variable de type Date pour permettre de calculer la vitesse du

téléchargement.
// TEMPS
var now:Date = new Date();
var initTime:Number = now.getTime();
- Des petits calculs pour déterminer les dimensions et la position de la barre de

progrès.
// DIMENSIONS DE LA PROGRESS BAR
var lclX:Number = (Stage.width - Stage.width/4) / 2;
var lclWidth:Number = Stage.width/4;
var lclY:Number = Stage.height/2;
var lclHeight:Number = 7;
trace("lclX:"+lclX+", lclWidth:"+lclWidth+", lclY:"+lclY+", lclHeight:"+lclHeight);
- Une petite fonction qui permet de déterminer si toutes les images ont étés

téléchargées.
function checkLoaded():Boolean
{
var loaded:Boolean = true;
for(var i:Number = 0; i < arProgress.length; i++)
{
loaded &= (arProgress[i] == 100);
}
return loaded;
}
- Une fonction qui calcule le pourcentage de téléchargement global, avec une

pondération égale entre les images (qui ne tient pas compte de la taille de chacune

puisque cette taille n'est pas disponible pour les images qui n'ont pas encore débuté

le téléchargement). Pour faire une fonction plus précise il faudrait connaître la taille

des images avant de débuter le téléchargement des images.
function calcPercent():Number {
31
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
var total:Number = 0;
for(var i:Number = 0; i < arProgress.length; i++)
total += arProgress[i];
total /= arProgress.length;
return total;
}
- Une fonction qui retourne le nombre d'octets téléchargés jusqu'à maintenant.
function calcBytes():Number
{
var total:Number = 0;
for(var i:Number = 0; i < arBytes.length; i++)
total += arBytes[i];
return total;
}
- La fonction appelé par le MovieClipLoader sur chaque 'listeners' qui sont enregistrés.

Elle met à jour le tableau du progrès de téléchargement ainsi que celui des octets.
function onLoadProgress(target:MovieClip, bytesLoaded:Number,

bytesTotal:Number):Void
{
//trace("onLoadProgress("+target+","+bytesLoaded+","+bytesTotal+")");
//trace(target._target);
//trace(target._name);
var index:Number = parseInt(target._name.substr(5, 1));
arProgress[index] = bytesLoaded/bytesTotal * 100;
trace("loaded at :"+arProgress[index]+"%");
arBytes[index] = bytesLoaded;
}
- La fonction appelé par le MovieClipLoader quand le téléchargement échoue.
function onLoadError(target:MovieClip, errorCode:String,

httpStatus:Number):Void
{
trace("onLoadError("+target+","+errorCode+","+httpStatus+")");
}
32
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
- La fonction appelé par le MovieClipLoader une fois que le MovieClip a loadé et a été

initialisé.
function onLoadInit(target:MovieClip):Void
{
trace("onLoadInit("+target+")");
target._alpha = 0;
target._visible = true;
trace("allLoaded:"+checkLoaded());
}
- Ici on rajoute l'objet _root à la liste des listeners du movieclip loader.
mcl.addListener(this);
- Cette fonction est appelé chaque fois que flash entre dans un nouveau frame. Le

rythme dépend du frame-rate choisis. En premier lieu on met à jour les champs de

texte (speedLbl et percentLbl). Ensuite on re-dessine la barre de progrès. Et par la

suite on fait un test voir si tout est loadé, si oui on désactive notre fonction

onEnterFrame.
onEnterFrame = function(){
var percent:Number = calcPercent();
now = new Date();
var nowTime:Number = now.getTime();
var elapsed:Number = nowTime - initTime;
var speed:Number = calcBytes() / elapsed;
speedLbl.text = Math.round(speed) + "kb/s";
percentLbl.text = Math.round(percent) + "%";
clear();
lineStyle(0, 0xAAAAAA);
drawRect(lclX, lclY, lclWidth, lclHeight);
lineStyle(0, 0xCCCCCC);
beginFill(0xCCCCCC);
drawRect(lclX+2, lclY+2, (lclWidth-4) * percent / 100, (lclHeight-4));
endFill();
33
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
if(percent == 100)
{
delete onEnterFrame;
allLoaded();
}
}
- la fonction a appelé lorsque tout est loadé. Elle va cacher les champs de texte et

partir l'animation.
function allLoaded():Void
{
trace("allLoaded");
clear();
speedLbl._visible = false;
percentLbl._visible = false;
// the exposition delay for each image
var delay:Number = 5;
for(var i:Number = 0; i < arImages.length; i++)
{
trace("doing:"+this['image'+i]);
// make the image appear
this['image'+i].alphaTo(100, 1, 'easeoutCirc', (delay+1)*i,
{startfunc:"hasApeared", startscope:this, startargs:[i],
updfunc:"isShowing", updscope:this, updargs:[i]});
// make the image disappear
this['image'+i].alphaTo(0, 1, 'easeoutCirc', (delay+1)*i + delay,
{func:"hasDisapeared", scope:this, args:[i]});
}
}
- cette fonction est appelé chaque fois que l'alpha d'une image est mis-à-jour par

l'engin de tweening, dans la progression positive.
function isShowing(index:Number):Void
{
trace("image"+index+" is at alpha:"+this['image'+index]._alpha);
}
34
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
- Cette fonction est appelé lorsque l'image a disparut. Par l'engin de tweening lorsque

le tween vers alpha=0 est terminé.
function hasDisapeared(index:Number):Void
{
trace("image"+index+" hasDisappeared");
}
- cette fonction est appelé par l'engin de tweening lorsque le premier des 2 tweens

(vers alpha=100) débute.
function hasApeared(index:Number):Void
{
trace("image"+index+" hasApeared");
}
35
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Exemple 3 – Utilisation du Custom Easing Tool
Custom Easing Tool
Voici le custom easing tool, disponible avec le «

Laco Tweening Engine

» et le «

Fuse

Kit

». Il se retrouve dans le menu 'Window / Other Panels / custom easing Tool' dans

Flash.
1.
Sert à visualiser les 'presets' ou en sauver des nouveaux.
2.
Ici vous pouvez manipuler les points gris avec la souris, en les déplaçant de haut-
en-bas.
36
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
3.
Pour augmenter le nombre de segments ou le diminuer (notez que vous perdrez

vos manipulations sur les points).
4.
Une fois que vous êtes satisfaits avec votre effet de transition, vous pouvez

générer un 'easing object' que vous devez copier-coller dans votre code et l'utiliser

dans le paramètre 'animType'.
5.
Est utilisé pour les animateurs pour générer les keyframes d'une animation.
Exemple d'utilisation

cet exemple utilise le 'Laco Tweening Engine' à nouveau.

(
http://laco.wz.cz/tween
)

Il faut créer un object dans la librairie qu'on glissera sur le stage et nommer cet

instance 'cercle'. Il est préférable que l'objet ne contienne qu'une seule couleur.
#include "lmc_tween.as"
- voici un exemple de code d'un 'easing object'. Il y a des points accompagnés d'une

fonction.
customEasing = {};
customEasing.pts = [{Mx:0,My:0,Nx:52,Ny:84,Px:-23.45,Py:-
112.55},{Mx:28.55,My:-28.55,Nx:30.9,Ny:-176.9,Px:-
3.45,Py:200.45},{Mx:56,My:-5,Nx:56,Ny:-28,Px:-28,Py:-114},{Mx:84,My:-
147,Nx:20,Ny:-146,Px:10.25,Py:178.75},{Mx:114.25,My:-
114.25,Nx:55.5,Ny:94.5,Px:-26.9,Py:-123.1},{Mx:142.85,My:-142.85,Nx:-
1.69999999999999,Ny:-180.3,Px:30.25,Py:151.75},{Mx:171.4,My:-
171.4,Nx:57.2,Ny:146.8,Px:-28.6,Py:-175.4},{Mx:200, My:-200}];
customEasing.ease = function(t,b,c,d,pl){
var i,r;
r = 200 * t/d;
for(i = 0;r>pl[i+1].Mx;i++){
}
i=pl[i];
if(i.Px != 0){
r=(-i.Nx+Math.sqrt(i.Nx*i.Nx-4*i.Px*(i.Mx-r)))/(2*i.Px);
}else{
r=-(i.Mx-r)/i.Nx;
}
return b-c*((i.My+i.Ny*r+i.Py*r*r)/200);
}
- Dans le premier appel et le troisième on utilise le 'easing object' définit ci-haut.
37
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
cercle.slideTo(5, 5, 1,customEasing);
cercle.alphaTo(30, 1, "easeOutElastic", 1);
cercle.colorTo(0x0000FF, 2, customEasing);
38
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Delegate
Le delegate permet de stocker une fonction et son contexte dans une autre fonction. Ce

qui permet d'exécuter une fonction à l'intérieur du contexte désiré à partir de n'importe

quel object.
Exemple d'utilisation
import mx.utils.Delegate;
var car:Object = {length:30, color:”red”};
car.changeColor() = function():Void{
this.color = “blue”;
trace(“the car's color is now:”+this.color);
}
_root.onRelease = Delegate.create(car, car.changeColor);
Tutoriel
http://www.actionscript.org/resources/articles/205/1/The-Delegate-Class/Page1.html
par Patrick Mineault
39
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
EventDispatcher
Méthodes
Signature
Description
Static initialize(object:Object)
Initializes an object so it can have event

listeners and broadcast events.
addEventListener(
event
,
listener
)
Registers a listener with a component

instance.
dispatchEvent
(
eventObject
)
Dispatches an event programmatically.
removeEventListener(
event
,
listener
)
Removes an event listener from a

component

instance.
Exemple d'utilisation
import mx.events.EventDispatcher;
class Component{
public var addEventListener:Function;
public var removeEventListener:Function;
private var dispatchEvent:Function;
public function Component()
{
EventDispatcher.initialize(this);
}
public function dispatchMyEvent(eventType:String, params:Array):Void
{
dispatchEvent({type:eventType, params:params, target:this});
}
}
public function onWelcome(eventObj:Object):Void
{
trace(“onWelcome fired from:”+eventObj.target+”, with

params:”+eventObj.params);
40
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
}
var comp:Component = new Component();
comp.addEventListener(“welcome”, Delegate.create(this, onWelcome));
comp.dispatchMyEvent(“welcome”, [“Sylvain”, “David”, “David”, “Charles”,

“Bogdan”]);
Tutoriel
http://www.actionscript.org/resources/articles/204/1/Using-EventDispatcher/Page1.html
par Patrick Mineault
41
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
ASBroadCaster
Méthodes
Signature
Description
addListener
(listenerObj:Object) :

Boolean
Registers an object to receive event

notification messages.
broadcastMessage
(eventName:String)

:Void
Sends an event message to each object in

the list of listeners.
initialize
(obj:Object) : Void
Adds event notification and listener

management functionality to a given

object.
removeListener
(listenerObj:Object) :

Boolean
Removes an object from the list of objects

that receive event notification messages.
Exemple d'utilisation
class SomeClass{
//declare functions that are used (but they need not be defined)
var broadcastMessage:Function;
var addListener:Function;
public function SomeClass(){ AsBroadcaster.initialize(this); }
public function someFunction(){ this.broadcastMessage("onSomething"); }
}
//and then outside the class
var myClassInstance:SomeClass = new SomeClass();
var myListener:Object = new Object();
myListener.onSomething = function(){
trace( "onSomething function event called" );
}
myClassInstance.addListener( myListener );
myClassInstance.someFunction();
Tutoriel
http://www.actionscript.org/resources/articles/126/1/Flash-Broadcasters-and-
Listeners/Page1.html
par
Ka Wai Cheung
42
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Dynamic Registration
(
http://www.darronschall.com/weblog/archives/000054.cfm
)
Méthodes
Signature
Description
static initialize(mc:MovieClip):Void
Initialized (decorates) a movie clip with the

dynamic registration's properties and

functions.
Public setRegistration(x:Number,

y:Number):Void
Set the new registration point.
Propriétés
Propriété
Description
public var _x2:Number
Equivalent of _x but based on the dynamic

registration point
public var _y2:Number
Equivalent of _y but based on the dynamic

registration point
public var _rotation2:Number
Equivalent of _rotation but based on the

dynamic registration point
public var _yscale2:Number
Equivalent of _yscale but based on the

dynamic registration point
public var _xscale2:Number
Equivalent of _xscale but based on the

dynamic registration point
public var _xmouse2:Number [read-only]
Equivalent of _xmouse but based on the

dynamic registration point
public var _xmouse2:Number [read-only]
Equivalent of _xmouse but based on the

dynamic registration point
Exemple d'utilisation
import com.darronschall.DynamicRegistration;
// Assume there is an instance named square_mc on the stage
var square_mc:MovieClip;
// updated 7/28/05 - add the dynamic registration stuff at runtime to our square

43
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
movieclip
DynamicRegistration.initialize(square_mc);
// The square_mc has an original registration at 0,0 so
// let's change that to 10, 60 at runtime.
square_mc.setRegistration(10, 60);
// Now whenever we access a property of the square_mc that deals
// with the registration point, use a "2" after the property name...
// These are the available properties:
square_mc._x2 = 4;
square_mc._y2 = 7;
square_mc._rotation2 = 40;
square_mc._xscale2 = 140;
square_mc._yscale2 = 80;
// square_mc._xmouse2 is readonly
// square_mc._ymouse2 is readonly
44
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
setInterval
La fonction setInterval permet d'exécuter une action de façon répétitive sur un interval

définit. Elle complémente la fonction OnEnterFrame.
Signature
setInterval (
functionReference:Function
,
interval:Number
, [
param1:Object
,

param2
, ...,
paramN
])
: Number
OU
setInterval (
objectReference:Object, methodName:String
,
interval:Number
,

[
param1:Object
,
param2
, ...,
paramN
])
: Number
Exemple
var intervalId:Number;
var count:Number = 0;
var maxCount:Number = 10;
var duration:Number = 20;
function executeCallback():Void {
trace("executeCallback intervalId: " + intervalId + " count: " + count);
if(count >= maxCount) {
clearInterval(intervalId);
}
count++;
}
intervalId = setInterval(this, "executeCallback", duration);
Tutoriel
http://www.actionscript.org/resources/articles/120/1/Intervals-in-Flash-with-
setInterval/Page1.html
par Jesse Stratford
45
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Loading MovieClips & Images

You can load MovieClips into your Flash Movie as long as it's enabled into it's settings.

Flash 8 will read JPEG's (non progressive), PNG's & GIF's.
46
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Propriétés d'un TextField
Les propriétés d'un TextField créé par createTextField sont:
type = "dynamic"
border = false
background = false
password = false
multiline = false
html = false
embedFonts = false
selectable = true
wordWrap = false
mouseWheelEnabled = true
condenseWhite = false
restrict = null
variable = null
maxChars = null
styleSheet = undefined
tabInded = undefined
A text field created with
createTextField()
receives the following default TextFormat

object settings:
font = "Times New Roman" // "Times" on Mac OS
size = 12
color = 0x000000
bold = false
italic = false
underline = false
url = ""
target = ""
align = "left"
leftMargin = 0
rightMargin = 0
indent = 0
leading = 0
blockIndent = 0
bullet = false
display = block
47
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
tabStops = [] // (empty array)
Les propriétés d'un objet Textfield
Property
Description
_alpha
:Number
Sets or retrieves the alpha transparency

value of the text field.
antiAliasType
:String
The type of anti-aliasing used for this

TextField instance.
autoSize
:Object
Controls automatic sizing and alignment of

text fields.
background
:Boolean
Specifies if the text field has a background

fill.
backgroundColor
:Number
The color of the text field background.
border
:Boolean
Specifies if the text field has a border.
borderColor
:Number
The color of the text field border.
bottomScroll
:Number
[read-only]
An integer (one-based index) that indicates

the bottommost line that is currently visible

the text field.
condenseWhite
:Boolean
A Boolean value that specifies whether

extra white space (spaces, line breaks, and

so on) in an HTML text field should be

removed when the field is rendered in a

browser.
embedFonts
:Boolean
Specifies whether to render using

embedded font outlines.
filters
:Array
An indexed array containing each filter

object currently associated with the text

field.
gridFitType
:String
The type of grid fitting used for this

TextField instance.
_height
:Number
The height of the text field in pixels.
hscroll
:Number
Indicates the current horizontal scrolling

48
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Property
Description
position.
html
:Boolean
A flag that indicates whether the text field

contains an HTML representation.
htmlText
:String
If the text field is an HTML text field, this

property contains the HTML representation

of the text field's contents.
length
:Number
[read-only]
Indicates the number of characters in a

text field.
maxChars
:Number
Indicates the maximum number of

characters that the text field can contain.
maxhscroll
:Number
[read-only]
Indicates the maximum value of

TextField.hscroll
.
maxscroll
:Number
[read-only]
Indicates the maximum value of

TextField.scroll
.
menu
:ContextMenu
Associates the ContextMenu object

contextMenu
with the text field
my_txt
.
mouseWheelEnabled
:Boolean
A Boolean value that indicates whether

Flash Player should automatically scroll

multiline text fields when the mouse

pointer clicks a text field and the user rolls

the mouse wheel.
multiline
:Boolean
Indicates whether the text field is a

multiline text field.
_name
:String
The instance name of the text field.
_parent
:MovieClip
A reference to the movie clip or object that

contains the current text field or object.
password
:Boolean
Specifies whether the text field is a

password text field.
_quality
:String
The rendering quality used for a SWF file.
restrict
:String
Indicates the set of characters that a user

may enter into the text field.
49
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Property
Description
_rotation
:Number
The rotation of the text field, in degrees,

from its original orientation.
scroll
:Number
A Boolean value that indicates whether the

text field is selectable.
sharpness
:Number
The sharpness of the glyph edges in this

TextField instance.
styleSheet
:StyleSheet
Attaches a style sheet to the text field.
tabEnabled
:Boolean
Specifies whether the text field is included

in automatic tab ordering.
tabIndex
:Number
Lets you customize the tab ordering of

objects in a SWF file.
_target
:String
[read-only]
The target path of the text field instance.
text
:String
Indicates the current text in the text field.
textColor
:Number
Indicates the color of the text in a text

field.
textHeight
:Number
Indicates the height of the text.
textWidth
:Number
Indicates the width of the text.
thickness
:Number
The thickness of the glyph edges in this

TextField instance.
type
:String
Specifies the type of text field.
_url
:String
[read-only]
Retrieves the URL of the SWF file that

created the text field.
variable
:String
The name of the variable that the text field

is associated with.
_visible
:Boolean
A Boolean value that indicates whether the

text field
my_txt
is visible.
_width
:Number
The width of the text field, in pixels.
wordWrap
:Boolean
A Boolean value that indicates if the text

field has word wrap.
50
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Property
Description
_x
:Number
An integer that sets the x coordinate of a

text field relative to the local coordinates of

the parent movie clip.
_xmouse
:Number
[read-only]
Returns the x coordinate of the mouse

position relative to the text field.
_xscale
:Number
Determines the horizontal scale of the text

field as applied from the registration point

of the text field, expressed as a

percentage.
_y
:Number
The y coordinate of a text field relative to

the local coordinates of the parent

movieclip.
_ymouse
:Number
[read-only]
Indicates the y coordinate of the mouse

position relative to the text field.
_yscale
:Number
The vertical scale of the text field as

applied from the registration point of the

text field, expressed as a percentage.
Pour utiliser une police embedded
Créer un nouveau symbole pour la dite police. Lui donner un nom de 'linkage' en

ActionScript. Et ensuite changer la propriété .embedFont du textField.
Propriétés d'un police 'embedded'
On doit choisir la variation de la police dans le symbole de la librairie. C'est l'endroit ou

on choisit si la police est en gras et ou italique (ou pas). Lorsqu'on utilise une police

'embedded' la manipulation de ses propriétés par l'object TextFormat (de l'italic et bold)

n'auront aucun effet.
De plus, si vous désirez manipuler le canal alpha de votre texte, vous devez utiliser une

police 'embedded'. Seuls les textfield qui utilisent une police embedded peuvent être

semi-transparente. Les autres sont soit opaque ou invisible.
Les propriétés de l'objet TextFormat
Property
Description
align
:String
A string that indicates the alignment of the

paragraph.
51
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Property
Description
blockIndent
:Number
A number that indicates the block

indentation in points.
bold
:Boolean
A Boolean value that specifies whether the

text is boldface.
bullet
:Boolean
A Boolean value that indicates that the text

is part of a bulleted list.
color
:Number
Indicates the color of text.
font
:String
The name of the font for text in this text

format, as a string.
indent
:Number
An integer that indicates the indentation

from the left margin to the first character in

the paragraph.
italic
:Boolean
A Boolean value that indicates whether text

in this text format is italicized.
kerning
:Boolean
A Boolean value that indicates whether

kerning is enabled or disabled.
leading
:Number
An integer that represents the amount of

vertical space in pixels (called
leading
)

between lines.
leftMargin
:Number
The left margin of the paragraph, in points.

letterSpacing
:Number
The amount of space that is uniformly

distributed between characters.
rightMargin
:Number
The right margin of the paragraph, in

points.
tabStops
:Array
Specifies custom tab stops as an array of

non-negative integers.
target
:String
Indicates the target window where the

hyperlink is displayed.
underline
:Boolean
A Boolean value that indicates whether the

text that uses this text format is underlined

(
true
) or not (
false
).
url
:String
Indicates the URL that text in this text

format hyperlinks to.
52
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
Le Constructeur de TextFormat
TextFormat
([font:String], [size:Number], [color:Number],

[bold:Boolean], [italic:Boolean], [underline:Boolean], [url:String],

[target:String], [align:String], [leftMargin:Number],

[rightMargin:Number], [indent:Number], [leading:Number])
Les fonctions qui utilisent le TextFormat
Methods
Signature
TextField.setTextFormat
public

setTextFormat([beginIndex:Number],

[endIndex:Number],

textFormat:TextFormat) : Void
TextField.getTextFormat
public

getTextFormat([beginIndex:Number],

[endIndex:Number]) : TextFormat
Tutoriel
http://www.actionscript.org/resources/articles/59/1/Using-pixel-fonts/Page1.html
53
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
FuseKit
Installation
Vous trouverez tout le nécessaire ici :
http://www.mosessupposes.com/Fuse
Premier Tutoriel
http://www.gotoandlearn.com
, choisir le tutoriel: Animating with Fuse.
Exemple simpliste
import com.mosesSupposes.Fuse.*;
ZigoEngine.register(Shortcuts, PennerEasing);
ZigoEngine.initialize(ball);
ball.slideTo(200, 300, 0.5, 'easeoutCirc');
Définition
La signature des fonctions dites 'shortcut' (ZigoEngine)
http://laco.wz.cz/
MovieClip.tween()
Usage
my_mc.tween(property, pEnd, seconds, animType, delay, callback, extra1,

extra2)
Parameters
property
property(ies) to be tweened (string, array of strings)
pEnd
end property value(s) (number, array of numbers)
seconds
seconds to reach the end value, /duration of tween/ (number) defaults to

2

54
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
animType
animation equation type (string, function or object from custom easing

tool) defaults to "easeOutExpo"
string as animType
You can use following strings as types of animation (easing equations by Robert

Penner)
"linear",
"easeInQuad","easeOutQuad","easeInOutQuad","easeOutInQuad"
"easeInCubic","easeOutCubic","easeInOutCubic","easeOutInCubic"
"easeInQuart","easeOutQuart","easeInOutQuart","easeOutInQuart"
"easeInQuint","easeOutQuint","easeInOutQuint","easeOutInQuint"
"easeInSine","easeOutSine","easeInOutSine","easeOutInSine"
"easeInExpo","easeOutExpo","easeInOutExpo","easeOutInExpo"
"easeInCirc","easeOutCirc","easeInOutCirc","easeOutInCirc"
"easeInElastic","easeOutElastic","easeInOutElastic","easeOutInElastic"
"easeInBack","easeOutBack","easeInOutBack","easeOutInBack"
"easeInBounce","easeOutBounce","easeInOutBounce""easeOutInBounce"
Exemple
my_mc.tween("_x",100,3,"easeOutElastic")
Function as animType
you can use
easing function generator
from Timothee Groleau to generate your

function: e.g.:
waveEasing = function(t,b,c,d){
// ... code from generator
};
my_mc.tween("_x",100,3,waveEasing);

Object as animType
you can use custom easing tool from menu window->other panels ->custom

easing tool
55
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
object must have properties pts (list of control point),ease (function) e.g.:
customEasing = {};
// ... copy and paste here generated code
my_mc.tween("_x",100,3,customEasing);
*this easing is bit slower than previous two methods
delay
delay in seconds to start animation (number) defaults to 0
this parameter allows you create cool sequential tweens:
my_mc.('_x', 200,0.5);
my_mc.('_x', 400,0.5,'easeoutcirc',0.5)
my_mc.tween('_width', 300,1,'easeoutelastic',1)
;
my_mc.tween('_height', 300,1,'easeoutelastic',2);
my_mc.colorTo(0xFF0000,1,'easeinexpo',3);
callback
function to be called when finished (function or object with scope, func

and args or string)
function as callback
function onEnd(){
trace("onEnd");
}
my_mc.tween("_x",100,1,"linear",0,onEnd);
// scope of function is my_mc._parent
object as callback
You can pass as callback object with properties
func
- function to be called when tween is finished
scope
- scope of function (this in called function)
args
- array of arguments passed to function
updfunc
- reference to function to be called on every update
updscope
- scope of update function (this object)
updargs
- array of arguments passed to update function
startfunc
- reference to function to be called on start of tween
startscope
- scope of start function (this object)
startargs
- array of arguments passed to start function
56
/
127
New Commerce Solutions Incorporated – Formation AS2.0 Intermédiaire
* internal mechanism is:
func.apply(scope,args)
// on _root
game={};
game.players = ["john","steve"];
game.showScore = function(id, score){
trace("(this==_root.game) is "+(this==_root.game));
trace(this.players[id] + " has " + score + " points");
}
// somewhere in nested movieclip
var callback = {scope: _root.game, func: _root.game.showScore, args:[1,39]};
my_mc.tween("_x",100,1,"linear",0,callback);
/* or in 1 line:
my_mc.tween("_x",100,1,"linear",0,{scope: _root.game, func:

_root.game.showScore, args:[1,39]});
*/
//output after finishing tween:
(this==_root.game) is true
steve has 39 points
string as callback
callbacks can be too defined as strings
my_mc.tween("_x",100,1,"linear",0,'_root.gotoAndPlay(8)');
it is very problematic determine type of primitive parameters(number, string,