Sei sulla pagina 1di 58

Guía de Macromedia Flash

1. Tipos de archivos en Flash


1.1. Documentos Flash

Se componen de escenas que contienen keyframes para describir los cambios en el


escenario. Estos archivos tienen extensión (.fla). Un documento flash se compone de:
• Escenas (un segmento de película Flash)
o Escenario (Stage): lugar donde se desarrolla la acción.
o Línea de tiempo (Timeline): lugar donde se controla la duración.
 Capas: permite mantener los objetos separados
• Capas normales: tipo de capa por defecto
• Capa de guía (Guide Layer): utilizadas para crear líneas u
objetos de registro personalizados.
• Capa de guía de movimiento (Motion Guide Layer): contiene
una línea a través de la cual se mueven los objetos.
• Capa de máscara (Mask layer): los contenidos determinan qué
se muestra en capas de máscaras anidadas.
 Guías de Líneas de tiempo (Timeline Header):
• Indicador de frame actual.
• Frames: Keyframes, Blank keyframes, Normal frames
• Onion Skin.
• Biblioteca (almacena símbolos e imágenes importadas, sonidos y video)
o Símbolos: ítems de uso múltiples
 Gráficos: imágenes
 Botones: event handler de cuatro estados
 Movie Clip: animación autocontenida.
o Bitmaps: Imágenes importadas.
o Sonidos: Archivos de audio importados.
o Video: Video digital importado.
1.2. Películas Flash

Se producen cuando se publica o prueba de un documento Flash. Los archivos de película


tienen extensión .swf y pueden ser incrustados de una página Web HTML mediante la
etiqueta object (Internet Explorer) o embed (browser basados en Mozilla)

1.3. Otros documentos Flash


• Archivos ActionScript: Son documentos con códigos ActionScript y se almacenan con
extensión .as
• Proyector de Windows: Son archivos ejecutables, del inglés proyector stand-alone, y se
almacenan con extensión .exe (para Windows), .mov (para videos Quicktime).
• Videos Flash: Son archivos de video Flash y se almacenan con extensión .flv

Prof. Giannina Núñez Marín Guía de ActionScript 1


2. Interface, Capas y Frames en Timeline
2.1. Barra de Herramientas (Tools)

• Lateral izquierdo de la sección superior de la barra


o Selection: Permite seleccionar
o Line:
o Pen
o Oval
o Pencil
o Free Transform
o Ink bootle
o Eyedropper
• Lateral derecho de la sección superior de la barra
o Subselection
o Lasso
o Text
o Rectangle
o Brush
o Fill transform
o Paint Bucket
o Eraser
• Sección View
o Hand
o Zoom

Prof. Giannina Núñez Marín Guía de ActionScript 2


• Sección Colors
o Stroke
o Fill
o Black&White
o No color
o Swap colors
• Sección Options
o Se ajusta de acuerdo con la herramienta activa
2.2. Frames en Timeline
• Keyframes: Frame cuyo contenido puede variar de los frames a su alrededor. Se
identifican con círculos negros rellenos.
• Blank keyframe: Es un keyframe sin contenido. Se identifican con círculos blancos
vacios.
• Frame Span: Sección de un keyframe a un endframe.
o Frames con relleno (filled frames): Frames intermedios en un span, son de color
gris.
o Frames vacios (blank frames): Frames intermedios en un span, son de color
blanco.
o Endframe: El frame final de un span, se identifica con un rectángulo blanco.
• Animación cuadro a cuadro (Frame by frame animation): Es una secuencia de
keyframes, cuyos contenidos pueden variar y dichos cambios se hacen manualmente.
• Animación Tween: Es un movimiento o cambio en un elemento interpolado en un span
entre dos keyframes. El span se marca con una flecha.
o Motion Tween: Se aplica a grupo, símbolos, textos editables. No se puede usar
en formas primitivas. Permite mover un objeto de un lugar a otro y también
animar la escala, skew, rotación, color y transparencia de un símbolo. Es de color
púrpura o azul. Procedimiento:
• Coloque el objeto en una capa
• Con la capa seleccionada en el timeline, abra el menú contextual y
seleccione Creation Motion Tween; o bien en el panel Propiedades
seleccione Motion en el menú Tween. También puede ir a Menú
Insert>Timeline>Creation Motion Tween (esta opción funciona también
con el objeto seleccionado en el escenario)
• Crear un keyframe en el último frame del span. También puede crear
otros keyframes a lo largo del span donde desea un cambio en la
animación.
• Realizar modificaciones deseadas al objeto en el primer frame y/o el
último frame del tween. Para modificar las propiedades de color y tamaño
debe seleccionar la instancia del objeto en el escenario, realizar las
modificaciones en el panel propiedades, para rotar aplique la herramienta
free transform.
• Orient to path: Cuando el ítem sigue una ruta o Motion Guide, esta
opción obliga al ítem a orientar su movimiento a esa ruta.

Prof. Giannina Núñez Marín Guía de ActionScript 3


• Sync: permite reemplazar el símbolo en el primer frame y actualiza
automáticamente el resto de los frames.
• Snap: Rompe su ítem animado en alineación con un Motion guide.
o Shape Tween: Se aplica a formas primitivas (no grupos). Es de color verde.
Procedimiento:
• Dibuje la forma primitiva en una capa
• Con la capa seleccionada en el panel Propiedades seleccione Shape en el
menú Tween.
• Crear un keyframe en el último frame del span. También puede crear
otros keyframes a lo largo del span donde desea un cambio en la
animación.
• Realizar modificaciones deseadas al objeto en cualquiera de los
keyframes del tween. Para modificar la forma del objeto, utilice la
herramienta subselection del panel de herramientas. También puede
modificar color, posición desde el panel de propiedades o de herramientas.
• Ease: varía la velocidad de la animación. In va de lento a rápido (-1 a
-100). Out va de rápido a lento (1 a 100). Velocidad constante Ease
tendrá valor de 0.
• Blend: utilice Distributive para crear formas interpoladas suaves.
Angular para formas interpoladas que tienen esquinas y líneas.
• Los puntos Shape Hint permiten especificar puntos en la forma inicial
que se deben parear con puntos específicos de la forma final. Para
agregar Shape Hint seleccione el keyframe inicial y entre a
Modify>Shape>Add Shape Hint. Luego arrastre el punto rojo a un punto
de la forma (ahora es amarillo) que desea parear con la forma final, luego
en el keyframe final arrastre el punto rojo al punto de la forma que
corresponda (ahora es verde) con la forma final. Los puntos son
etiquetados con letras, agregue todos los puntos que necesite.

Prof. Giannina Núñez Marín Guía de ActionScript 4


2.3. Layers en Timeline

Prof. Giannina Núñez Marín Guía de ActionScript 5


• Folder Layer: Permiten organizar las capas en carpetas. No tienen contenido en la línea
de tiempo se muestra como una barra gris. (Se identifica con un folder)
• Layer: Son las capas normales en la que se coloca el arte que aparece en escena. (Se
identifica con hoja crema doblada en la esquina inferior derecha)
• Guide layer: Sirve como una referencia para alinear objetos. No se exporta en el archivo
.swf. (Se identifica con un martillo). Procedimiento:
o Inserte una capa normal.
o Seleccione la capa en el timeline y en el menú contextual seleccione Guide.
Luego inserte o dibuje el ítem de referencia o guía.
o Coloque la capa con el arte a alinear encima de la capa Guide. Active Snap to
object (ícono del imán o bien View>Snapping>Snap to object) para alinear los
ítem del arte con el ítem de referencia de la capa guía.
• Motion guide layer: Guía un objeto animado a lo largo de una ruta vectorial.
o Crear el arte en un capa
o Con esta capa seleccionada, y con el menú contextual en el panel de capas,
seleccionar Add Motion Guide. Aparece una capa encima de la capa de arte con el
nombre Guide: nombre_capa_arte.
o En la capa guía creada en el paso anterior, crear el stroke (línea) de la ruta que
seguirá el arte en la animación.
o Agregar una animación Tween Motion al arte.
o Activar el Snap to Object (imán de la sección inferior de la barra de
herramientas). Seleccionar el primer frame del arte y colocarlo donde se desea
que inicie la animación en la ruta de la capa guía, seleccionar el keyframe final y
colocar el arte donde se desea que termine la animación dentro de la ruta.
o Activar en las propiedades tween Orient to path para forzar la rotación del ítem de
acuerdo con la ruta.
• Mask Layer: Define el área visible de las capas anidadas debajo de ella. Su contenido
no es visible en el archivo .swf. Una máscara se puede crear a partir de un símbolo o
forma rellena (sin strokes). La máscara puede ser animada o estática.

Prof. Giannina Núñez Marín Guía de ActionScript 6


o Cree una capa con el arte que será visible a través de la máscara.
o Cree una capa encima de la anterior, ésta será la máscara, y cree la apertura
(forma con relleno, instancia de símbolo con relleno, texto) a través de la cual se
verá el contenido del arte. Si desea que la máscara sea animada aplique un efecto
de animación. Una máscara también puede ser una instancia de un movie clip con
animación en su propia línea de tiempo. La máscara también puede ser un texto,
en este caso el efecto resultante es un texto con relleno de una imagen.
o Coloque el contenido de la máscara encima del área que será visible.
o Convierta la capa de máscara activando en el menú contextual la opción Mask. Si
desea que la máscara sea animada aplique antes de transformarla en máscara una
animación tween.
o Para modificar y ver el contenido de la máscara, desactive el bloqueo en el panel
de capas, haciendo clic en el candado.
• Label: Son capas con keyframe blanco y span de frames en blanco. En algunos keyframe
se pueden agregar etiquetas desde el panel de Propiedades. Estas etiquetas permiten
hacer referencia al frame que la contiene en un código ActionScript, se identifican con un
banderín rojo. Procedimiento:
o Seleccione el frame en la línea de tiempo.
o Active el panel Propiedades.
o Escriba la etiqueta deseada en el campo rotulado Frame.
o En el campo Label Type, escoja nombre.
• Comment: Son capas con keyframe blanco y span de frames en blanco. En algunos
keyframe se pueden agregar comentarios desde el panel de Propiedades. Estos
comentarios permiten documentar la línea de tiempo, se identifican con un para de
diagonales verde. Procedimiento:
o Seleccione el frame en la línea de tiempo.
o Active el panel Propiedades.
o Escriba el comentario deseado en el campo rotulado Frame.
o En el campo Label Type, escoja comment.
• Waveform: Es una capa que contiene un sonido.
• Frame Actions: Son capas con keyframe blanco y span de frames en blanco. En algunos
keyframe se pueden agregar códigos Script desde el panel Actions. Estos códigos
controlan la línea de tiempo, se denominan actions-frame. Se identifican con una letra a
en negro. Procedimiento:
o Seleccione el frame en la línea de tiempo.
o Active el panel Actions.
o Escriba el código deseado.
2.4. Creación de símbolos
• Gráficos: Recordar que su línea de tiempo depende de la línea principal o de su padre
• Movie clip: Su línea de tiempo es independiente de la línea principal o del padre.
• Botón: Es posible compartir partes del arte en capas adicionales en todos los estados del
botón.

Prof. Giannina Núñez Marín Guía de ActionScript 7


• Sufijos para diferenciar instancias de símbolos, elementos de biblioteca. Esta lista de
sufijos es útil para referenciar instancias en códigos de ActionScript, se agregan al final
del nombre del símbolo o elemento de biblioteca.
o _mc movie clip
o _btn button
o _sound sound
o _video video
o _str string
o _array array
o _txt text field
o _fmt text format
o _date date
o _color color
o _xml XML
o _xmlsocket XMLSocket

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:

Prof. Giannina Núñez Marín Guía de ActionScript 8


objeto.propiedad=valor;
u
objeto.metodo();

Un objeto es cualquier elemento en un programa (película Flash) que tiene características


accesibles y modificables. Los objetos pueden ser creados por el usuario o predefinidos por el
lenguaje. Flash tiene diferentes objetos predefinidos, también llamados clases, es decir son
predefinidos en el lenguaje ActionScript. Movie Clip es un objeto, y sus instancias en el
escenario también son objetos.
Las propiedades son las características de los objetos que se pueden cambiar o actualizar
a través de la película. La escala es un ejemplo de propiedad de Movie Clip, y se identifican
como _xscale y _yscale.
Los datos que acompañan a las propiedades se denominan valor. Así el tamaño de un
Movie Clip indica el valor de la propiedad _xscale.
Ejemplo: La propiedad _xscale de la instacia de Movie Clip rio_mc se configura en 100.
rio_mc._xscale=100;
Los métodos son procedimientos para hacer algo a o con el objeto. Los métodos pueden
ser creados para sus propios objetos o pueden ser predefinidos. Los métodos se pueden aplicar a
instancias de símbolos. Ejemplo: El método gotoAndPlay le indica a la instancia rio_mc dirigir
el playhead a la etiqueta inicio de su propia línea de tiempo.
rio_mc.gotoAndPlay(“inicio”);
El núcleo del lenguaje se compone de: variables, operadores, condicionales, ciclos,
expresiones, propiedades internas, subrutinas, funciones internas.
La interactividad es una relación causa-efecto. Las causas son entradas, en este caso
particular son eventos. El efecto es la reacción a la causa, son conductas o acciones que se
ejecutan ante la ocurrencia de un evento. En Flash la interactividad se implementa mediante un
event handler.

5.1. Conceptos básicos de orientación a eventos.


5.1.1. Event Handler

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

Un evento es la ocurrencia de algo que provoca la activación de la acción. Puede ser:


• Entrada de audio y video: Micrófono y cámara
• Entrada del usuario: Mouse y Teclado
• Basado en el tiempo: Playback en la línea de tiempo
• Basado en el sistema: Flujos de datos (data)

Prof. Giannina Núñez Marín Guía de ActionScript 9


Eventos y Handlers
Event Type Event handler Ejemplo

Playback Basado en el tiempo Keyframes Play hasta llegar a un frame


Objeto MovieClip Instancia de movieClip
Objeto NetStream monitorea el tiempo de película
Cuando un video se termina de
reproducir, inicia otro
Mouse Entrada del usuario Objeto Button Clic en un botón
Objeto MovieClip Movimiento del mouse se
Objeto Mouse detecta sobre una instancia de
MovieClip
Key Press Entrada del usuario Objeto Button Usuario teclea Enter para enviar
Objeto MovieClip datos.
Objeto Key Alerta si una tecla está activa

Actividad en Entrada Audio/ Video Objeto Microphone Se muestra un gráfico cuando el


Microphone Objeto Camera usuario deja de hablar en el
o Webcam micrófono. Cuando se detecta
movimiento en la cámara se
graba.
Data Basado en el sistema Objeto MovieClip Se muestran los resultados de
Objetos data una búsqueda cuando los
mismos se han cargado
completamente.

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

Las acciones de Script se asignan al objeto seleccionado. En el panel de Acciones de Script


la barra de título del panel se identifica con el tipo de script a escribir, según el objeto
seleccionado.
• Actions-Frame: Se asignan al keyframe del Timeline seleccionado
• Actions-MovieClip: Se asignan a la instancia de movieClip seleccionada en el escenario.
• Actions-Button: Se asignan a la instancia de símbolo Button seleccionada en el escenario
• Actions: Se asignan a un componente de interface de usuario (UI Component)
seleccionado en el escenario.

Prof. Giannina Núñez Marín Guía de ActionScript 10


La estructura de un script de movieClip, Button, componente UI es la siguiente:

Los script de keyframe generalmente se componen de conductas, es decir, no tienen un


event handler específico.
Algunos aspectos generales de la sintaxis son los siguientes:
• Espacios: son áreas blancas entre líneas de código.
• Paréntesis: lo utilizan la mayoría de las acciones (funciones, métodos).
• Punto y coma: Se agrega al final de una línea de código (acciones)
• Llaves: Se utilizan generalmente en acciones que inician en on, on (), onClipEvent(), en
sentencias if, ciclos de repetición y declaraciones de funciones.
• Un event handler admite más de un evento separados por “,”. Estos eventos pueden ser
teclado y/o mouse.
– on(release, releaseOutside) {..}
• Un evento se asocia a event handler específico
5.2. Acciones básicas

Los parámetros entre corchetes son opcionales.

5.2.1. Controlar la línea de tiempo

Estas son las acciones básicas de navegación en Flash.


gotoAndPlay([escena,]frame); Cambia el frame actual por el frame especificado, y
luego ejecuta una acción play.
gotoAndStop([escena,]frame); Cambia el frame actual por el frame especificado, y
luego se detiene la película.
nextFrame(); Se mueve un frame hacia adelante y detiene el
playback
nextScene(); Se mueve al primer frame de la siguiente escena
play(); Activa el movimiento de una película o instancia de
movieClip
stop(); Detiene el movimiento de una película o instancia de
movieClip
prevFrame(); Se mueve un frame hacia atrás y detiene el playback
prevScene(); Se mueve al primer frame de la escena anterior
stopAllSounds(); Apaga todos los sonidos que se están ejecutando en

Prof. Giannina Núñez Marín Guía de ActionScript 11


la película.
El orden de las escenas es el establecido por el panel Scene, y se recorren de manera
circular.
Agregue stop(); al inicio del timeline de un MovieClip, si no desea que se ejecute una vez
entra en escena.
Solo stopAllSounds(); responde al evento click.

5.2.2. Browser / Network

getURL(url [,window [,method]]);


Enlaza a una página Web, sitio FTP, película Flash, un ejecutable. Permite enviar variables en un
formulario. La aplicación enlazada se ejecuta en el Web Browser
url – Dirección del recurso, archivo, sitio web.
window – (_self, _blank, _parent, _top)
method – Se omite para enlaces normales. Para envío de variables de formulario: “GET” o
“POST”.
fscommand(“command”, “args”);
Envía un comando de una película Flash a su entorno (hosting): Web Browser o standalone Flash
Player.
Acciones para fscommand en un standalone player
command args función
fullscreen true or false True- Modo pantalla
completa sin menú.
False- Tamaño especificado
en propiedades
allowscale true or false Permite escalar la película.
showmenu true or false True-Activa la barra de
menú y el clic del botón
derecho.
False-Los desactiva
trapallkeys true or false Captura todas las teclas
presionadas.
exec Ruta al Abre un ejecutable en el
ejecutable stand-alone player. El
executable debe estar en un
carpeta fscommand dentro
de la misma carpeta del
proyector stand-alone.
quit cierra el player
fscommand(“quit”);
fscommand(“fullscreen”,”true”);

loadMovie(url, target, method);


unloadMovie(target);
Abrir /cerrar otras películas dentro de la película original. Se usa en stand-alone player.

Prof. Giannina Núñez Marín Guía de ActionScript 12


loadMovieNum(url, level, method);

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);

Equivalently, you can use MovieClip.loadMovie() to achieve the same result:


target_mc.loadMovie("contents.swf");

The following code loads the JPEG image flowers.jpg into the movie clip instance image_clip:
image_clip.loadMovie("flowers.jpg");

5.2.3. Controlar MovieClip


Global functions that control a Timeline have a target parameter that allows you to specify the target path
to the instance that you want to control. For example, in the following script startDrag() targets the
customCursor instance and makes it draggable:
on(press){
startDrag("customCursor");
}

The following functions target movie clips: loadMovie(), unloadMovie(), loadVariables(),


setProperty(), startDrag(), duplicateMovieClip(), and removeMovieClip(). To use these functions,
you must enter a target path for the function's target parameter to indicate the target of the function.

5.2.4. Funciones misceláneas

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);

5.3. Event Handler

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.

Prof. Giannina Núñez Marín Guía de ActionScript 13


5.4. Script de frame

Cuando se escribe una acción generalmente se hace referencia a un frame. La referencia se


puede hacer:
• Por el número: Cada frame en cada escena tiene un número, sin embargo el número de
frame se expande entre escenas, así si una película tiene dos escenas de 10 y 20 frames,
respectivamente, una acción que referencia al número de frame 15 se refiere al frame 5 de
la escena 2. Ejemplo: gotoAndPlay(10)
• Label: Un frame se identifica con una etiqueta, mediante el campo Label del inspector de
Propiedades. Ejemplo: gotoAndStop(“fin”)
• Expresión ActionScript: Un segmento de código. Ejemplo:
var destino=“fin”
gotoAndStop(destino)
Un script de frame no requiere un event handler específico, las acciones se listan una
debajo de otra. Para crear un script de Frame, considere incluir en la escena una capa para
colocar en ella exclusivamente los script de frame correspondientes a esa escena.
Adicionalmente agregue una capa para colocar en ella las etiquetas de frame que permitirán
identificar algunos keyframe particulares. Además agregue todas las capas de arte que considere
necesarias. Procedimiento:
1. Seleccione el frame de la línea de tiempo, preferiblemente en la capa de script dispuesta
para ello.
2. Active el panel de acciones. Verifique que el panel de Acciones debe tener el título:
Actions-Frame.
3. Escriba las acciones deseadas
Ejemplo:
gotoAndPlay(1);
El código anterior hace que el playback de la película entre al frame número 1, y ejecute la
película.
gotoAndPlay("inicio");
El código anterior hace que el playback de la película entre al frame etiqueado “inicio”, y ejecute
la película.
gotoAndPlay("Scene 1","parte2");

5.5. Eventos del mouse


• Localización del puntero del mouse
• Over: Mouse entra en contacto con el área hit del botón
• Outside: No over
• Movimiento del puntero del mouse
• Rolling: Movimiento del mouse sin el botón presionado
• Dragging: Movimiento del mouse con el botón presionado
• Click del mouse
• Press es cuando el botón del mouse está presionado (downstroke)
• Release es cuando el botón del mouse se suelta o libera (upstroke)
Los eventos del mouse pueden ser aplicados a:
– UI Componentes

Prof. Giannina Núñez Marín Guía de ActionScript 14


• Evento: Click
• No aplica a eventos del mouse estándar e instancias de símbolos botón
– Botones Flash
• press:
– Puntero del mouse está (over) en el área hit
– Se detecta el downstroke del clic del mouse
• release:
– Puntero del mouse está (over) en el área hit
– Se detecta el downstroke y el upstroke del clic del mouse
• releaseOutside:
– Puntero del mouse está (over) en el área hit
– El botón del mouse está presionado
– Puntero del mouse se mueve fuera (outside) del área hit
– El botón del mouse es liberado (release)
• rollOver:
– Puntero del mouse se mueve sobre (over) el área hit
– El botón del mouse no está presionado
• rollOut:
– Puntero del mouse está fuera (outside) del área hit
– El botón del mouse no está presionado
• dragOver:
– El botón del mouse es presionado cuando el puntero del mouse
está fuera (outside) del área hit
– El puntero del mouse se mueve sobre el área hit mientras que el
botón del mouse se mantiene presionado(press)
• dragOut:
– El botón del mouse es presionado cuando el puntero del mouse
está sobre(over) del área hit
– El puntero del mouse se mueve fuera (outside) del área hit,
mientras que el botón del mouse se mantiene presionado(press)

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

Prof. Giannina Núñez Marín Guía de ActionScript 15


getURL("http://www.macromedia.com","_blank");
//End 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.

5.6. Eventos del teclado

Se aplican a instancias de botón con timeline en blanco.


• Evento: keyPress
• Event handler: on()
• Script: on (keyPress “<Enter>”) {…}
El evento keyPress se hace acompañar el código de tecla al que aplica:
keyPress "<Left>"
keyPress "<Right>"
keyPress "<Home>"
keyPress "<End>"

Cuando la tecla presionada sea una letra el evento keyPress se hace acompañar de la letra.
keyPress "A"

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:

Prof. Giannina Núñez Marín Guía de ActionScript 16


• No se permiten combinaciones de tecla.
• En un browser, el usuario debe hacer un clic en la ventana para que los eventos del
teclado se reconozcan.
• El evento keyPress es sensitivo a mayúscula/minúscula.
5.7. Manejo de múltiples timeline (Rutas)

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

Prof. Giannina Núñez Marín Guía de ActionScript 17


5.8. Directiva de compilador include

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. Elementos básicos del lenguaje


• Es fuertemente tipado.
• Es sensitivo mayúsculas/minúsculas.
• Las constantes literales se escriben entre comillas dobles.

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;

Prof. Giannina Núñez Marín Guía de ActionScript 18


var name=value;
var _global.nombre; // variables globales, independiente de cualquier timeline para hacer
referencia no requiere de una ruta.
var _global.nombre=valor;
Las variables globales se pueden crear en el frame 1 del main timeline. En este frame
también se pueden declarar variables “on the fly”. Las variables del _root se muestran en el
nivel 0 (_level0) en el panel Output, después de activar Debug>List Variables en el Test
Movie.

• 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.2. Constantes de cadenas

Prof. Giannina Núñez Marín Guía de ActionScript 19


Una cadena es cualquier combinación de caracteres alfanuméricos. Se escriben entre
comillas dobles.

5.9.3. Expresiones

Una expresión es un fragmento de código. Expresiones condicionales permiten


comparar valores en una condicional o en un ciclo. Expresiones numéricas y expresiones de
cadenas son segmentos de código convertidos en sus valores calculados en tiempo de ejecución.

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.6. Condiciones con switch y case

Funciona de manera similar al switch-case de C.


switch (condicion) {
case condition :
acciones;
case condition :

Prof. Giannina Núñez Marín Guía de ActionScript 20


acciones;
break;
case condition :
acciones;
default:
acciones;
}

5.9.7. Ciclos

Funciona similar a los ciclos de C.


while (condicion) {
acciones;
}

do {
acciones;
} while (condicion);

for (inicialización; condicion; proximo) {


acciones;
}

for (variableIterante in object) {


acciones;
}
Este ciclo aplica a objetos y arreglos, con propiedades que puedan ser enumeradas.
for (name in _root){
if (_root[name] instanceof MovieClip) {
_root[name]._xscale=50;
}
}

i=0
while (i<5){
_root["flor"+i+"_mc"]._visible=false;
i=i+1;
}

5.10. Inspector de Propiedades y Panel Info


As you create a Flash application, it can be difficult to identify a particular instance of a symbol on the
Stage, particularly if you are working with multiple instances of the same symbol. You can identify instances
using the Property inspector, the Info panel, or the Movie Explorer.

Prof. Giannina Núñez Marín Guía de ActionScript 21


The Property inspector and Info panel display the symbol name of the selected instance and an icon that
indicates its type—graphic, button, or movie clip. In addition, you can view the following information:

• 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.

Para la figura seleccionada el punto central (punto de registro) está ubicado en la


esquina superior izquierda de la imagen, observe el cuadro negro en el Aligment Grid del Panel
Info. Este punto puede ubicarse en el centro o la esquina superior izquierda del objeto
seleccionado.

5.11. Propiedades

Son características de película o MovieClip que pueden ser recuperadas y configuradas.


Se pueden almacenar en variables.
var nombre_var=objeto.propiedad;

_xmouse Distancia horizontal en pixeles entre el punto central de un MovieClip (o la película


Movie) y la posición actual del puntero del mouse
_ymouse Distancia vertical en pixeles entre el punto central de un MovieClip (o la película
Movie) y la posición actual del puntero del mouse
_x Distancia horizontal, en pixeles, entre el punto central de un MovieClip y la
esquina superior izquierda del escenario, en el cual reside. Incrementa cuando el
clip se mueve hacia la derecha
_y Distancia vertical, en pixeles, entre el punto central de un MovieClip y la esquina
superior izquierda del escenario, en el cual reside. Incrementa cuando el clip se
mueve hacia abajo.
_rotation La cantidad en grados que un Movie Clip es rotado fuera de su plomada.
_xscale Ancho de la instancia de movieClip como un porcentaje del tamaño actual del

Prof. Giannina Núñez Marín Guía de ActionScript 22


símbolo padre.
_yscale Altura de la instancia de movieClip como un porcentaje del tamaño actual del
símbolo padre.
_width Ancho, en pixeles, de un movieClip o el escenario principal de la película. No
determinado por el ancho del canvas, sino por el ancho del espacio ocupado por los
elementos en el escenario.
_height Altura, en pixeles, de un movieClip o el escenario principal de la película. No
determinado por la altura del canvas, sino por la altura del espacio ocupado por los
elementos en el escenario.
_alpha
_visible
_color

Category Property Timeline Flash Flash Flash Definition


4 5+ 8
Position _x MC RW RW RW The horizontal distance
between a Movie Clip’s
Movie RW RW RW center point and the top-left
corner of the stage upon
which it resides. It increases
as the clip moves to the right,
and is measured in pixels.
_y MC RW RW RW The vertical distance between
a Movie Clip’s center point
Movie RW RW RW and the top-left corner of the
stage upon which it resides. It
increases as the clip moves
downward, and is measured
in pixels.
_xmouse MC N/A R R The horizontal distance (in
pixels) between the zero
Movie R R point of a Movie Clip (or the
Movie) and the current
position of the mouse pointer.
_ymouse MC N/A R R The vertical distance (in
pixels) between the zero
Movie R R point of a Movie Clip (or the
Movie) and the current
position of the mouse pointer.
_rotation MC RW RW RW The amount (in degrees) that
a Movie Clip is rotated off
Movie RW RW RW plumb. It returns values set
both by the Transform panel

Prof. Giannina Núñez Marín Guía de ActionScript 23


Category Property Timeline Flash Flash Flash Definition
4 5+ 8
(or Transform tool) and by
ActionScript.
_xscale MC RW RW RW The width of a Movie Clip
instance (or Movie) as a
Movie RW RW RW percentage of the parent
symbol’s actual size.
Size _yscale MC RW RW RW The height of a Movie Clip
instance (or Movie) as a
Movie RW RW RW percentage of the parent
symbol’s actual size.
_width MC R RW RW The width (in pixels) of a
Movie Clip or the main Movie
Movie R R R Stage. It is determined not by
the width of the canvas but by
the width of the space
occupied by elements on the
Stage (meaning it can be less
than or greater than the
canvas width set in Movie
Properties).
_height MC R RW RW The height (in pixels) of a
movie clip or the main movie
Movie R R R Stage. It is determined not by
the height of the canvas but
by the height of the space
occupied by elements on the
Stage.
Appearance _alpha MC RW RW RW The amount of transparency
of a Movie Clip or Movie. It is
Movie RW RW RW measured as a percentage:
100 percent is completely
opaque; 0 percent is
completely transparent.
_visible MC RW RW RW A Boolean value that
indicates whether a Movie
Movie RW RW RW Clip instance is shown or
hidden. It is set to 1 (or true)
to show; 0 (or false) to hide.
Buttons in "hidden" movies
are not active.
filters MC N/A N/A RW This new property in Flash
Player 8 enables you to add

Prof. Giannina Núñez Marín Guía de ActionScript 24


Category Property Timeline Flash Flash Flash Definition
4 5+ 8
visual effects to MovieClip
Movie N/A N/A RW objects. The filters property
uses an array to describe
which filters have been
applied to the clip.
transform MC N/A RW RW This new property in Flash
Player 8 enables you to
Movie N/A N/A RW control physical
characteristics of a MovieClip
object via transformation
object. In Chapter 27,
“Interacting with Movie Clips,”
we discuss the
ColorTransform class, which
can control the color
properties of a MovieClip
object.
Internal Path _name MC RW RW RW This property returns or
reassigns the Movie Clip
Movie R R R instance’s name (as listed in
the Property inspector).
_target MC R R R This property returns the
exact string in Slash notation
Movie R R R that you'd use to refer to the
Movie Clip instance. To
retrieve the dot syntax path,
use eval(_target).
_droptarget MC R R R This property returns the
name (in Slash notation) of
Movie R R R the last Movie Clip upon
which a draggable Movie Clip
was dropped. To retrieve the
dots syntax path, use
eval(_droptarget). For usage,
see “Creating Draggable
Movie Clips” in this chapter.
_lockroot MC RW RW RW This property, only available
to Flash Player 7 or higher-
Movie RW RW RW compatible movies, enables
you to control how a _root
reference is interpreted. If the
_lockroot property of a

Prof. Giannina Núñez Marín Guía de ActionScript 25


Category Property Timeline Flash Flash Flash Definition
4 5+ 8
MovieClip object is set to
true, then any child assets
(nested MovieClip objects)
will see the parent MovieClip
object as _root. For example,
if you load an .swf file into a
MovieClip object, any _root
target in the loaded .swf will
point to the MovieClip object.
_parent MC N/A R R This property returns a
reference to the parent
Movie N/A R R timeline of the current
MovieClip object. For
example, if an instance
named bird_1 exists within
another instance named
flock_mc, then bird_1._parent
refers to the flock_mc
instance.
* _parent will return only a
valid reference from the Main
Timeline if the Flash movie is
loaded into a MovieClip
instance of another Flash
movie.
External _url MC R R R This property returns the
Path complete path to the Flash
Movie R R R movie (.swf) in which the
action is executed, including
the name of the Flash movie
file (.swf) itself. It can be used
to prevent a movie from being
viewed if it is not on a
particular server.
Timeline _currentframe MC R R R This property returns the
number of the current frame
Movie R R R (for example, the frame on
which the Playhead currently
resides) of the Movie or a
Movie Clip instance.
_totalframes MC R R R This property returns the
number of total frames in a

Prof. Giannina Núñez Marín Guía de ActionScript 26


Category Property Timeline Flash Flash Flash Definition
4 5+ 8
Movie or Movie Clip
Movie R R R instance’s timeline.
_framesloaded MC R R R This property returns the
number of frames that have
Movie R R R downloaded over the
network.
Global _quality Movie N/A RW RW The visual quality of the
Movie. The value is a string
equal to: “LOW” (no anti-
aliasing, no bitmap
smoothing), “MEDIUM” (anti-
aliasing on a 2 x 2 grid, no
bitmap smoothing), “HIGH”
(anti-aliasing on a 4 x 4 grid,
bitmap smoothing on static
frames), “BEST” (anti-aliasing
on a 4 x 4 grid, bitmap
smoothing on all frames).
_focusrect Movie RW RW RW A Boolean value that
indicates whether a yellow
rectangle is shown around
buttons when accessed via
the Tab key. The default is to
show. When set to 0, the Up
state of the button is shown
instead of the yellow
rectangle.
_soundbuftime Movie RW RW RW The number of seconds a
sound should preload before
it begins playing. The default
is five seconds.
MC = Movie Clip; R = Read property (cannot be modified); W = Write property (can be
modified)

Prof. Giannina Núñez Marín Guía de ActionScript 27


Figure 25-2: Properties of the MovieClip object

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.

5.11.1. Movie Clip Methods

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:

Prof. Giannina Núñez Marín Guía de ActionScript 28


• Action: gotoAndPlay("start");

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.

Table 25-2: Common Movie and Movie Clip Methods


Open table as spreadsheet
Categor Method Flas Definition Usage
y h4
Position hitTest No Determines if a timeline.hitTest(MovieClip object);
MovieClip object
M overlaps with OR
the boundaries
of another timeline.hitTest(x coordinate, y
MovieClip coordinate, shapeFlag);
object, or if an
X-Y coordinate myMC.hitTest(myOther_mc);
intersects with a
MovieClip myMC.hitTest(_root._xmouse,
instance. For
more _root._ymouse,true);
information on
this method, see
Chapter 27,
“Interacting with
Movie Clips.”
startDrag Yes Enables the timeline.startDrag(lock, min X, min
user to move a Y, max X, max Y);
M, A Movie Clip
instance on the myMC.startDrag(false,200,0,200,20
Stage. The 0);
Movie Clip
moves (or

Prof. Giannina Núñez Marín Guía de ActionScript 29


Table 25-2: Common Movie and Movie Clip Methods
Open table as spreadsheet
Categor Method Flas Definition Usage
y h4
drags) in
tandem with the
movements of
the mouse. You
can specify
whether the
mouse pointer
locks to the
center of the
Movie Clip
instance and if
the drag area is
constrained to a
range of X and
Y coordinates
(in the parent
symbol or
timeline space).
Constraining the
drag area is
useful for slider
controls.
stopDrag Yes Stops any timeline.stopDrag();
startDrag action
M, A currently in myMC.stopDrag();
progress. No
target needs to
be specified
with this action.
Playback play Yes Starts playback timeline.play();
from the current
M, A position of the _root.play(); // plays the Main
Playhead on a Timeline
specified
timeline. _root.myMC.play(); // plays myMC
stop Yes Stops playback timeline.stop();
on a specified
M, A timeline. _root.stop(); // stops the Main
Timeline

_root.myMC.stop(); // stops myMC

Prof. Giannina Núñez Marín Guía de ActionScript 30


Table 25-2: Common Movie and Movie Clip Methods
Open table as spreadsheet
Categor Method Flas Definition Usage
y h4
gotoAndPlay Yes Jumps the timeline.gotoAndPlay(position);
Playhead of a
M, A specified _root.myMC.gotoAndPlay(“start”);
timeline to a
label, frame // plays from the “start” label of the
number, or myMC
expression, and
starts playing timeline
from there.
gotoAndStop Yes Jumps the timeline.gotoAndStop(position);
Playhead of a
M, A specified _root.myMC.gotoAndStop(“mute”);
timeline to a
label, frame // stops playback on the “mute”
number, or label of myMC
expression, and
stops playback.
nextFrame Yes Moves the timeline.nextFrame();
Playhead of the
M, A specified _root.myMC.nextFrame();
timeline to the
next frame.
prevFrame Yes Moves the timeline.prevFrame();
Playhead of the
M, A specified _root.myMC.prevFrame();
timeline to the
previous frame.
Internal createEmptyMovie No Makes a blank timeline.createEmptyMovieClip(new
Clip (empty) Movie name*, depth);
Assets Clip instance on
M the Stage (or _root.createEmptyMovieClip(“myM
nested in C”, 1);
another Movie
Clip instance). myMC._x = 50;
The new
instance is *You should only specify an
placed directly instance name for the new
above the MovieClip object — not a new path.
parent instance, You can only create new instances
at a specified relative to the instance invoking the

Prof. Giannina Núñez Marín Guía de ActionScript 31


Table 25-2: Common Movie and Movie Clip Methods
Open table as spreadsheet
Categor Method Flas Definition Usage
y h4
depth. Higher
depth numbers method.
appear above
lower depth
numbers (for
example, a
Movie Clip at
depth 2 is
stacked above a
Movie Clip at
depth 1).

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

Prof. Giannina Núñez Marín Guía de ActionScript 32


Table 25-2: Common Movie and Movie Clip Methods
Open table as spreadsheet
Categor Method Flas Definition Usage
y h4
depth 1).
remove MovieClip Yes Deletes a timeline.removeMovieClip();
previously
M, A duplicated myMC_2.removeMovieClip();
Movie
Clipinstance.
When used as a
method, you do
not need to
specify a target.
You cannot
remove a Movie
Clip instance
that is manually
inserted on any
timeline frame
from the Library.
attachMovie No Places an timeline.attachMovie(ID*, new
instance of from name, depth);
M the Library into
the specified _root.attachMovie(“eye”, “eye_1”,
timeline. Each 1);
attached
instance *
You need to specify a unique
requires a identifier to linked Movie Clip
unique name symbols in the Library, using the
and depth. Linkage Properties.
Attached Movie
Clip instances
can be deleted
with
removeMovieCli
p.
getDepth No Returns the timeline.getDepth();
current depth of
M a duplicated (or _root.attachMovie(“eye”, “eye_1”,
attached) 1); trace(eye_1.getDepth());
MovieClip
object. *
If you attempt to retrieve the depth
of a Movie Clip instance that you
This method manually placed on the Stage, then

Prof. Giannina Núñez Marín Guía de ActionScript 33


Table 25-2: Common Movie and Movie Clip Methods
Open table as spreadsheet
Categor Method Flas Definition Usage
y h4

only works in ActionScript will return -16383 as


Flash 6 movies the value of getDepth().
played in Flash
Player 6.
swapDepths No Switches the timeline.swapDepths(depth);
depth
M placement of timeline.swapDepths(target);
two duplicated
or attached eye_1.swapDepths(10); // depth
Movie Clips.
This method is eye_1.swapDepths(eye_2); // target
useful for
placing one
Movie Clip
instance in front
of (or behind)
another
instance.
getNextHighestDept No Determines if timeline.getNextHighestDepth();
h any objects
currently exist var nextSlot =
M within depth
slots of the myMC.getNextHighestDepth();
current
MovieClip
object, and
returns a depth
number one
higher than an
occupied slot.
For example, if
you duplicated a
MovieClip object
to a depth count
of 2, this
method would
return 3. You
can use this
method in
conjunction with

Prof. Giannina Núñez Marín Guía de ActionScript 34


Table 25-2: Common Movie and Movie Clip Methods
Open table as spreadsheet
Categor Method Flas Definition Usage
y h4
any of the Movie
Clip methods
that require a
depth
parameter.

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.

Prof. Giannina Núñez Marín Guía de ActionScript 35


Table 25-2: Common Movie and Movie Clip Methods
Open table as spreadsheet
Categor Method Flas Definition Usage
y h4

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

Prof. Giannina Núñez Marín Guía de ActionScript 36


Table 25-2: Common Movie and Movie Clip Methods
Open table as spreadsheet
Categor Method Flas Definition Usage
y h4
standard JPEG
image files (.jpg)
into Flash
Player 6 or
higher movies.
Flash Player 8
movies can also
load GIF, PNG,
and progressive
JPEG images
into Movie Clip
targets.
unloadMovie Yes Removes an timeline.unloadMovie();
externally
M, A loaded movie myMC.unloadMovie();
file (.swf) or
image file from
the main movie.
This method
enables you to
dump
movieassets
when they are
no longer
needed. Use
this method for
assets loaded
into Movie Clip
targets.
loadVariables Yes Loads external timeline.loadVariables(path, send
text-based data variables*);
M, A into the movie.
This method myMC.loadVariables(“info.txt”);
enables you to
access data (in *See note in loadMovie. We discuss
the form of load Variables() and the LoadVars
variable object in Chapter 29, “Sending Data
name/value In and Out of Flash.”
pairs) from
server-side
scripts or text

Prof. Giannina Núñez Marín Guía de ActionScript 37


Table 25-2: Common Movie and Movie Clip Methods
Open table as spreadsheet
Categor Method Flas Definition Usage
y h4
files, and place
it in a Movie Clip
target.
getBytesLoaded No Returns the timeline.getBytesLoaded();
number of bytes
M that have loadBytes =
streamed into myMC.getBytesLoaded();
the Flash Player
for a specified
Movie Clip (or
movie).
getBytesTotal No Returns the total timeline.getBytesTotal();
file size (in
M bytes) for a totalBytes = myMC.getBytesTotal();
loading movie or
Movie Clip. loadBytes =
Combined with myMC.getBytesLoaded();
getBytesLoaded
(), you can use newPercent =
this method to (loadBytes/totalBytes)*100;
calculate the
movie’s loaded
percentage.
getSWFVersion No Returns the timeline.getSWFVersion();
version of the
Flash movie as This method can only be invoked
a number. For from Flash movies created for Flash
example, if you Player 7 or higher.
create a Flash
movie (.swf) to myMC.getSWFVersion();
be Flash Player
4-compatible,
you can check
the version
number of
that .swf from a
Flash Player 7-
compatible
movie file (.swf).
M = Method; A = Action

Prof. Giannina Núñez Marín Guía de ActionScript 38


Figure 25-3: Common methods of the MovieClip object
Cross-Reference Figure 25-3 and Table 25-2 do not contain all methods of the
MovieClip class. For comprehensive descriptions and usage of the
methods, refer to the Flash ActionScript Bible series by Robert
Reinhardt and Joey Lott (Wiley).

Here's how you create a simple example of onClipEvent() in action:

1. Open a new Flash document (File ⇨ New).


2. Draw any artwork you wish, and make the artwork a Movie Clip symbol.
3. Select the Movie Clip instance on the Stage. In the Property inspector, name the
instance mcTracker.
4. With the mcTracker instance selected on the Stage, open the Actions panel (F9).
Type the following code into the Script pane:
5. onClipEvent (mouseMove){
6. this._x = _root._xmouse;
7. this._y = _root._ymouse;
8. updateAfterEvent();
9. }

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.

10. Save your Flash document as tracker_oce.fla, and test it (Ctrl+Enter or


+Enter). As you move the mouse, the artwork will follow the mouse.

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

Prof. Giannina Núñez Marín Guía de ActionScript 39


In Flash Player 6 and higher, event handlers for MovieClip objects can be written and
executed from any other event handler. This means that you can code the same event
handlers used for onClipEvent() in keyframe or Button instance actions. While this may
not seem like a monumental leap forward, this new event model enables you to create
event handlers that are not directly attached to physical instances of a Movie Clip on the
Stage. For a summary of common event methods, see Table 25-3.

Table 25-3: Common Flash Player 5 and Higher Event Handlers


Open table as spreadsheet
Category onClipEvent Event Definition Usage
(FP5+) Handler
(FP6+)
Playback load onLoad This event is onClipEvent(load){
triggered when (A)
a Movie Clip trace( _name + “ has
instance first loaded.”);
appears on the
Stage; (B) a new }
instance is added
with attachMovie or OR
duplicateMovieClip;
or (C) an external
Flash movie file
(.swf) is loaded into
a Movie Clip target.
Note: The onLoad MovieClip.prototype.onLoad
method does not = function(){
function properly on
individual trace(“A movie or Movie Clip
instances. When a has loaded.”);
Flash movie file
(.swf) loads into a };
level or a Movie
Clip target, any
existing methods
will be overwritten,
including onLoad.
See the Usage
example to see
how onLoad can be
used. The onLoad
method, however,
is useful for setting
parameters for
components that

Prof. Giannina Núñez Marín Guía de ActionScript 40


Table 25-3: Common Flash Player 5 and Higher Event Handlers
Open table as spreadsheet
Category onClipEvent Event Definition Usage
(FP5+) Handler
(FP6+)
are added via
ActionScript.
unload onUnload This event occurs onClipEvent(unload){
when (A) a Movie
Clip instance exits trace( _name + “ has
the Stage (just after unloaded.”);
the last frame has
played on the Main }
Timeline), or (B) an
external Flash OR
movie file (.swf) is
unloaded from a mcHolder.onUnload =
Movie Clip target. function(){
Actions within this
handler type will be trace(this._name + “ has
executed before unloaded.”);
any actions in the
keyframe };
immediately after
the Movie Clip’s
departure
keyframe.
enterFrame onEnterFrame This event onClipEvent(enterFrame){
executes when
each frame on a trace( _name+ “ is playing.”);
Movie Clip
instance’s timeline }
is played. The
actions within this OR
event handler will
be processed after mcHolder.onEnterFrame =
any actions that function(){
exist on the
keyframes of the trace(_name + “ is playing.”);
Movie Clip
Timeline. Note that };
enterFrame events
will execute
repeatedly (at the
same rate as the

Prof. Giannina Núñez Marín Guía de ActionScript 41


Table 25-3: Common Flash Player 5 and Higher Event Handlers
Open table as spreadsheet
Category onClipEvent Event Definition Usage
(FP5+) Handler
(FP6+)
movie’s frame
rate), regardless of
whether any
timelines within the
movie are actually
playing frames.
User mouseMove onMouseMove This event is onClipEvent(mouseMove){
Input triggered each time
the mouse moves var myX = _root._xmouse;
anywhere on the
Stage. All Movie var myY = _root._ymouse;
Clip instances with
this event handler if(this.hitTest(myX, myY,
defined receive this true) == true){
event. Combined
with the hitTest() trace(“Mouse move over
method, this event MC.”);
can be used to
detect mouse }
movements over
Movie Clip }
instances.
OR

mcHolder.onMouseMove =
function(){

var myX:Number =
_root._xmouse;

var myY:Number =
_root._ymouse;

if(this.hitTest(myX, myY,
true)){

trace(“Mouse move over “ +


this._name);

Prof. Giannina Núñez Marín Guía de ActionScript 42


Table 25-3: Common Flash Player 5 and Higher Event Handlers
Open table as spreadsheet
Category onClipEvent Event Definition Usage
(FP5+) Handler
(FP6+)

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);

Prof. Giannina Núñez Marín Guía de ActionScript 43


Table 25-3: Common Flash Player 5 and Higher Event Handlers
Open table as spreadsheet
Category onClipEvent Event Definition Usage
(FP5+) Handler
(FP6+)

};
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);

};

Prof. Giannina Núñez Marín Guía de ActionScript 44


Table 25-3: Common Flash Player 5 and Higher Event Handlers
Open table as spreadsheet
Category onClipEvent Event Definition Usage
(FP5+) Handler
(FP6+)
keyDown onKeyDown This event occurs onClipEvent(keyDown){
when the user
presses a key. newKey = Key.getCode();
Combined with the
Key.getCode myKey = Key.UP;
method, you can
use this event if(newKey == myKey){
handler to detect
unique key trace(“UP arrow is
presses. pressed.”);

Note: It’s better to }


use
Key.addListener() }
with a listener
object to detect key
down events.
keyUp onKeyUp This event happens onClipEvent(keyUp){
when the user
releases a key newKey = Key.getCode();
(when the finger
leaves the key). It myKey = Key.LEFT;
provides the same
functionality as the if(newKey == myKey){
keyDown event.
trace(“LEFT arrow
Note: It’s released.”);
preferable to use
Key.addListener() }
with a listener
object to detect key }
down events. We
discuss this
advanced use of
the Key class in the
Flash ActionScript
Bible series by
Robert Reinhardt
and Joey Lott
(Wiley).

Prof. Giannina Núñez Marín Guía de ActionScript 45


Table 25-3: Common Flash Player 5 and Higher Event Handlers
Open table as spreadsheet
Category onClipEvent Event Definition Usage
(FP5+) Handler
(FP6+)
External data onData This event is onClipEvent(data){
Input triggered when (A)
the loadMovie trace(“New data received.”);
action retrieves an
external Flash }
movie file (.swf)
and puts it in a OR
Movie Clip target,
or (B) the data from mcHolder.onData =
a file or script with function(){
the loadVariables
action (targeted at trace(“New data received.”);
a Movie Clip
instance) is finished }
loading.

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:

1. Create a new Flash document.


2. Draw some artwork, and make it a Movie Clip symbol.
3. Select the new instance on the Stage. Name the instance mcTracker in the
Property inspector.

Prof. Giannina Núñez Marín Guía de ActionScript 46


4. Create a new layer on the Main Timeline (that is, Scene 1). Name the layer
actions.
5. Select frame 1 of the actions layer, and open the Actions panel (F9). Type the
following code into the Script pane:
6. var mcTracker:MovieClip;
7. mcTracker.onMouseMove = function (){
8. this._x = _root._xmouse;
9. this._y = _root._ymouse;
10. updateAfterEvent();
11. };

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.

12. Save your Flash document as tracker_eventmodel.fla, and test it (Ctrl+Enter or


+Enter). The artwork will follow your mouse pointer as you move it on the
Stage.

On the CD-You can find the completed document, tracker_eventmodel.fla, in the


ROM ch25 folder of this book's CD-ROM. You will also find another
document, tracker_eventmodel_adv.fla, which uses multiple event
handlers.

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."

Prof. Giannina Núñez Marín Guía de ActionScript 47


Sound Class

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:

Prof. Giannina Núñez Marín Guía de ActionScript 48


with (donut.hole){
_alpha = 20;
_xscale = 150;
_yscale = 150;
}

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;

The above code is also equivalent to the following:


with (donut){
hole._alpha = 20;
hole._xscale = 150;
hole._yscale = 150;
}

5.12. Funciones predefinidas

getTimer()
getVersion()
parseFloat()
parseInt()
escape()
unescape()

5.13. Funciones definidas por el usuario

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.

5.14. Uso del texto

Prof. Giannina Núñez Marín Guía de ActionScript 49


En una aplicación de Flash se puede colocar un bloque texto en cuadro de texto (creado con la
herramienta texto de la barra de herramientas) o usando el UI Componente TextArea.

Cuadro de texto (UI Component):


1. Agregue una instancia del TextArea en la escena.
2. En los parámetros del Inspector de Propiedades
a. Editable –True si desea que el usuario escriba un texto.
b. HTML – True si se desean interpretar etiquetas HTML.
c. Escribir un nombre para la instancia del componente.
3. El contenido de esta área se puede escribir en un script de frame, en la propiedad text del
nombre de la instancia especificada en el paso 2c).
Ejemplo:
En el campo instance name del inspector de propiedades de componente
textarea1_txt
En el script-frame
textarea1_txt.text ="La vida es bella <br/> pero más hermoso es la fe en Dios"

5.14.1. Login con variables de texto


1. Crear dos rótulos con texto estático “Nombre de usuario” y “Contraseña”
2. Crear dos text fields uno en cada capa.
3. En el inspector de propiedades defina asigne el tipo Input Text, agregue un
nombre de instancia y el campo para contraseña active la opción Password
y restringa la longitud a 6. No asigne nombre a las variables.
4. Crear un símbolo movieClip que emitirá un mensaje de error. Este
movieClip debe iniciar en stop y el primer frame debe ser vacío. Arrastre
una instancia a una capa del timeline de la escena.
5. En el movieClip de error, agregar en una capa de etiquetas donde se, la
etiqueta que indica donde se inicia la reproducción del mensaje de error.
En el último frame colocar gotoAndStop(1);
6. En la línea principal cree el arte para cuando el acceso sea exitoso, para
ello coloque una etiqueta.
7. Cree un botón de aceptar o enviar datos. En este botón agregue el código
que verifique si la propiedad text del nombre de usuario y contraseña son
iguales a un par previamente establecido, y enviar el control al frame
correspondiente.
Índice
Guía de Macromedia Flash.............................................................................................................1
1. Tipos de archivos en Flash...........................................................................................................1
1.1. Documentos Flash ................................................................................................................1
1.2. Películas Flash .....................................................................................................................1
1.3. Otros documentos Flash........................................................................................................1
2. Interface, Capas y Frames en Timeline........................................................................................2
2.1. Barra de Herramientas (Tools)..............................................................................................2
2.2. Frames en Timeline...............................................................................................................3
2.3. Layers en Timeline...............................................................................................................5
2.4. Creación de símbolos............................................................................................................7

Prof. Giannina Núñez Marín Guía de ActionScript 50


3. Planificación de un Proyecto.......................................................................................................8
4. Probar y publicar..........................................................................................................................8
5. ActionScript 2.0...........................................................................................................................8
5.1. Conceptos básicos de orientación a eventos.........................................................................9
5.1.1. Event Handler................................................................................................................9
5.1.2. Eventos...........................................................................................................................9
5.1.3. Conductas.....................................................................................................................10
5.1.4. Script............................................................................................................................10
5.2. Acciones básicas.................................................................................................................11
5.2.1. Controlar la línea de tiempo.........................................................................................11
5.2.2. Browser / Network.......................................................................................................12
5.2.3. Controlar MovieClip....................................................................................................13
5.2.4. Funciones misceláneas.................................................................................................13
5.3. Event Handler.....................................................................................................................13
5.4. Script de frame....................................................................................................................14
5.5. Eventos del mouse..............................................................................................................14
5.6. Eventos del teclado.............................................................................................................16
5.7. Manejo de múltiples timeline (Rutas).................................................................................17
5.8. Directiva de compilador include........................................................................................18
5.9. Elementos básicos del lenguaje..........................................................................................18
5.9.1. Variables......................................................................................................................18
5.9.2. Constantes de cadenas..................................................................................................19
5.9.3. Expresiones..................................................................................................................20
5.9.4. Operadores...................................................................................................................20
5.9.5. Condicional if...............................................................................................................20
5.9.6. Condiciones con switch y case....................................................................................20
5.9.7. Ciclos...........................................................................................................................21
5.10. Inspector de Propiedades y Panel Info..............................................................................21
5.11. Propiedades.......................................................................................................................22
5.11.1. Movie Clip Methods..................................................................................................28
5.11.2. Event Methods: The More Flexible Movie Clip Handler..........................................39
5.11.3. Other Classes and Functions that Use the MovieClip Object....................................47
5.11.4. MovieClip..................................................................................................................48
5.12. Funciones predefinidas.....................................................................................................49
5.13. Funciones definidas por el usuario...................................................................................49
5.14. Uso del texto.....................................................................................................................49
5.14.1. Login con variables de texto......................................................................................50

Cronograma

Semana 1 Clase 1 Presentación del curso


Clase 2 Discusión de Ciclo de vida de producto multimedia
Semana 2 Clase 3 Propiedades de película. Barra de herramientas y propiedades de las
herramientas
Clase 4 Tipos de archivos flash. Introducción a los tipos de capas y frames.
Capas folder, normal. Frames: keyframe, blank, span.

Prof. Giannina Núñez Marín Guía de ActionScript 51


Semana 3 Clase 5 Técnicas de animación: cuadro, tween shape, tween motion. Capas
Guide, Motion Guide. Animación orientada a una ruta.
Clase 6 Capas de máscara. Animación con máscara de tipo gráfico, movie clip,
texto. Biblioteca. Símbolos: gráfico, movie clip y botón.
Semana 4 Clase 7 Revisión de aplicación de técnicas de animación. Laboratorio para
evaluar.
Clase 8 Evaluación de laboratorio.
Semana 5 Clase 9 Introducción a ActionScript (Event handler, evento, conductas, eventos
del mouse). Práctica de enlace entre dos escenas, loop de escenas.
Clase 10 Explicación de rutas relativas y rutas absolutas.
Semana 6 Clase 11 Sentencias básicas. Propiedades de MovieClip. Práctica de arrastrar
objetos sobre otro.
Clase 12 Componente Loader (Cargador). Autenticación de usuario con
textField. Enlace entre películas.
Semana 7 Clase 13
Clase 14
Semana 8 Clase 15
Clase 16
Semana 9 Clase 17
Clase 18
Semana 10 Clase 19
Clase 20
Semana 11 Clase 21
Clase 22
Semana 12 Clase 23
Clase 24
Semana 13 Clase 25
Clase 26
Semana 14 Clase 27
Clase 28
Semana 15 Clase 29
Clase 30
Semana 16 Clase 31
Clase 32
Discusión de las bases de programación orientada a eventos. Resultado de monografía.
.

• 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

Prof. Giannina Núñez Marín Guía de ActionScript 52


o Entendiendo los distintos tipos de archivos
o Crear y Guardar archivos de Flash
o Personalizando tu lugar de trabajo
o Personalizando tus teclas de trabajo
o Ajustando las propiedades del documento
• Dibujando en Flash
o Creando y trabajando con formas
o Cómo seleccionar y modificar formas
o Uso de rectángulos y herramientas
o La herramienta “PolyStar”
o Dibujando líneas
o Técnicas de rellenado
o Uso de la herramienta Lápiz
o Uso de la herramienta de libre transformación
o Creación de gradientes
o Modificación de gradientes
o Aplicación de trasparencias a las formas
o Uso de la herramienta Vista
o Herrmienta Color
o Herramienta Borrador
o El panel de colores
o Alineación del Panel
• Trabajando con Texto
o Comprendiendo los tipos de texto
o Creación de texto estático
o Modificando las propiedades del texto
o Uso de campos de texto dinámicos
• Trabajando con Simbolos
o Explicación de los símbolos y las instancias
o Creación de los símbolos en Flash
o Edición de Símbolos
o Editando las instancias de los símbolos
o Cómo organizar nuestra librería.
• Uso del TimeLine (Línea de tiempo)
o Comprendiendo el TimeLine
o Trabajando con capas
o Organizaciónd de capas
o Creando Máscaras
o Entendiendo los diferentes tipos de frames
o Trabajando con frames y keyframes
o Creación de una animación frame a frame
o Uso de la “capa cebolla”
o Edición de múltiples frames
o Uso del TimeLime Avanzado
o Uso de la herramienta Art Deco

Prof. Giannina Núñez Marín Guía de ActionScript 53


• Creación de Morphing
o Cómo hacer un morphing vectorial
o Creación de un morphing paso a paso
o Trucos para creación de formas
o Modificando múltiples elementos de una vez
o Técnicas Avanzadas
o Perfeccionando el Morphing
• Creación de Morphing en Movimiento
o Comprendiendo los Morphing en movimiento
o Explicando la técnica paso a paso
o Modificación del PATH
o Uso del editor de Movimiento
o Uso de las propiedades de animación
o Anidando Animaciones con los Movie Clips
o Técnicas de Animación Avanzada
• Trabajando con “Bones”
o Creando un sistema de “Bones”
o Animación un sistema de “Bones”
• Trabajando con elementos 3D
o Uso de la herramienta de translación 3D
o Uso de la herramienta de rotación 3D
o Animación de elementos en 3D
o Ordenación de MAIL con Loops
• Filtros y modos de Blend
o Usando Filtros en Flash
o Aplicando Filtros
o Animación de Filtros
o Comprendiendo el modo BLEND
o Uso de los modos BLEND
• Uso de gráficos Bitmap
o Dónde econtrar Imágenes
o Importanto Bitmaps
o Compresión de Bitmaps
o La herramienta Lazo
o Vectorización de un Bitmap
o Importación de una secuencia de Bitmaps
o Técnicas de Animación con Bitmaps
• Usando sonido en Flash
o Dónde Encontrar sonidos
o Importanto sonidos
o Modificando las propiedades del sonido
o Comprendiendo los diferentes tipos de sonido
o Trabajando con efectos de sonido
• Uso del vídeo
o Uso de Adobe Media Encoder

Prof. Giannina Núñez Marín Guía de ActionScript 54


o El componente FLVplayback
o Creación de vídeos en Flash
• Introducción a ActionScript 3.0
o Qué es ActionScript
o Trabajando con MovieClips
o Modificando MovieClips con AS
o Creación y programación de Botones
o Añadiendo Interactividad
o Uso de ActionScript para controlar la TimeLine
o Navegando con ActionScript
• Integración
o Entendiendo los archivos XFL
o Creación de XFL y SWF en Indesign
o Generando XFL desde After effects
o Integración SoundBooth
o Integración con Ilustrator
o Integración de Flash con Dreamweaver
• Publicando y Exportando Contenidos en Flash
o Comprendiendo la publicación en Flash.
o Publicando Flash en HTML
o Publicando a AIR
o Exportación de imágenes
o Exportación de películas
• Conclusión
o Despedida

Módulo II: Programación Flash con Actionscript 3.0

• 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

Prof. Giannina Núñez Marín Guía de ActionScript 55


o Los parámetros de las funciones
o Devolviendo valor
o Uso de varibales locales
• Trabajando con Objetos
o Explicación de la sintaxis del punto
o Controlando las propiedades
o Creación de objetos dinámicamente
o Controlando movie clips anidados
• Uso de Eventos
o Entendiendo los eventos
o Programando los clics de ratón
o Otros eventos con el ratón
o Eventos del teclado
o Quitando los eventos
• Creación y uso de condicionales
o Uso del condicional en AS 3.0
o Trabajando el la sentencia IF
o Entendiendo los operadores de condición
o Escribiendo Sentencias IF
o Escribiendo sentencias ELSE IF
o Escribiendo sentencias SWITCH-CASE
o Detectando colisiones
• Uso de matemáticas para realizar tareas
o Comprendiendo los operadores matemáticos
o Entendiendo los tipos de datos
o Alineando objetos en el escenario
o Uso aleatorio de numeros entre el 0 y 1
o Uso de un rango de números
o Creación de la función RANDOM-NUMBER
o Creación de una calculadora en Flash
• Creación y Uso de Arrays
o Creando nuestro primer ARRAY
o Indexación de ARRAYS
o Métodos alternativos para creación de ARRAYS
o Buscando Índices
o Creación de un juego con ARRAYS
• Creación y uso de Loops
o Explicación “¿Qué son los Loops?”
o Creación de Loops
o Uso de Loops
o Ordenación de MAIL con Loops
o Uso de WHILE en Loops
• Usando Clases
o Explicación “¿Qué es una clase?”
o Tipos de Clases

Prof. Giannina Núñez Marín Guía de ActionScript 56


o Comprendiendo los “Métodos”
o Uso de propiedades
o Múltiples Clases
o Creando un grupo
• Tratamiento de texto
o Carga de texto externo
o Adición de texto
o Lectura de HTML
o Links con CSS
• Carga de Medios
o Carga de Bitmaps
o Carga de archivos SWF
o Creación de un PRELOADER
o Carga del sonido
o Cómo detener el sonido
o Controlando el volumen
o Uso del vídeo
o Carga del vídeo
o Controlando el playback del vídeo
• Creación de una calculadora
o Ejemplo de la práctica
o Configuración de variables
o Añadir eventos
o Controlando las entradas numércias
o Configurando los botones
o Buscando la operación actual
o Captura de datos
o Ejecución de cálculos
o Creando una clase
• Solucionando problemas
o Identificando problemas
o Cómo solucionar Errores
o Obteniendo ayuda adicional
• Conclusión
o Despedida del módulo de programación

Módulo III: Creación de un proyecto web en Flash

• 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

Prof. Giannina Núñez Marín Guía de ActionScript 57


http://www.freeopenbook.com/flash8-bible/BBL0050.html

Prof. Giannina Núñez Marín Guía de ActionScript 58

Potrebbero piacerti anche