Особенности применения языка сценариев ActionScript
Некоторые особенности применения языка сценариев ActionScript
Идентификация экземпляров. Итак, приступим к рассмотрению различных особенностей применения сценариев ActionScript. Одновременно будем обращать внимание на элементы языка, не описанные ранее.
Имена экземпляров флэш-символов в ролике. Начнем с небольшого примера. Он покажет, как управлять экземплярами флэш-символов из основного ролика или из любого встроенного объекта. Описание ролика. Предположим, имеется ролик, в котором объекты движутся по экрану навстречу друг другу. Поскольку рисунок в книге не может воспроизвести анимацию, опишем этот ролик немного подробнее. Графический объект Wheel-static содержит изображение колеса. Этот объект помещен в мувик Wheel. В позиции 35 мувика Wheel создан ключевой кадр с тем же изображением и кодом gotoAndPlay(1). В первом кадре создана анимация движения и задан режим поворота по часовой стрелке (CW) 1 раз. Второй мувик, Car-static, содержит изображение силуэта машины и два мувика Wheel в качестве колес. Анимацию движения машины обеспечивает мувик Car. Он содержит мувик Car-static. В позиции 60 имеется еще один ключевой кадр, в котором мувик Car-static сдвинут далеко вправо. Между этими кадрами создана анимация движения. В основной ролик помещены шесть экземпляров мувика Car. Три из них сдвинуты за границу рабочей области влево, а три - вправо. Те, что справа, развернуты в горизонтальной плоскости командой Flip Horizontal (Отразить по горизонтали).
Теперь мы хотим нажатием на разные клавиши останавливать движение некоторых машинок. Для чего это может потребоваться - сейчас неважно, пофантазируйте сами. Например, пусть клавиши 1, 2 и 3 останавливают, соответственно, верхнюю, среднюю и нижнюю машинки из движущихся слева направо. Для этого экземплярам мувика Car надо дать имена. Вообще говоря, тем экземплярам мувиков, которым имена не даны, программа присваивает их самостоятельно. В этом можно убедиться, нажав во время просмотра ролика клавиши CTRL+L. Это сочетание открывает список объектов. Вот как он выглядит для только что описанного ролика. Как видите, каждому экземпляру каждого мувика дано имя, состоящее из слова instance (экземпляр) и номера экземпляра. Однако согласитесь, что разобраться в том, какое имя какому мувику соответствует, нелегко. К тому же, приведенный выше листинг соответствует очень простому ролику, а в более сложном ролике дело может обстоять еще хуже. Поэтому лучше, если имена экземплярам даст автор ролика, причем имена осмысленные. В данном случае вполне подойдут имена саr1, car2 и car3. Напишем их в соответствующих полях вспомогательной панели Instance (Экземпляр). Теперь можно добавить в единственный пока кадр основного ролика такой код. Он проверяет, не нажата ли одна из клавиш 1, 2 или 3, и, если это так, останавливает соответствующий мувик. Осталось только добавить в основной ролик обычный кадр в позицию 2, чтобы обеспечить цикличность исполнения кода в первом кадре.
Для проверки знаний попробуйте самостоятельно решить задачку: как останавливать вместе с машинкой и ее колеса, которые (если вы сделали все так, как описано) продолжают крутиться после остановки машины? Доступ к переменным во флэш-символах. Отвлечемся на некоторое время от конкретных примеров и вернемся к теории. Мы видели, что экземпляры флэш-символов могут размещаться друг в друге. Далее, каждый мувик может иметь свои переменные. Причем, если основной ролик содержит переменную а, это совсем не значит, что какой=либо мувик не может содержать переменную с таким же именем. Для них в памяти выделяются различные области, и, следовательно, это совершенно разные переменные.
Теперь представим себе, что внутри нашего мувика с переменными имеется экземпляр другого, «маленького» мувика с именем small. Таким образом, у нас появились независимые объекты. Теперь внутри этого последнего объекта потребовалось создать переменную newvar. Как должен выглядеть код для обращения к ней? Во-первых, независимо от размещения кода, к этой переменной можно обратиться по абсолютному пути. Из основного ролика можно использовать обращение, из мувика - обращение small. newvar, а из мувика small, pacположенного внутри yourmovie - просто newvar. Кроме того, из мувика mymovie можно обратиться к этой переменной так просто. Продолжить цепочку примеров можете самостоятельно. Таким образом, к любому объекту и любой переменной можно обратиться по имени через абсолютный или относительный путь, Это позволяет гибко управлять поведением экземпляров мувиков из любого «уголка» ролика.
Анимация, приведенная в качестве примера в предыдущем разделе, относительно сложна в управлении. Можно намного упростить задачу, сделав эту анимацию программной. В этом случае мы не создаем множество кадров с различным расположением объектов, а меняем расположение объектов в одном кадре с помощью сценария ActionScript.
Для осуществления программной анимации необходимо читать и изменять значения свойств экземпляров флэш-символов, расположенных в ролике. Эти свойства задают расположение экземпляров, их размер, цвет и так далее. Давайте вначале посмотрим, какие свойства экземпляров доступны сценарию ActionScript. Имена всех свойств, чтобы их было сразу видно, начинаются с символа (подчеркивание). Текущие координаты указателя мыши записываются в свойства. Эти два свойства сильно облегчают жизнь, если нужно отслеживать координаты указателя мыши. В предыдущих версиях языка ActionScript для этого приходилось «прикреплять» к указателю мыши невидимый мувик с помощью оператора startDrag, о котором речь пойдет ниже. Свойства содержат соответственно имя экземпляра мувика и полный путь к нему. Значение свойства можно изменить, а вот свойство изменению не поддается, что вполне логично. Номер текущего кадра можно узнать из свойства. Его значение также невозможно изменить из сценария. Прозрачность экземпляра мувика можно установить с помощью свойства alpha. Не забудьте, что с помощью методов объекта Color setTransform и setRGB - также можно устанавливать как прозрачность экземпляра флэш символа, так и его цвет. Общее количество кадров мувика (или всего основного ролика) можно узнать из свойства totalframes, а количество кадров, уже загруженных на данный момент - из свойства framesloaded. Это значение особенно актуально при загрузке ролика через Интернет. К этим двум свойствам мы еще вернемся, когда речь пойдет о создании предзагрузчиков. Значения свойств totalframes и framesloaded изменить нельзя. Свойство visible управляет видимостью экземпляра. Если оно имеет значение false, мувик не отображается на экране. Свойство uri содержит сетевой адрес, с которого данный ролик был загружен. Значение этого свойства также неизменяемо.
Качеством воспроизведения видеоряда управляет свойство quality. Оно может принимать четыре значения: Low (Низкое), Medium (Среднее), High (Высокое) и Best (Наилучшее). В режиме Best (наилучшее) кривые сглаживаются по наилучшему алгоритму (с сеткой 4×4), а также сглаживается вся растровая графика. То же самое происходит в режиме High (Высокое), однако здесь растровая графика сглаживается только в статических объектах. В режиме Medium (Среднее) сглаживание кривых происходит с использованием упрощенного алгоритма (сетка 2×2), а растровая графика вообще не сглаживается. В режиме Low (Низкое) не происходит даже сглаживания кривых.
Как видите, повышение качества обеспечивается сглаживанием кривых линий. Чем больше кривых сглаживается, тем больше ресурсов компьютера требуется для прорисовки каждого отдельного кадра. При качестве Best (Наилучшее) многие компьютеры, не успевая прорисовать все кадры сколько-нибудь сложного ролика, начнут просто пропускать кадры. От таких пропусков качество видеоряда ролика страдает заметно сильнее, чем от отсутствия сглаживания некоторых кривых.
Поэтому свойство quality следует устанавливать в зависимости от сложности ролика. Если ролик содержит много объектов и много анимации, если он имеет повышенную частоту кадров или содержит много текстовой информации, лучше предусмотреть переключение качества воспроизведения в режим Medium (Среднее) или даже Low (Низкое). Правда, текст в режиме Medium (Среднее) и, тем более, Low (Низкое) воспринимается крайне плохо, а при небольшом размере шрифта может стать и вообще нечитаемым. Помимо свойства quality, для определения и установки качества воспроизведения иногда используют также устаревшее свойство highquality. Оно может принимать значения 0, 1 или 2, причем значение 2 соответствует наилучшему качеству.
Для настройки воспроизведения звука можно регулировать размер звукового буфера с помощью свойства soundbuftime. При потоковом воспроизведении звука некоторая часть записи предварительно загружается в буфер (чтобы при небольших сбоях в канале связи звук не прерывался). По умолчанию размер звукового буфера равен 5 секундам записи. Значение свойства soundbuftime должно быть целым числом. Если экземпляр мувика повернут в рабочей области относительно своего оригинального расположения, угол его поворота в градусах хранится в свойстве rotation.
Интересно также свойство droptarget. Оно недоступно для изменения и всегда содержит имя экземпляра объекта, над которым находится текущий объект при перетаскивании. Чтобы это свойство имело смысл, к указанному объекту вначале должен быть применен оператор (или метод) startDrag. Об этом мы поговорим позже. Наконец, свойство focusrect применяется весьма редко. Если его значение равно true, то при перемещении фокуса ввода между полями пользовательского ввода с помощью клавиши ТАВ активное поле выделяется желтым прямоугольником. По умолчанию значение этого свойства равно false.
Names of instances of flash characters in the video. Let's start with a small example. It will show how to manage instances of flash characters from the main video or from any embedded object. Description of the video. Suppose there is a video in which objects move across the screen towards each other. Since the drawing in the book cannot reproduce the animation, we will describe this video in a little more detail. The Wheel-static graphic object contains an image of a wheel. This object is placed in the Wheel movie. A keyframe with the same image and gotoAndPlay(1) code has been created at position 35 of the Wheel movie. In the first frame, a motion animation is created and the clockwise rotation mode (CW) is set 1 time. The second movie, Car-static, contains an image of the silhouette of the car and two Wheel movies as wheels. The animation of the car movement is provided by the Car movie. It contains a Car-static movie. At position 60 there is another key frame in which the Car-static movie is shifted far to the right. A motion animation is created between these frames. Six copies of the Car movie are placed in the main video. Three of them are shifted beyond the border of the workspace to the left, and three to the right. The ones on the right are deployed in the horizontal plane with the Flip Horizontal command.
Now we want to stop the movement of some cars by pressing different keys. What it may be required for - it doesn't matter now, dream up yourself. For example, let the keys 1, 2 and 3 stop, respectively, the upper, middle and lower cars from moving from left to right. To do this, the instances of the Car movie must be given names. Generally speaking, the program assigns them independently to those instances of movies that are not given names. You can verify this by pressing CTRL+L while watching the video. This combination opens a list of objects. Here's what it looks like for the video just described. As you can see, each instance of each movie is given a name consisting of the word instance and the instance number. However, you must agree that it is not easy to figure out which name corresponds to which movie. In addition, the above listing corresponds to a very simple video, and in a more complex video, the situation may be even worse. Therefore, it is better if the author of the video gives the names to the instances, and the names are meaningful. In this case, the names sag1, car2 and car3 are quite suitable. Let's write them in the corresponding fields of the Instance auxiliary panel. Now you can add this code to the only frame of the main video so far. It checks if one of the keys 1, 2 or 3 is pressed, and if so, stops the corresponding movie. All that remains is to add a regular frame to the main video at position 2 to ensure the cyclical execution of the code in the first frame.
To test your knowledge, try to solve the problem yourself: how to stop the wheels together with the machine, which (if you have done everything as described) continue to spin after the machine stops? Access to variables in flash symbols. Let's digress from concrete examples for a while and return to theory. We have seen that instances of flash symbols can be placed in each other. Further, each movie can have its own variables. Moreover, if the main video contains the variable a, this does not mean at all that any movie cannot contain a variable with the same name. For them, different areas are allocated in memory, and, therefore, these are completely different variables.
Now imagine that inside our movie with variables there is an instance of another, "small" movie named small. Thus, we have independent objects. Now it was necessary to create a newvar variable inside this last object. What should the code look like to access it? Firstly, regardless of the placement of the code, this variable can be accessed by an absolute path. You can use an appeal from the main video, a small. newvar appeal from the movie, and just newvar from the small movie located inside yourmovie. In addition, from the mymovie movie, you can access this variable so simply. You can continue the chain of examples yourself. Thus, any object and any variable can be accessed by name via an absolute or relative path, This allows you to flexibly control the behavior of movie instances from any "corner" of the video.
The animation given as an example in the previous section is relatively difficult to manage. You can simplify the task a lot by making this animation programmatic. In this case, we do not create multiple frames with different locations of objects, but change the location of objects in one frame using an ActionScript script.
To implement the program animation, it is necessary to read and change the values of the properties of instances of flash symbols located in the video. These properties specify the location of instances, their size, color, and so on. Let's first see what instance properties are available to the ActionScript script. The names of all properties, so that they can be immediately seen, begin with the symbol (underscore). The current coordinates of the mouse pointer are recorded in the properties. These two properties make life much easier if you need to track the coordinates of the mouse pointer. In previous versions of the ActionScript language, it was necessary to "attach" an invisible movie to the mouse pointer using the startDrag operator, which will be discussed below. The properties contain, respectively, the name of the movie instance and the full path to it. The value of the property can be changed, but the property cannot be changed, which is quite logical. The number of the current frame can be found from the property. Its value also cannot be changed from the script. The transparency of the movie instance can be set using the alpha property. Do not forget that using the methods of the Color setTransform and setRGB object, you can also set both the transparency of the flash symbol instance and its color. The total number of frames of the movie (or the entire main video) can be found from the totalframes property, and the number of frames already loaded at the moment can be found from the framesloaded property. This value is especially relevant when downloading a video over the Internet. We will return to these two properties later when we talk about creating preloaders. The values of the totalframes and framesloaded properties cannot be changed. The visible property controls the visibility of the instance. If it is set to false, the movie is not displayed on the screen. The uri property contains the network address from which this video was uploaded. The value of this property is also immutable.
The quality of video sequence playback is controlled by the quality property. It can take four values: Low (Low), Medium (Medium), High (High) and Best (Best). In the Best mode, the curves are smoothed according to the best algorithm (with a 4×4 grid), and the entire raster graphics are smoothed. The same thing happens in High mode, but here the raster graphics are smoothed only in static objects. In Medium mode, curves are smoothed using a simplified algorithm (2×2 grid), and raster graphics are not smoothed at all. In the Low mode, there is not even smoothing of curves.
As you can see, the quality improvement is provided by smoothing curved lines. The more curves are smoothed, the more computer resources are required to draw each individual frame. With the Best quality, many computers, without having time to draw all the frames of any complex video, will simply skip frames. From such omissions, the quality of the video sequence of the video suffers noticeably more than from the lack of smoothing of some curves.
Therefore, the quality property should be set depending on the complexity of the video. If the video contains a lot of objects and a lot of animation, if it has an increased frame rate or contains a lot of text information, it is better to provide for switching the playback quality to Medium (Medium) or even Low (Low) mode. However, the text in Medium (Medium) and, moreover, Low (Low) mode is perceived extremely poorly, and with a small font size it can become unreadable at all. In addition to the quality property, the outdated high quality property is also sometimes used to determine and set the playback quality. It can take the values 0, 1 or 2, and the value 2 corresponds to the best quality.
To adjust the sound playback, you can adjust the size of the sound buffer using the soundbuftime property. When streaming audio, some part of the recording is preloaded into the buffer (so that in case of small failures in the communication channel, the sound is not interrupted). By default, the size of the audio buffer is 5 seconds of recording. The value of the soundbuftime property must be an integer. If the movie instance is rotated in the workspace relative to its original location, the angle of its rotation in degrees is stored in the rotation property.
The droptarget property is also interesting. It is not editable and always contains the name of the instance of the object over which the current object is located when dragging. In order for this property to make sense, the startDrag operator (or method) must first be applied to the specified object. We'll talk about this later. Finally, the focusrect property is rarely used. If its value is true, then when moving the input focus between user input fields using the TAV key, the active field is highlighted with a yellow rectangle. By default, the value of this property is false.