Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
3. Planificación de un Proyecto
1. Diseñar un diagrama organizacional del contenido del proyecto, que a la vez
representa la arquitectura del mismo.
2. Especifique las propiedades de la película: velocidad de reproducción (frame
rate), tamaño, color del documento Flash.
3. Para cada área del proyecto cree un keyframe en el Main Timeline, cada uno con
una etiqueta diferente. Una sola escena administra el diseño y desarrollo de la
película. O bien, cree escenas para cada área del proyecto.
4. Cree el contenido de cada área, puede iniciar con los elementos de navegación,
luego continuar con el contenido propiamente. Cree los símbolos que sean
necesarios para optimizar el tamaño de la aplicación.
Cuando se utiliza una sola escena en lugar de varias, se puede controlar mejor el diseño de la
plantilla de todo el proyecto. Aquellas instancias de símbolos que se comparten entre áreas se
pueden manejar más fácilmente.
Si cada parte del proyecto no comparte la misma plantilla entonces se podrá trabajar en
escenas diferentes con gran facilidad.
4. Probar y publicar
Cuando se utiliza Test Movie o Test Scene:
o En el menú View se puede activar Bandwith Profiler, permite simular la velocidad
descarga, y ver el recorrido del playhead.
5. ActionScript 2.0
ActionScript 2.0 es un lenguaje orientado a objetos que se ajusta a los estándares compilados en
ECMA-262 (estándar de programación derivado de JavaScript).
La sintaxis de ActionScript se denomina sintaxis dot (punto). Esto quiere decir que todas
las acciones son escritas dentro de una fórmula estándar que es comun dentro de los lenguajes
orientados a objetos:
Un event handler (manejador de eventos) es un mecanismo que le indica a Flash qué acción
ejecutar cuando ocurre un evento.
Pueder ser de tres clases
• Keystroke: Reconocen cuando se presiona una tecla
• Keyframe: Responden al avance de la línea de tiempo
• Button manipulation: Detectan la acción del mouse en instancias de botón. Los script se
colocan en las instancias del botón y no en su timeline
5.1.2. Eventos
5.1.3. Conductas
Las conductas controlan objetos: data, video, movieclip, sound, Web, media. Las conductas
se componen de acciones, se agregan a un event handler. Puede ser:
• Script automatizado: Se activan en Windows>Development Panel>Behavior
• Script escrito por el usuario: Se activa en Panel Actions
5.1.4. Script
For image files, Flash supports only the standard JPEG image file type, not progressive JPEG files.
When you use the global loadMovie() or loadMovieNum() function, specify the target level or clip as a
parameter. For example, the following code loads the Flash application contents.swf into the movie clip
instance named target_mc:
loadMovieNum("contents.swf", target_mc);
The following code loads the JPEG image flowers.jpg into the movie clip instance image_clip:
image_clip.loadMovie("flowers.jpg");
trace(message);
Envía un mensaje al panel Output en el Test Movie.
message - Cadena entre comillas, variable, expresión.
getTimer();
Devuelve el tiempo en milisegundos desde que la película inició su ejecución.
eval(variable);
El event handler on es de tipo Movie Clip Control, permite controlar los eventos del Mouse
y teclado que se describen más abajo.
Un script de frame no requiere un event handler específico. El event handler de keyframe
depende del playback de la película misma, y no del usuario. Las acciones asociadas a un
keyframe se ejecutan cuando el playhead entra al keyframe.
Procedimiento:
1. Crear un símbolo de tipo botón. Recuerde que los estados del botón son
importantes para que el usuario visualice como el botón responde a sus acciones. Es
importante el área hit, pues será el área activable por el mouse.
2. Colocar una instancia del botón en el escenario.
3. Seleccionar la instancia y agregar el código deseado. ¡Pruebe con los siguientes
ejemplos !
Ejemplos de script:
on (release) {
gotoAndPlay("escena2",1);
}
on (click) {
//Goto Webpage Behavior
Un ejemplo particular de botones, son los botones invisibles, solo tienen el estado Hit
definido. Con un botón invisible se puede convertir cualquier elemento Flash en un botón, para
ello se arrastra la instancia del botón encima del objeto. Recuerde que el código se anexa a la
instancia del botón.
Procedimiento:
1. Crear un símbolo de tipo botón, cuyos estados (up, over, down, hit) sean vacíos.
Si desea puede crear una pequeña area hit para poder visualizar la ubicación de su
instancia en el escenario, ésta área no se será visible por el usuario final, pero si será
activable. Al ser activable responde a los eventos del mouse, pero si no se escribe un
evento de mouse, al hacer clic sobre ella no ocurrirá ninguna acción.
2. Colocar una instancia del botón en el escenario.
3. Seleccionar la instancia y agregar el código deseado. ¡Pruebe con los siguientes
ejemplos !
Ejemplos de script:
on (keyPress "A") {
stopAllSounds();
stop();
}
on (keyPress "<Left>") {
trace ("Presionó la tecla izquierda");
}
on (keyPress "<Right>") {
gotoAndPlay("Scene 2",1);
}
En los eventos de teclado:
Dado que una película puede componerse de escenas y dentro de las escenas instancias de
símbolos, y dentro de un símbolo se puede tener otros símbolos anidados, entonces en Flash se
manejan varias líneas de tiempo en el mismo espacio y tiempo. Recuerde que la línea de tiempo
de un movie clip es independiente de la línea de tiempo principal, no así la línea de tiempo de un
símbolo gráfico.
En el manejo de la interactividad con Movie Clips esto es muy importante, porque se debe
saber cómo indicarle a Flash cuál Movie Clip se desea controlar, y para ello se utilizan las rutas.
Antes de entrar a ver las rutas propiamente, es importante tener presente que cada instancia
de Movie Clip (o símbolo) debe tener un nombre único en cualquier línea de tiempo.
Una ruta, indica la dirección de la instancia de un Movie Clip (a través del nombre de la
instancia) o variable. Puede ser absoluta o relativa.
• Uso:
– Ruta.action
– Ruta.variable
• Ruta Absoluta: Es la información de localización completa o destino de una instancia de
Movie Clip o variable desde cualquier otra localización. Se determina desde el main
timeline y termina con el nombre de la instancia en el timeline destino. Ejemplo: Se tiene
el timeline principal (main), desde allí se instancia un clip (clip_mc), y desde ése timeline
se instancia un gráfico (graf_gf).
– main
• clip_mc
• graf_gf
La ruta de main timeline se escribe: _root. Así la ruta absoluta de graf_gf sería:
_root.clip_mc.graf_gf
Observe que en la ruta se escriben los nombres de las instancias de los símbolos.
• Ruta Relativa: Es una ruta contextual de un timeline a otro. Desde el timeline de la
instancia actual hasta la instancia destino, es decir, se escribe desde la instancia que emite
la acción, pasando por el Main Timeline y termina con el nombre de la instancia destino.
_parent dirige la acción desde el timeline actual al timeline superior. Ejemplo:
– main
• clip1
o graf1
o graf2
• clip2
Ruta relativa desde clip1 hasta main: _parent
Ruta relativa desde clip1 hasta clip2: _parent.clip2
Ruta relativa desde graf1 hasta main: _parent._parent
Ruta relativa desde graf1 hasta clip2: _parent._parent.clip2
Ruta relativa arriba de la actual: this._parent
Ruta relativa actual: this
Usa la directiva #include para insertar archivos de texto externos (con extensión .as) que
contienen código de ActionScript. Cuando se publica el archivo .swf el contenido del archivo .as
se inserta a la lista de acciones. Si el archivo .as se modifica es necesario volver a publicar el
archivo .swf. Sintaxis: #include “name_file.as” este código se coloca en un keyframe, instancia
de botón onClipEvent. Permite reutilizar código y escribir código ActionScript en cualquier
editor.
5.9.1. Variables
• Es un nombre de espacio de almacenamiento de datos (números y letras) modificables.
Son tipadas, su valor es explicítamente configurado a uno de los tipos: cadena, numérico,
booleano, u objeto. El nombre no puede empezar con un número.
• Ayudan a crear atajos o alias de otros elementos del lenguaje. Por ejemplo almacenar una
ruta (URL, ruta absoluta o relativa de una instancia) en un nombre de variable, y hacer
referencia al nombre de la variable.
var serverURL= “http://www.up.ac.pa”;
getURL(serverURL)
var rutaToIris=_root.caraanim.ojoani.iris;
gotoAndPlay(rutaToIris)
• Se anexan a la línea de tiempo (timeline) de la película o instancia de MovieClip en la
cual se crea.
• Para acceder al valor de una variable sobre otra línea de tiempo, agregue al nombre de
la variable la ruta (absoluta o relativa) en la cual se creó.
• Escena1 En el timeline de la escena1 se pueden crear las variables a, b y
referenciar a la variable z creada en el timeline del movieClip1
var a=expr
var b=expr
_root.movieClip1_mc.z
o En el timeline del símbolo movieClip1 se puede crear la
movieClip1_mc variable z y referenciar a la variable b creada en la escena1.
var z=expr
_root.b //ruta absoluta
_parent.b //ruta relativa
• Escena2 En la escena2 se puede referenciar a la variable a creada en la
escena1
a=expr
• Declaración de variables:
var name;
• Variables como text fields: Un text field se puede utilizar como contenedor de texto
dinámico (Dinamic Text), cuyo contenido se puede actualizar vía ActionScript y/o la
intervención de un script del lado del servidor; o puede aceptar entrada del usuario (Input
text) . Un text field es un objeto TextField. En el inspector de propiedades se pueden
definir los parámetros del objeto texto: nombre de la instancia y nombre de la variable
(var), ambos deben ser diferentes.
o Input text: Es editable cuando la película se ejecuta. El texto escrito será el valor
del nombre de la variable del campo var, o la propiedad text de la instancia del
text field.
o Dynamic text: Es similar al input text.
o Procedimiento:
Crear el cuadro de texto con la herramienta texto.
En el inspector de propiedades del texto configurar
• Type Text –como Input Text o Dynamic Text.
• Escriba el nombre de la instancia del text field, agregue el sufijo
_txt
• var –escriba el nombre de la variable donde se guarda el contenido
del texto, agregue el sufijo _var.
• Activar Render Text as HTML si desea que se interpreten las
etiquetas HTML del texto.
• Activar Show border around text.
El contenido del cuadro de texto se puede escribir en un script-frame y
asignarlo a la variable especificada en el campo var. También es posible
referenciar al texto escrito por el usuario en un código.
Ejemplo:
En el nombre de la instancia del cuadro de texto
nombre_txt
En el campo var del inspector de propiedades
nombre_var
En el script-frame
nombre_txt.text="La vida es bella <br/> pero más hermoso es la fe en Dios"
nombre_var="La vida es bella <br/> pero más hermoso es la fe en Dios"
5.9.3. Expresiones
5.9.4. Operadores
o Operadores aritméticos: +, -, *,/
o Operador de concatenación de cadenas: +
o Operador de asignación: =
o Operadores lógicos: &&, ||, !
o Operadores de relación (aplican a cadenas y números): ==, !=, <, >, <=, >=, ===
(igualdad de tipo y valor), !== (no igual de tipo y valor)
o Operadores de acceso en arreglos: name_1 es equivalente a _root[“name_”+”1”] o a
_root[“name_”+i] donde i es una variable que vale 1.
5.9.5. Condicional if
if (condicion) {
acciones;
}
if (condicion){
acciones;
}
else {
acciones;
}
if (condicion) {
acciones;
} else if (condicion){
acciones;
} else {
acciones;
}
5.9.7. Ciclos
do {
acciones;
} while (condicion);
i=0
while (i<5){
_root["flor"+i+"_mc"]._visible=false;
i=i+1;
}
• In the Property inspector, you can view the instance's behavior and settings—for all instance types,
color effect settings, location, and size; for graphics, the loop mode and first frame that contains the
graphic; for buttons, the instance name (if assigned) and tracking option; for movie clips, the instance
name (if assigned). For location, the Property inspector displays the x and y coordinates of either the
symbol's registration point or the symbol's upper left corner, depending on which option is selected in the
Info panel.
• In the Info panel, you can view the instance's size and location; the location of its registration point;
its red (R), green (G), blue (B), and alpha (A) values (if the instance has a solid fill); and the location of
the pointer. The Info panel also displays the x and y coordinates of either the symbol's registration point
(center point) or the symbol's upper left corner, depending on which option is selected. To display the
coordinates of the registration point, click the center square in the Coordinate grid in the Info panel. To
display the coordinates of the upper left corner, click the upper left square in the Coordinate grid.
5.11. Propiedades
All properties are preceded by the underscore (_) character. In Table 25-1, each
property has an "R" (as in "read") and/or "W" (as in "write") designation. All properties
can be read, which means that you can retrieve that property's current value. The
values of some properties can also be changed through ActionScript. The table
represents these properties with the "W" designation.
Note In Flash Player 4 ActionScript, these properties were retrieved using the
getProperty() action. Properties are altered using the setProperty() action. For
Flash Player 5 or higher movies, you should avoid using these actions. Many free
online Flash tutorials or samples at sites such as FlashKit.com will often be riddled
with these deprecated actions.
Cross-Reference We don't review the more advanced properties of the MovieClip
object in this chapter. Cross For the most comprehensive coverage,
refer to the MovieClip class coverage in the Flash ActionScript Bible
series by Robert Reinhardt and Joey Lott (Wiley).
On the CD-Use the propInspector Movie Clip in the Library of the
ROM property_inspector.fla file, located in the ch25 folder of this book's CD-
ROM, to see the values of Movie Clip or Movie properties.
Although the name might sound intimidating, don't be scared. Methods are simply
actions that are attached to objects. As you now know, Movie Clips qualify as objects in
ActionScript. A method looks like a regular action, except it doesn't (and, in most cases,
can't) operate without a dot syntax reference to a target or an object:
becomes
• Method: myMovieClip.gotoAndPlay("start");
As actions, interactive commands are executed from the timeline on which they are
written. As methods, interactive commands are tied to specific (or dynamic) targets.
Figure 25-3 lists many of the methods and Table 25-2 reviews them in more detail.
Some methods can be used with Movie Clip instances and with the entire Flash movie
(_root, _level0, and so on), while others can only be used with Movie Clip instances.
The "Flash 4" column in Table 25-2 indicates if the method (when used as an action) is
compatible in Flash Player 4. Some commands need to be written in dot syntax, as a
method (designated as "M" in the table) of a timeline or MovieClip object. Other
commands can be used as actions (designated as "A" in the table), meaning that the
MovieClip object name need not precede the command.
This method
works only in
Flash 6 or
higher movies
played in Flash
Player 6 or
higher.
duplicateMovieClip Yes Makes a copy of timeline.duplicateMovieClip(new
an existing name*, depth);
M, A Movie Clip
instance on the myMC.duplicateMovieClip(“myMC_
Stage (or 2”, 20);
nested in
another Movie myMC_2._x = 200;
Clip). The new
copy is placed *See note for the
directly above createEmptyMovieClip() method.
the parent
instance, at a
specified depth.
Higher depth
numbers appear
above lower
depth numbers
(for example, a
Movie Clip at
depth 2 is
stacked above a
Movie Clip at
This method
works only
when issued
from a Flash
Player 7 or
higher movie.
getInstanceAtDepth No Returns the timeline.getInstanceAtDepth(depth
name of an Slot);
M object
occupying the var isOccupied =
specified depth myMC.getInstanceAtDepth(1);
slot. If no object
exists at the
slot, undefined
is returned
This method
works only
when issued
from a Flash
Player 7 or
higher movie.
createTextField No Adds a new timeline.createTextField (name,
TextField object depth, x position, y position, width,
M (that is, a height);
dynamic or input
text field) to the myMC.createTextField(“display_txt”
MovieClip , 1, 10, 10, 300, 50);
object. This
method enables
you to add new
text fields to
your movie at
run time.
This method
works only
when issued
from a Flash
Player 6 or
higher movie.
setMask No Assigns a timeline.setMask(instanceName);
MovieClip object
M to be used as myMC.setMask(clip_mc);
the mask for
another
MovieClip
object.
This method
works only
when issued
from a Flash
Player 6 or
higher movie.
External loadMovie Yes Loads an timeline.loadMovie(path, send
Assets external movie variables*);
M, A file (.swf) or
image file into myMC.loadMovie(“menu.swf”);
the main movie.
As one of the OR
most powerful
features of myMC.loadMovie(“image.jpg”);
Flash, this
method enables *You can also send Flash variables
you to break up to the newly loaded .swf file with an
your Flash optional "GET" or "POST"
movie into parameter. We discuss this in
several smaller Chapter 24, “Knowing the Nuts and
components, Bolts of Code.”
and load them
as needed. This
method can
load movie files
(.swf) or
This code uses onClipEvent() to track the position of the user's mouse, and apply
that position to the MovieClip object — effectively moving the MovieClip object
with the mouse pointer. The code is executed every time the user's mouse
moves. The updateAfterEvent() action will tell the Flash Player to refresh the
video display each time a mouse move is detected, resulting in a smoother
movement of the object.
On the CD-You can find a completed version of the file tracker_oce.fla in the ch25
ROM folder of this book's CD-ROM.
5.11.2. Event Methods: The More Flexible Movie Clip Handler
mcHolder.onMouseMove =
function(){
var myX:Number =
_root._xmouse;
var myY:Number =
_root._ymouse;
if(this.hitTest(myX, myY,
true)){
updateAfterEvent();
};
mouseDown onMouseDown This event occurs onClipEvent(mouseDown){
each time the left
mouse button is myX = _root._xmouse;
pressed (or down)
anywhere on the myY = _root._ymouse;
Stage. All Movie
Clip instances with if(this.hitTest(myX, myY,
this event handler true)){
receive this event.
trace(“Mouse press on
MC.”);
OR
mcHolder.onMouseDown =
function(){
var myX:Number =
_root._xmouse;
var myY:Number =
_root._ymouse;
if(this.hitTest(myX, myY,
true)){
trace(“Mouse press on “ +
this._name);
};
mouseUp onMouseUp This event is onClipEvent(mouseUp){
triggered each time
the left mouse myX = _root._xmouse;
button is released
(when the user lets myY = _root._ymouse;
up on the mouse
button). All Movie if(this.hitTest(myX, myY,
Clip instances with true)){
this handler receive
this event. trace(“Mouse release on
MC.”);
OR
mcHolder.onMouseUp =
function(){
var myX:Number =
_root._xmouse;
var myY:Number =
_root._ymouse;
if(this.hitTest(myX, myY,
true)){
trace(“Mouse release on “ +
this._name);
};
Note: If you’re
building Flash
Player 6 or higher
movies, use the
LoadVars class to
load URL-encoded
variables into a
Flash movie. Learn
more about the
LoadVars class in
Chapter 29,
“Sending Data In
and Out of Flash.”
Cross-Reference It is beyond the scope of this book to discuss all of the event methods
available in ActionScript 1.0 and 2.0. Please refer to the Flash
ActionScript Bible series by Robert Reinhardt and Joey Lott (Wiley)
for more information.
To get a better idea of how this event model works, create this simple example:
This code adds an onMouseMove() method to the tracker instance. Each time
the user's mouse moves, the function written for the method will execute. We
discuss functions in the next chapter.
You can continue to add more event methods to the tracker instance, in order for the
instance to respond to mouse clicks, time elapsing, and so on.
Caution The new event model for Flash movies only works in Flash Player 6 or higher.
If you need to use events with Movie Clips that are compatible with Flash
Player 5, then use onClipEvent() handlers.
5.11.3. Other Classes and Functions that Use the MovieClip Object
You can use Movie Clips with other ActionScript classes to control appearances and
sounds, and to manipulate data.
ColorTransform Class
This class can control the color effects of the targeted Movie Clip.
New Flash Player 8 introduces a new MovieClip class property, transform. The
Feature transform property controls color transformations applied to a MovieClip
instance. For more information about this new feature, read Chapter 27,
"Interacting with Movie Clips."
With this class, you can create virtual sound instances on a Movie Clip Timeline and
target them for later use.
Mouse Class
This class controls the appearance of the mouse pointer within the Flash movie. After
the Mouse object is hidden, you can attach a MovieClip object to the X and Y
coordinates of the mouse pointer.
PrintJob API
Flash MX 2004 and Flash Player 7 introduced the ActionScript class, PrintJob. PrintJob
objects enable you to send MovieClip instances — as pages to a user's printer. The
PrintJob class offers you more control over printing than previous versions of the Flash
Player. You learn more about the PrintJob API in Chapter 27, "Interacting with Movie
Clips."
Note You can still use the print() function for Flash Player 6 or earlier movies. This
function prints a frame (or series of frames) in the targeted timeline. Each frame
prints to one piece of paper. Use this function to print high-quality artwork. Note
that alpha and color effects applied to MovieClip objects do not print reliably with
this method — use the printAsBitmap() function instead.
With() Action
This action enables you to avoid needless replication of object references and paths. By
specifying a target for the with() action, you can omit the path from nested actions. We
demonstrate the with() action in the next section.
TellTarget() Action
This Flash Player 4-compatible action can direct actions to a specific Movie Clip
Timeline. To be compatible with Flash Player 4, you need to use slash syntax for the
target path. We strongly discourage you from using tellTarget() actions if you are
designing Flash Player 5 or higher movies.
5.11.4. MovieClip
The with statement takes an object as a parameter. The object you specify is added to the end of the
current target path. All actions nested inside a with statement are carried out inside the new target path, or
scope. For example, in the following script, the with statement is passed the object donut.hole to change
the properties of hole:
The script behaves as if the statements inside the with statement were called from the Timeline of the hole
instance. The above code is equivalent to the following:
donut.hole._alpha = 20;
donut.hole._xscale = 150;
donut.hole._yscale = 150;
getTimer()
getVersion()
parseFloat()
parseInt()
escape()
unescape()
Se definen en una timeline y al igual que las instancias de MovieClip tienen una ruta relativa o
absoluta que debe ser utilizada en la invocación.
Definición:
function nombre(args){
acciones;
}
Invocación:
_root.nombre(par); //Invoca la función nombre definida en main timeline
_root.func_mc.nombre(par); //Invoca la función nombre definida en la instancia de MovieClip
func_mc del main timeline.
Cronograma
• Introducción
o Bienvenida al curso
o Explicación de la Metodología a seguir.
• Comenzando con Flash
o Comprendiendo lo que Flash puede hacer
o Diferencias entre Bitmaps y Vectores
o El nuevo interface de Flash
o Cómo se trabaja con Flash
• Introducción
o Bienvenida
o Metodología del curso
• Introducción a AS 3.0
o Comprendiendo Actionscript
o Uso inteligente de TRACE
o Trabajando con comentarios
• Trabajando con variables
o Comprendiendo las variables
o Comprendiendo la sintaxis de las variables
o Asignando valores a las variables
o Recogiendo valores de las variables
o Trabajando con diferentes tipos de datos
• Usando funciones
o Comprendiendo las funciones
o Usando las funciones
o Entendiendo la sintaxis
• En este último módulo (Sin duda el más importante de todos y el que dará al alumno
los conocimientos prácticos para enfrentarse al mundo real y estar preparado para
desarrollar todo tipo de trabajos en Flash), los alumnos, aprenderán cómo crear un
proyecto en flash paso a paso. Desde la idea inicial, la preparación del proyecto así como
su diseño, planificación y programación para finalmente publicarlo en la web. Para la
realización del proyecto los alumnos deberán poner en práctica todo lo aprendido en los 2
últimos meses