Guía de Macromedia Flash

84
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. Prof. Giannina Núñez Marín Guía de ActionScript 1

Transcript of Guía de Macromedia Flash

Page 1: Guía de Macromedia Flash

Guía de Macromedia Flash

1. Tipos de archivos en Flash1.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 ActionScript1

Page 2: Guía de Macromedia Flash

2. Interface, Capas y Frames en Timeline2.1. Barra de Herramientas (Tools)

Lateral izquierdo de la sección superior de la barrao Selection: Permite seleccionar o Line:o Peno Ovalo Pencilo Free Transformo Ink bootleo Eyedropper

Lateral derecho de la sección superior de la barrao Subselectiono Lassoo Texto Rectangleo Brusho Fill transformo Paint Bucketo Eraser

Sección Viewo Hando Zoom

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

Page 3: Guía de Macromedia Flash

Sección Colorso Strokeo Fillo Black&Whiteo No coloro Swap colors

Sección Optionso 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.

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.

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

Page 4: Guía de Macromedia Flash

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 ActionScript4

Page 5: Guía de Macromedia Flash

2.3. Layers en Timeline

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.

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

Page 6: Guía de Macromedia Flash

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

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:

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

Page 7: Guía de Macromedia Flash

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. 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 clipo _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 Proyecto1. 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.

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

Page 8: Guía de Macromedia Flash

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 publicarCuando 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.0ActionScript 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:

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.

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

Page 9: Guía de Macromedia Flash

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)

Eventos y Handlers

Event Type Event handler Ejemplo

Playback Basado en el tiempo Keyframes Objeto MovieClip Objeto NetStream

Play hasta llegar a un frame Instancia de movieClip monitorea el tiempo de películaCuando un video se termina de reproducir, inicia otro

Mouse Entrada del usuario Objeto Button Objeto MovieClip Objeto Mouse

Clic en un botónMovimiento del mouse se detecta sobre una instancia de MovieClip

Key Press Entrada del usuario Objeto Button Objeto MovieClip Objeto Key

Usuario teclea Enter para enviar datos.Alerta si una tecla está activa

Actividad en Microphone o Webcam

Entrada Audio/ Video Objeto Microphone Objeto Camera

Se muestra un gráfico cuando el usuario deja de hablar en el micrófono. Cuando se detecta movimiento en la cámara se graba.

Data Basado en el sistema Objeto MovieClip Se muestran los resultados

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

Page 10: Guía de Macromedia Flash

Event Type Event handler Ejemplo

Objetos data de 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.

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) {..}

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

Page 11: Guía de Macromedia Flash

• Un evento se asocia a event handler específico5.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

playbacknextScene(); Se mueve al primer frame de la siguiente escena play(); Activa el movimiento de una película o instancia de

movieClipstop(); Detiene el movimiento de una película o instancia de

movieClipprevFrame(); Se mueve un frame hacia atrás y detiene el playbackprevScene(); Se mueve al primer frame de la escena anteriorstopAllSounds(); Apaga todos los sonidos que se están ejecutando en

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 Browserurl – 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 playercommand args funciónfullscreen true or false True- Modo pantalla

completa sin menú.False- Tamaño especificado

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

Page 12: Guía de Macromedia Flash

en propiedadesallowscale 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 ejecutable

Abre un ejecutable en el stand-alone player. El executable debe estar en un carpeta fscommand dentro de la misma carpeta del proyector stand-alone.

quit cierra el playerfscommand(“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.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.

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

Page 13: Guía de Macromedia Flash

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.

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

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

Page 14: Guía de Macromedia Flash

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

• 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

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

Page 15: Guía de Macromedia Flash

– 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 BehaviorgetURL("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"

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

Page 16: Guía de Macromedia Flash

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:

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

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

Page 17: Guía de Macromedia Flash

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 graf1o graf2

• clip2Ruta relativa desde clip1 hasta main: _parent Ruta relativa desde clip1 hasta clip2: _parent.clip2Ruta relativa desde graf1 hasta main: _parent._parent Ruta relativa desde graf1 hasta clip2: _parent._parent.clip2Ruta relativa arriba de la actual: this._parent Ruta relativa actual: this

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.

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

Page 18: Guía de Macromedia Flash

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 movieClip1var a=exprvar b=expr_root.movieClip1_mc.z

omovieClip1_mc

En el timeline del símbolo movieClip1 se puede crear la 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 escena1a=expr

Declaración de variables:var name;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.

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

Page 19: Guía de Macromedia Flash

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 textonombre_txtEn el campo var del inspector de propiedadesnombre_varEn el script-framenombre_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

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. Operadoreso 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;}

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

Page 20: Guía de Macromedia Flash

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 : 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) {

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

Page 21: Guía de Macromedia Flash

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=0while (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.

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

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

Page 22: Guía de Macromedia Flash

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

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 4

Flash 5+

Flash 8

Definition

Position _x MC

Movie

RW

RW

RW

RW

RW

RWThe horizontal distance between a Movie Clip’s center point and the top-left corner of the stage upon which it resides. It increases

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

Page 23: Guía de Macromedia Flash

Category Property Timeline Flash 4

Flash 5+

Flash 8

Definition

as the clip moves to the right, and is measured in pixels.

_y MC

Movie

RW

RW

RW

RW

RW

RWThe vertical distance between a Movie Clip’s center point 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

MovieN/A

R

R

R

RThe horizontal distance (in pixels) between the zero point of a Movie Clip (or the Movie) and the current position of the mouse pointer.

_ymouse MC

MovieN/A

R

R

R

RThe vertical distance (in pixels) between the zero point of a Movie Clip (or the Movie) and the current position of the mouse pointer.

_rotation MC

Movie

RW

RW

RW

RW

RW

RWThe amount (in degrees) that a Movie Clip is rotated off plumb. It returns values set both by the Transform panel (or Transform tool) and by ActionScript.

_xscale MC

Movie

RW

RW

RW

RW

RW

RWThe width of a Movie Clip instance (or Movie) as a percentage of the parent symbol’s actual size.

Size _yscale MC

Movie

RW

RW

RW

RW

RW

RWThe height of a Movie Clip instance (or Movie) as a percentage of the parent

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

Page 24: Guía de Macromedia Flash

Category Property Timeline Flash 4

Flash 5+

Flash 8

Definition

symbol’s actual size.

_width MC

Movie

R

R

RW

R

RW

RThe width (in pixels) of a Movie Clip or the main Movie 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

Movie

R

R

RW

R

RW

RThe height (in pixels) of a movie clip or the main movie 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

Movie

RW

RW

RW

RW

RW

RWThe amount of transparency of a Movie Clip or Movie. It is measured as a percentage: 100 percent is completely opaque; 0 percent is completely transparent.

_visible MC

Movie

RW

RW

RW

RW

RW

RWA Boolean value that indicates whether a Movie 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

Movie

N/A

N/A

N/A

N/A

RW

RWThis new property in Flash Player 8 enables you to add visual effects to MovieClip objects. The filters property

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

Page 25: Guía de Macromedia Flash

Category Property Timeline Flash 4

Flash 5+

Flash 8

Definition

uses an array to describe which filters have been applied to the clip.

transform MC

Movie

N/A

N/A

RW

N/A

RW

RWThis new property in Flash Player 8 enables you to 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

Movie

RW

R

RW

R

RW

RThis property returns or reassigns the Movie Clip instance’s name (as listed in the Property inspector).

_target MC

Movie

R

R

R

R

R

RThis property returns the exact string in Slash notation that you'd use to refer to the Movie Clip instance. To retrieve the dot syntax path, use eval(_target).

_droptarget MC

Movie

R

R

R

R

R

RThis property returns the name (in Slash notation) of 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.

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

Page 26: Guía de Macromedia Flash

Category Property Timeline Flash 4

Flash 5+

Flash 8

Definition

_lockroot MC

Movie

RW

RW

RW

RW

RW

RWThis property, only available to Flash Player 7 or higher-compatible movies, enables you to control how a _root reference is interpreted. If the _lockroot property of a 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

Movie

N/A

N/A

R

R

R

RThis property returns a reference to the parent 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 Path

_url MC

Movie

R

R

R

R

R

RThis property returns the complete path to the Flash 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

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

Page 27: Guía de Macromedia Flash

Category Property Timeline Flash 4

Flash 5+

Flash 8

Definition

being viewed if it is not on a particular server.

Timeline _currentframe MC

Movie

R

R

R

R

R

RThis property returns the number of the current frame (for example, the frame on which the Playhead currently resides) of the Movie or a Movie Clip instance.

_totalframes MC

Movie

R

R

R

R

R

RThis property returns the number of total frames in a Movie or Movie Clip instance’s timeline.

_framesloaded MC

Movie

R

R

R

R

R

RThis property returns the number of frames that have 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

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

Page 28: Guía de Macromedia Flash

Category Property Timeline Flash 4

Flash 5+

Flash 8

Definition

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)

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

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

Page 29: Guía de Macromedia Flash

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-ROM  Use the propInspector Movie Clip in the Library of the

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:

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

Category

Method Flash 4

Definition Usage

PositionhitTest

No Determines if a timeline.hitTest(MovieClip object);

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

Page 30: Guía de Macromedia Flash

Table 25-2: Common Movie and Movie Clip Methods Open table as spreadsheet

Category

Method Flash 4

Definition Usage

M MovieClip object overlaps with the boundaries of another MovieClip object, or if an X-Y coordinate intersects with a MovieClip instance. For more information on this method, see Chapter 27, “Interacting with Movie Clips.”

OR

timeline.hitTest(x coordinate, y coordinate, shapeFlag);

myMC.hitTest(myOther_mc);

myMC.hitTest(_root._xmouse,

_root._ymouse,true);

startDrag

M, AYes Enables the

user to move a Movie Clip instance on the Stage. The Movie Clip moves (or 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

timeline.startDrag(lock, min X, min Y, max X, max Y);

myMC.startDrag(false,200,0,200,200);

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

Page 31: Guía de Macromedia Flash

Table 25-2: Common Movie and Movie Clip Methods Open table as spreadsheet

Category

Method Flash 4

Definition Usage

(in the parent symbol or timeline space). Constraining the drag area is useful for slider controls.

stopDrag

M, AYes Stops any

startDrag action currently in progress. No target needs to be specified with this action.

timeline.stopDrag();

myMC.stopDrag();

Playbackplay

M, AYes Starts playback

from the current position of the Playhead on a specified timeline.

timeline.play();

_root.play(); // plays the Main Timeline

_root.myMC.play(); // plays myMC

stop

M, AYes Stops playback

on a specified timeline.

timeline.stop();

_root.stop(); // stops the Main Timeline

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

gotoAndPlay

M, AYes Jumps the

Playhead of a specified timeline to a label, frame number, or expression, and starts playing from there.

timeline.gotoAndPlay(position);

_root.myMC.gotoAndPlay(“start”);

// plays from the “start” label of the myMC

timeline

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

Page 32: Guía de Macromedia Flash

Table 25-2: Common Movie and Movie Clip Methods Open table as spreadsheet

Category

Method Flash 4

Definition Usage

gotoAndStop

M, AYes Jumps the

Playhead of a specified timeline to a label, frame number, or expression, and stops playback.

timeline.gotoAndStop(position);

_root.myMC.gotoAndStop(“mute”);

// stops playback on the “mute” label of myMC

nextFrame

M, AYes Moves the

Playhead of the specified timeline to the next frame.

timeline.nextFrame();

_root.myMC.nextFrame();

prevFrame

M, AYes Moves the

Playhead of the specified timeline to the previous frame.

timeline.prevFrame();

_root.myMC.prevFrame();

Internal

Assets

createEmptyMovieClip

M

NoMakes a blank (empty) Movie Clip instance on the Stage (or nested in another Movie Clip instance). The new instance is placed directly above the parent instance, at a specified depth. Higher depth numbers appear above lower depth numbers (for

timeline.createEmptyMovieClip(new name*, depth);

_root.createEmptyMovieClip(“myMC”, 1);

myMC._x = 50;

*You should only specify an instance name for the new MovieClip object — not a new path. You can only create new instances relative to the instance invoking the method.

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

Page 33: Guía de Macromedia Flash

Table 25-2: Common Movie and Movie Clip Methods Open table as spreadsheet

Category

Method Flash 4

Definition Usage

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

M, AYes Makes a copy of

an existing Movie Clip instance on the Stage (or nested in another Movie Clip). The new copy is placed directly above 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 depth 1).

timeline.duplicateMovieClip(new name*, depth);

myMC.duplicateMovieClip(“myMC_2”, 20);

myMC_2._x = 200;

*See note for the createEmptyMovieClip() method.

  remove MovieClip Yes Deletes a

timeline.removeMovieClip();

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

Page 34: Guía de Macromedia Flash

Table 25-2: Common Movie and Movie Clip Methods Open table as spreadsheet

Category

Method Flash 4

Definition Usage

M, A previously duplicated 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.

myMC_2.removeMovieClip();

  attachMovie

MNo Places an

instance of from the Library into the specified timeline. Each attached instance requires a unique name and depth. Attached Movie Clip instances can be deleted with removeMovieClip.

timeline.attachMovie(ID*, new name, depth);

_root.attachMovie(“eye”, “eye_1”, 1);

*You need to specify a unique identifier to linked Movie Clip symbols in the Library, using the Linkage Properties.

  getDepth

MNo

Returns the current depth of a duplicated (or attached) MovieClip object.

timeline.getDepth();

_root.attachMovie(“eye”, “eye_1”, 1); trace(eye_1.getDepth());

*If you attempt to retrieve the depth of a Movie Clip instance that you

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

Page 35: Guía de Macromedia Flash

Table 25-2: Common Movie and Movie Clip Methods Open table as spreadsheet

Category

Method Flash 4

Definition Usage

This method only works in Flash 6 movies played in Flash Player 6.

manually placed on the Stage, then ActionScript will return -16383 as the value of getDepth().

  swapDepths

MNo Switches the

depth placement of two duplicated or attached Movie Clips. This method is useful for placing one Movie Clip instance in front of (or behind) another instance.

timeline.swapDepths(depth);

timeline.swapDepths(target);

eye_1.swapDepths(10); // depth

eye_1.swapDepths(eye_2); // target

  getNextHighestDepth

M

NoDetermines if any objects currently exist within depth slots of the 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

timeline.getNextHighestDepth();

var nextSlot =

myMC.getNextHighestDepth();

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

Page 36: Guía de Macromedia Flash

Table 25-2: Common Movie and Movie Clip Methods Open table as spreadsheet

Category

Method Flash 4

Definition Usage

can use this method in conjunction with 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

MNo

Returns the name of an object occupying the specified depth 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.

timeline.getInstanceAtDepth(depthSlot);

var isOccupied = myMC.getInstanceAtDepth(1);

createTextField

MNo

Adds a new TextField object (that is, a dynamic or input text field) to the MovieClip object. This method enables you to add new

timeline.createTextField (name, depth, x position, y position, width, height);

myMC.createTextField(“display_txt”, 1, 10, 10, 300, 50);

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

Page 37: Guía de Macromedia Flash

Table 25-2: Common Movie and Movie Clip Methods Open table as spreadsheet

Category

Method Flash 4

Definition Usage

text fields to your movie at run time.

This method works only when issued from a Flash Player 6 or higher movie.

  setMask

MNo

Assigns a MovieClip object to be used as the mask for another MovieClip object.

This method works only when issued from a Flash Player 6 or higher movie.

timeline.setMask(instanceName);

myMC.setMask(clip_mc);

External Assets

loadMovie

M, AYes Loads an

external movie file (.swf) or image file into the main movie. As one of the most powerful features of Flash, this method enables you to break up your Flash movie into several smaller components,

timeline.loadMovie(path, send variables*);

myMC.loadMovie(“menu.swf”);

OR

myMC.loadMovie(“image.jpg”);

*You can also send Flash variables to the newly loaded .swf file with an optional "GET" or "POST" parameter. We discuss this in Chapter 24, “Knowing the Nuts and Bolts of Code.”

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

Page 38: Guía de Macromedia Flash

Table 25-2: Common Movie and Movie Clip Methods Open table as spreadsheet

Category

Method Flash 4

Definition Usage

and load them as needed. This method can load movie files (.swf) or 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

M, AYes Removes an

externally loaded movie 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.

timeline.unloadMovie();

myMC.unloadMovie();

  loadVariables

M, AYes Loads external

text-based data into the movie.

timeline.loadVariables(path, send variables*);

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

Page 39: Guía de Macromedia Flash

Table 25-2: Common Movie and Movie Clip Methods Open table as spreadsheet

Category

Method Flash 4

Definition Usage

This method enables you to access data (in the form of variable name/value pairs) from server-side scripts or text files, and place it in a Movie Clip target.

myMC.loadVariables(“info.txt”);

*See note in loadMovie. We discuss load Variables() and the LoadVars object in Chapter 29, “Sending Data In and Out of Flash.”

getBytesLoaded

MNo Returns the

number of bytes that have streamed into the Flash Player for a specified Movie Clip (or movie).

timeline.getBytesLoaded();

loadBytes = myMC.getBytesLoaded();

getBytesTotal

MNo Returns the total

file size (in bytes) for a loading movie or Movie Clip. Combined with getBytesLoaded(), you can use this method to calculate the movie’s loaded percentage.

timeline.getBytesTotal();

totalBytes = myMC.getBytesTotal();

loadBytes = myMC.getBytesLoaded();

newPercent = (loadBytes/totalBytes)*100;

getSWFVersion No Returns the version of the Flash movie as

timeline.getSWFVersion();

This method can only be invoked from Flash movies created for

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

Page 40: Guía de Macromedia Flash

Table 25-2: Common Movie and Movie Clip Methods Open table as spreadsheet

Category

Method Flash 4

Definition Usage

a number. For example, if you create a Flash movie (.swf) to be Flash Player 4-compatible, you can check the version number of that .swf from a Flash Player 7-compatible movie file (.swf).

Flash Player 7 or higher.

myMC.getSWFVersion();

M = Method; A = Action

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.

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

Page 41: Guía de Macromedia Flash

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-ROM  You can find a completed version of the file tracker_oce.fla in the ch25

folder of this book's CD-ROM.5.11.2. Event Methods: The More Flexible Movie Clip Handler

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 (FP5+)

Event Handler (FP6+)

Definition Usage

Playback load onLoad This event is triggered when (A) a Movie Clip instance first appears on the

onClipEvent(load){

trace( _name + “ has loaded.”);

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

Page 42: Guía de Macromedia Flash

Table 25-3: Common Flash Player 5 and Higher Event Handlers Open table as spreadsheet

Category onClipEvent (FP5+)

Event Handler (FP6+)

Definition Usage

Stage; (B) a new instance is added with attachMovie or duplicateMovieClip; or (C) an external Flash movie file (.swf) is loaded into a Movie Clip target.

}

OR

Note: The onLoad method does not function properly on individual instances. When a 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 are added via ActionScript.

MovieClip.prototype.onLoad = function(){

trace(“A movie or Movie Clip has loaded.”);

};

unload onUnload This event occurs when (A) a Movie Clip instance exits the Stage (just after the last frame has played on the Main Timeline), or (B) an

onClipEvent(unload){

trace( _name + “ has unloaded.”);

}

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

Page 43: Guía de Macromedia Flash

Table 25-3: Common Flash Player 5 and Higher Event Handlers Open table as spreadsheet

Category onClipEvent (FP5+)

Event Handler (FP6+)

Definition Usage

external Flash movie file (.swf) is unloaded from a Movie Clip target. Actions within this handler type will be executed before any actions in the keyframe immediately after the Movie Clip’s departure keyframe.

OR

mcHolder.onUnload = function(){

trace(this._name + “ has unloaded.”);

};

 enterFrame onEnterFrame This event

executes when each frame on a Movie Clip instance’s timeline is played. The actions within this event handler will be processed after any actions that exist on the keyframes of the Movie Clip Timeline. Note that enterFrame events will execute repeatedly (at the same rate as the movie’s frame rate), regardless of whether any timelines within the movie are actually playing frames.

onClipEvent(enterFrame){

trace( _name+ “ is playing.”);

}

OR

mcHolder.onEnterFrame = function(){

trace(_name + “ is playing.”);

};

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

Page 44: Guía de Macromedia Flash

Table 25-3: Common Flash Player 5 and Higher Event Handlers Open table as spreadsheet

Category onClipEvent (FP5+)

Event Handler (FP6+)

Definition Usage

User Input

mouseMove onMouseMove This event is triggered each time the mouse moves anywhere on the Stage. All Movie Clip instances with this event handler defined receive this event. Combined with the hitTest() method, this event can be used to detect mouse movements over Movie Clip instances.

onClipEvent(mouseMove){

var myX = _root._xmouse;

var myY = _root._ymouse;

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

trace(“Mouse move over MC.”);

}

}

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

}

updateAfterEvent();

};

 mouseDown onMouseDown This event occurs

onClipEvent(mouseDown){

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

Page 45: Guía de Macromedia Flash

Table 25-3: Common Flash Player 5 and Higher Event Handlers Open table as spreadsheet

Category onClipEvent (FP5+)

Event Handler (FP6+)

Definition Usage

each time the left mouse button is pressed (or down) anywhere on the Stage. All Movie Clip instances with this event handler receive this event.

myX = _root._xmouse;

myY = _root._ymouse;

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

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

triggered each time the left mouse button is released

onClipEvent(mouseUp){

myX = _root._xmouse;

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

Page 46: Guía de Macromedia Flash

Table 25-3: Common Flash Player 5 and Higher Event Handlers Open table as spreadsheet

Category onClipEvent (FP5+)

Event Handler (FP6+)

Definition Usage

(when the user lets up on the mouse button). All Movie Clip instances with this handler receive this event.

myY = _root._ymouse;

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

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

}

};

 keyDown onKeyDown

This event occurs when the user presses a key. Combined with the Key.getCode method, you can use this event

onClipEvent(keyDown){

newKey = Key.getCode();

myKey = Key.UP;

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

Page 47: Guía de Macromedia Flash

Table 25-3: Common Flash Player 5 and Higher Event Handlers Open table as spreadsheet

Category onClipEvent (FP5+)

Event Handler (FP6+)

Definition Usage

handler to detect unique key presses.

Note: It’s better to use Key.addListener() with a listener object to detect key down events.

if(newKey == myKey){

trace(“UP arrow is pressed.”);

}

}

 keyUp onKeyUp

This event happens when the user releases a key (when the finger leaves the key). It provides the same functionality as the keyDown event.

Note: It’s 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).

onClipEvent(keyUp){

newKey = Key.getCode();

myKey = Key.LEFT;

if(newKey == myKey){

trace(“LEFT arrow released.”);

}

}

External Input

data onData This event is triggered when (A) the loadMovie action retrieves an external Flash movie file (.swf) and puts it in a

onClipEvent(data){

trace(“New data received.”);

}

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

Page 48: Guía de Macromedia Flash

Table 25-3: Common Flash Player 5 and Higher Event Handlers Open table as spreadsheet

Category onClipEvent (FP5+)

Event Handler (FP6+)

Definition Usage

Movie Clip target, or (B) the data from a file or script with the loadVariables action (targeted at 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.”

OR

mcHolder.onData = function(){

trace(“New data received.”);

}

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.

4. Create a new layer on the Main Timeline (that is, Scene 1). Name the layer actions.

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

Page 49: Guía de Macromedia Flash

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-ROM  You can find the completed document, tracker_eventmodel.fla, in the

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 Feature  Flash Player 8 introduces a new MovieClip class property, transform. The

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 ActionScript49

Page 50: Guía de Macromedia Flash

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

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

Page 51: Guía de Macromedia Flash

scope. For example, in the following script, the with statement is passed the object donut.hole to change the properties of hole:

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 ActionScript51

Page 52: Guía de Macromedia Flash

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 componentetextarea1_txtEn el script-frametextarea1_txt.text ="La vida es bella <br/> pero más hermoso es la fe en Dios"

5.14.1. Login con variables de texto1. 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.

ÍndiceGuía de Macromedia Flash..............................................................................................................11. Tipos de archivos en Flash......................................................................................................1

1.1. Documentos Flash...........................................................................................................11.2. Películas Flash.................................................................................................................11.3. Otros documentos Flash..................................................................................................1

2. Interface, Capas y Frames en Timeline...................................................................................22.1. Barra de Herramientas (Tools)........................................................................................22.2. Frames en Timeline.........................................................................................................32.3. Layers en Timeline..........................................................................................................52.4. Creación de símbolos.......................................................................................................7

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

Page 53: Guía de Macromedia Flash

3. Planificación de un Proyecto...................................................................................................74. Probar y publicar......................................................................................................................85. ActionScript 2.0.......................................................................................................................8

5.1. Conceptos básicos de orientación a eventos....................................................................95.1.1. Event Handler..........................................................................................................95.1.2. Eventos....................................................................................................................95.1.3. Conductas..............................................................................................................105.1.4. Script......................................................................................................................10

5.2. Acciones básicas............................................................................................................115.2.1. Controlar la línea de tiempo..................................................................................115.2.2. Browser / Network.................................................................................................115.2.3. Controlar MovieClip..............................................................................................135.2.4. Funciones misceláneas...........................................................................................13

5.3. Event Handler................................................................................................................135.4. Script de frame...............................................................................................................135.5. Eventos del mouse.........................................................................................................145.6. Eventos del teclado........................................................................................................155.7. Manejo de múltiples timeline (Rutas)............................................................................165.8. Directiva de compilador include...................................................................................175.9. Elementos básicos del lenguaje.....................................................................................17

5.9.1. Variables................................................................................................................185.9.2. Constantes de cadenas...........................................................................................195.9.3. Expresiones............................................................................................................195.9.4. Operadores.............................................................................................................195.9.5. Condicional if........................................................................................................205.9.6. Condiciones con switch y case..............................................................................205.9.7. Ciclos.....................................................................................................................20

5.10. Propiedades................................................................................................................215.11. Funciones predefinidas..............................................................................................215.12. Funciones definidas por el usuario............................................................................215.13. Uso del texto..............................................................................................................22

Cronograma

Semana 1 Clase 1 Presentación del cursoClase 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.

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.

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

Page 54: Guía de Macromedia Flash

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 13Clase 14

Semana 8 Clase 15Clase 16

Semana 9 Clase 17Clase 18

Semana 10 Clase 19Clase 20

Semana 11 Clase 21Clase 22

Semana 12 Clase 23Clase 24

Semana 13 Clase 25Clase 26

Semana 14 Clase 27Clase 28

Semana 15 Clase 29Clase 30

Semana 16 Clase 31Clase 32

Discusión de las bases de programación orientada a eventos. Resultado de monografía..

Introducción o Bienvenida al cursoo Explicación de la Metodología a seguir.

Comenzando con Flash o Comprendiendo lo que Flash puede hacero Diferencias entre Bitmaps y Vectoreso El nuevo interface de Flasho Cómo se trabaja con Flasho Entendiendo los distintos tipos de archivoso Crear y Guardar archivos de Flasho Personalizando tu lugar de trabajoo Personalizando tus teclas de trabajoo Ajustando las propiedades del documento

Dibujando en Flash o Creando y trabajando con formas

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

Page 55: Guía de Macromedia Flash

o Cómo seleccionar y modificar formaso Uso de rectángulos y herramientaso La herramienta “PolyStar”o Dibujando líneaso Técnicas de rellenadoo Uso de la herramienta Lápizo Uso de la herramienta de libre transformacióno Creación de gradienteso Modificación de gradienteso Aplicación de trasparencias a las formaso Uso de la herramienta Vistao Herrmienta Coloro Herramienta Borradoro El panel de coloreso Alineación del Panel

Trabajando con Texto o Comprendiendo los tipos de textoo Creación de texto estáticoo Modificando las propiedades del textoo Uso de campos de texto dinámicos

Trabajando con Simbolos o Explicación de los símbolos y las instanciaso Creación de los símbolos en Flasho Edición de Símboloso Editando las instancias de los símboloso Cómo organizar nuestra librería.

Uso del TimeLine (Línea de tiempo) o Comprendiendo el TimeLineo Trabajando con capaso Organizaciónd de capaso Creando Máscaraso Entendiendo los diferentes tipos de frameso Trabajando con frames y keyframeso Creación de una animación frame a frameo Uso de la “capa cebolla”o Edición de múltiples frameso Uso del TimeLime Avanzadoo Uso de la herramienta Art Deco

Creación de Morphing o Cómo hacer un morphing vectorialo Creación de un morphing paso a pasoo Trucos para creación de formaso Modificando múltiples elementos de una vezo Técnicas Avanzadaso Perfeccionando el Morphing

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

Page 56: Guía de Macromedia Flash

Creación de Morphing en Movimiento o Comprendiendo los Morphing en movimientoo Explicando la técnica paso a pasoo Modificación del PATHo Uso del editor de Movimientoo Uso de las propiedades de animacióno Anidando Animaciones con los Movie Clipso 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 3Do Uso de la herramienta de rotación 3Do Animación de elementos en 3Do Ordenación de MAIL con Loops

Filtros y modos de Blend o Usando Filtros en Flasho Aplicando Filtroso Animación de Filtroso Comprendiendo el modo BLENDo Uso de los modos BLEND

Uso de gráficos Bitmap o Dónde econtrar Imágeneso Importanto Bitmapso Compresión de Bitmapso La herramienta Lazoo Vectorización de un Bitmapo Importación de una secuencia de Bitmapso Técnicas de Animación con Bitmaps

Usando sonido en Flash o Dónde Encontrar sonidoso Importanto sonidoso Modificando las propiedades del sonidoo Comprendiendo los diferentes tipos de sonidoo Trabajando con efectos de sonido

Uso del vídeo o Uso de Adobe Media Encodero El componente FLVplaybacko Creación de vídeos en Flash

Introducción a ActionScript 3.0 o Qué es ActionScripto Trabajando con MovieClipso Modificando MovieClips con ASo Creación y programación de Botones

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

Page 57: Guía de Macromedia Flash

o Añadiendo Interactividado Uso de ActionScript para controlar la TimeLineo Navegando con ActionScript

Integración o Entendiendo los archivos XFLo Creación de XFL y SWF en Indesigno Generando XFL desde After effectso Integración SoundBootho Integración con Ilustratoro Integración de Flash con Dreamweaver

Publicando y Exportando Contenidos en Flash o Comprendiendo la publicación en Flash.o Publicando Flash en HTMLo Publicando a AIRo Exportación de imágeneso Exportación de películas

Conclusión o Despedida

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

Introduccióno Bienvenidao Metodología del curso

Introducción a AS 3.0 o Comprendiendo Actionscripto Uso inteligente de TRACEo Trabajando con comentarios

Trabajando con variables o Comprendiendo las variableso Comprendiendo la sintaxis de las variableso Asignando valores a las variableso Recogiendo valores de las variableso Trabajando con diferentes tipos de datos

Usando funciones o Comprendiendo las funcioneso Usando las funcioneso Entendiendo la sintaxiso Los parámetros de las funcioneso Devolviendo valoro Uso de varibales locales

Trabajando con Objetos o Explicación de la sintaxis del puntoo Controlando las propiedadeso Creación de objetos dinámicamente

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

Page 58: Guía de Macromedia Flash

o Controlando movie clips anidados Uso de Eventos

o Entendiendo los eventoso Programando los clics de ratóno Otros eventos con el ratóno Eventos del tecladoo Quitando los eventos

Creación y uso de condicionales o Uso del condicional en AS 3.0o Trabajando el la sentencia IFo Entendiendo los operadores de condicióno Escribiendo Sentencias IFo Escribiendo sentencias ELSE IFo Escribiendo sentencias SWITCH-CASEo Detectando colisiones

Uso de matemáticas para realizar tareas o Comprendiendo los operadores matemáticoso Entendiendo los tipos de datoso Alineando objetos en el escenarioo Uso aleatorio de numeros entre el 0 y 1o Uso de un rango de númeroso Creación de la función RANDOM-NUMBERo Creación de una calculadora en Flash

Creación y Uso de Arrays o Creando nuestro primer ARRAYo Indexación de ARRAYSo Métodos alternativos para creación de ARRAYSo Buscando Índiceso Creación de un juego con ARRAYS

Creación y uso de Loops o Explicación “¿Qué son los Loops?”o Creación de Loopso Uso de Loopso Ordenación de MAIL con Loopso Uso de WHILE en Loops

Usando Clases o Explicación “¿Qué es una clase?”o Tipos de Claseso Comprendiendo los “Métodos”o Uso de propiedadeso Múltiples Claseso Creando un grupo

Tratamiento de texto o Carga de texto externoo Adición de texto

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

Page 59: Guía de Macromedia Flash

o Lectura de HTMLo Links con CSS

Carga de Medios o Carga de Bitmapso Carga de archivos SWFo Creación de un PRELOADERo Carga del sonidoo Cómo detener el sonidoo Controlando el volumeno Uso del vídeoo Carga del vídeoo Controlando el playback del vídeo

Creación de una calculadora o Ejemplo de la prácticao Configuración de variableso Añadir eventoso Controlando las entradas numérciaso Configurando los botoneso Buscando la operación actualo Captura de datoso Ejecución de cálculoso Creando una clase

Solucionando problemas o Identificando problemaso Cómo solucionar Erroreso 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

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

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