ActionScript 3 interactive objects tutorial: Difference between revisions
(Daniel K. Schneider moved page ActionScript 3 interactive objects tutorial to ActionScript 3 interactive objects tutorial (CS3)) |
m (Text replacement - "<pageby nominor="false" comments="false"/>" to "<!-- <pageby nominor="false" comments="false"/> -->") |
||
(11 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
{{Flash tutorial|intermediate|CS6 (CS3 to CS5)|}} | |||
{{Incomplete}} | |||
<!-- <pageby nominor="false" comments="false"/> --> | |||
== Overview == | |||
<div class="tut_goals"> | |||
; Learning goals | |||
The purpose of this tutorial is go a little bit beyond dealing with mouse clicks, buttons and button components as seen in previous tutorials, i.e. you will learn how to change properties of objects (such as position, size and visibility) and how to play embedded movie clips: | |||
* Learn about how to use mouse and key-press events. | |||
* Learn about some object properties you can easily change with a little ActionScript code | |||
* Learn some ActionScript control statements (if-then-else clause and assignments) | |||
* Learn how to play embedded Flash movie clips. | |||
* Learn how to use embedded Flash movie clips for multiple animations | |||
; Prerequisites | |||
:[[Flash CS6 desktop tutorial]] | |||
:[[Flash drawing tutorial]] | |||
:[[Flash button tutorial]] | |||
:[[Flash component button tutorial]] | |||
:[[Flash embedded movie clip tutorial]] | |||
; Other recommended prior tutorials (not necessary, but can help) | |||
:[[Flash video component tutorial]] | |||
:[[Flash sound tutorial]] | |||
:[[ActionScript 3 event handling tutorial]] | |||
; Moving on | |||
: [[Flash drag and drop tutorial]] | |||
: [[Flash games tutorial]] | |||
: [[Flash ActionScript 3 overview]] | |||
: The [[Flash tutorials]] index has a list of other tutorials. | |||
; Alternative versions | |||
: [[ActionScript 3 interactive objects tutorial (CS3)]] (old version) | |||
; Level and target population | |||
* It aims at Flash '''designers''', '''not''' beginning ActionScript 3 programmers, although programmers can read this to get a feeling for object properties before digging into a real documentation like [http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/ Adobe's Flash 9 reference manual]. Also, some of the code should be rewritten a bit. I skipped type declarations on purpose and should even rip off more. These don't make sense for a few lines of code written by/for non-programmers. The goal is to keep code as simple as possible. I should at some point decide whether I should remove all type declarations from the examples or consistently leave the ones that might be useful in order to receive compiler warnings. | |||
; Quality | |||
: This text should technical people get going and may not be good enough for self-learning beginners. It can be used as handout in a "hands-on" class. That is what [[User:Daniel K. Schneider|Daniel K. Schneider]] made it for... | |||
</div> | |||
; Learning materials | |||
Grab the various *.fla files from here: | |||
: http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/ | |||
== Manipulating objects == | |||
The principle of (simple) object manipulation is fairly simple: '''change properties of a display object'''. The tricky thing is to know ''what'' you can change | |||
on a given kind of object. Some changes are easy to make, others are really hard. | |||
Typically, most objects are non-editable (its component objects maybe are). It's easy to change size and position of a display object, i.e. operations you could do on grouped objects and symbol instances with the transform tool or the parameters panel. | |||
Below, we show a few little examples that demonstrate how to manipulate objects | |||
with mouse events (see the [[ActionScript 3 event handling tutorial]] for more details). All the objects on the stage (e.g. black_cat) are instances of movie clip symbols. These are a kind of interactive object and react to mouse and keyboard events. The kind of tricks will we show act on '''named instances''' movie clips. | |||
[[image:flash-cs6-named-symbol-instance.png|thumb|440px|none|Symbol instances you want to manipulate must be named]] | |||
You could imagine dozens of other simple examples, but it's not so easy to understand the technical ActionScript documentation which is made for programmers and not designers. If you feel more adventurous, you may have a look at the class hierarchy described in the [[Flash ActionScript 3 overview]] and in particular the [[Flash_ActionScript_3_overview#The_DisplayObject|Display Object]] and its children. Follow up a link to the Flash documentation and see if you can find other properties that are easy to manipulate... | |||
=== Simple repositioning example === | |||
To understand what is going on below, you may want to look at: | |||
: [http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/actionscript3-simple-object-manipulation.html actionscript3-simple-object-manipulation.html] | |||
And also load the *.fla file | |||
: [http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/actionscript3-simple-object-manipulation.fla actionscript3-simple-object-manipulation.fla] | |||
In order to reposition an object, change its ''x'' and ''y'' properties. | |||
In the following example, when you click on the interactive object (a symbol instance that is called "black_cat") it will move itself to position x= 200 and y=200. | |||
Note: Position is defined by the center of the display object (i.e. the little "+" sign who's value depends on how you made it). | |||
<source lang="actionscript"> | |||
black_cat.addEventListener(MouseEvent.CLICK, moveCat); | |||
function moveCat(event:MouseEvent):void { | |||
black_cat.x = 200; | |||
black_cat.y = 200; | |||
} | |||
</source> | |||
A statement like | |||
<source lang="actionscript"> | |||
cat.x = 100; | |||
</source> | |||
is called an '''assignment''' and means: The '''x''' ''property'' of the cat object will become "100". | |||
If you want to move the cat forth and back you'd rather use this code: | |||
<source lang="actionscript"> | |||
black_cat.addEventListener(MouseEvent.CLICK, moveCat); | |||
// cat can be in original position or not (true,false) | |||
var black_cat_ori_pos = true; | |||
function moveCat(event:MouseEvent):void { | |||
if (black_cat_ori_pos == true) | |||
{ | |||
black_cat.x += 200; | |||
black_cat.y += 200; | |||
black_cat_ori_pos = false; | |||
} | |||
else | |||
{ | |||
black_cat.x -= 200; | |||
black_cat.y -= 200; | |||
black_cat_ori_pos = true; | |||
} | |||
} | |||
</source> | |||
In this function we use a so-called '''if-then-else statement'''. The line | |||
<source lang="actionscript"> | |||
if (black_cat_ori_pos == true) | |||
</source> | |||
checks if the variable black_cat_ori_pos has the value of true. If this is true we then execute the clause <code>{ black_cat.x += ... ; black_cat.y ..... }</code> that follows. If it is not true we execute the other {...} clause after the else. | |||
Also note the difference between an assignment ("'''='''") and an '''equality test''' ("'''=='''"). The latter will test if two values are the same. Note to beginners: | |||
never use just the "=" inside the conditional of an "if". Use "==". | |||
Let's describe this at a more conceptual level: ''black_cat_ori_pos'' can be called a "flag" variable since it will register whether the cat is in a new position or the original old position. If it's in the new one, we will move it back, and the other way round. So | |||
<source lang="actionscript"> | |||
black_cat_ori_pas == true | |||
</source> | |||
tests if the cat sits in its original position. | |||
X and Y positions are defined with respect to the upper left corner. E.g. if x is 100 and y is 100, the registered center point of the object is 100 pixels to the right and 100 pixels down. The instruction: | |||
<source lang="actionscript"> | |||
x += 100; | |||
x -= 100; | |||
</source> | |||
means "add 100 to x" or "subtract 100 from x". So it's a shortcut for ''x = x + 100;'', i.e. "new value of x ''becomes'' old value of x plus 100". | |||
Code above isn't of the kind that a real programmer would use. Therefore, if you are familiar with programming, rather go for something like the following. ''Beginners, please ignore''. The following function would work with any object (not just a given cat). It will retrieve the symbol instance from the event object. Original position of the object is remembered in the object itself, using a new property we create (ori_x and ori_y). | |||
<source lang="actionscript"> | |||
function moveIt(event:MouseEvent):void | |||
{ | |||
var obj = event.target; | |||
// initialize original values if necessary (on first pass) | |||
// test if properties ori_ exist, if not create them | |||
if (! ("ori_x" in obj)) | |||
{ | |||
obj.ori_x = obj.x; | |||
obj.ori_y = obj.y; | |||
obj.buttonMode = true; // for better UX, this could be done before | |||
} | |||
// Is object in original position ? If so move close to friend | |||
if (obj.ori_x == obj.x) | |||
{ | |||
obj.x =+ 200; | |||
obj.y =+ 200; | |||
} | |||
else | |||
{ | |||
obj.x = obj.ori_x; | |||
obj.y = obj.ori_y; | |||
} | |||
} | |||
</source> | |||
=== Change size === | |||
Changing size, means to change ''width'' and ''height'' properties. | |||
In the following example, when you click on the interactive object (a symbol instance that is called "blue_cat") it will double its size when you hold down | |||
the mouse button and go back to normal when you release it. Note: | |||
If you hold down the button and then move the mouse out (still holding down), and only then release the button, the mouse will stay big since it never will catch the mouse up event. | |||
<source lang="actionscript"> | |||
blue_cat.addEventListener(MouseEvent.MOUSE_DOWN, resizeCat); | |||
function resizeCat(event:MouseEvent):void { | |||
blue_cat.width = blue_cat.width * 2; | |||
blue_cat.height = blue_cat.height * 2; | |||
} | |||
blue_cat.addEventListener(MouseEvent.MOUSE_UP, resizeCat2); | |||
function resizeCat2(event:MouseEvent):void { | |||
blue_cat.width = blue_cat.width / 2; | |||
blue_cat.height = blue_cat.height / 2; | |||
} | |||
</source> | |||
This code may not exactly do what you want. As we said, if the user holds down the mouse button '''and''' moves it out, the MOUSE_UP event will never happen, i.e. the cat will grow permanently. A better solution can be found in the example code that we included at the end of this section. | |||
=== Visibility === | |||
In the following example, we will make a white cat invisible when you click on it. | |||
Technical note: It is still there, but the user can't click on it. | |||
<source lang="actionscript"> | |||
white_cat.addEventListener(MouseEvent.CLICK, hideCat); | |||
function hideCat(event:MouseEvent):void { | |||
white_cat.visible = false; | |||
} | |||
</source> | |||
Once the cat is hidden, the user never will be able to bring it back. Therefore, in the next example we decided to implement a switch between a cat and a dog: | |||
<source lang="actionscript"> | |||
// can't see the dog for starters | |||
brown_dog.visible=false; | |||
brown_dog.addEventListener(MouseEvent.CLICK, hideShow); | |||
white_cat.addEventListener(MouseEvent.CLICK, hideShow); | |||
function hideShow(event:MouseEvent):void { | |||
// instead of using white_cat.visible = false; we just switch it to the opposite | |||
white_cat.visible = !white_cat.visible; | |||
brown_dog.visible =!brown_dog.visible; | |||
} | |||
</source> | |||
The "<code>!</code>" used for <code>white_cat.visible</code>in the hideShow function means that the "visible" property will be set to its opposite. E.g. if the value is ''true'' it will become ''false'', and the other way round. Same technique for the dog (which is invisible for starters). | |||
=== Let the user drag example === | |||
The next example shows how to let a user drag the red cat object with the mouse (button pressed down) and then drop the cat when the user releases the mouse button. | |||
<source lang="actionscript"> | |||
red_cat.addEventListener(MouseEvent.MOUSE_DOWN, startDragging); | |||
red_cat.addEventListener(MouseEvent.MOUSE_UP, stopDragging); | |||
function startDragging(event:MouseEvent):void | |||
{ | |||
red_cat.startDrag(); | |||
} | |||
function stopDragging(event:MouseEvent):void | |||
{ | |||
red_cat.stopDrag(); | |||
} | |||
</source> | |||
For a tutorial on dragging and dropping, see the [[Flash drag and drop tutorial]] that demonstrates how to implement a simple children's educational game. You will learn for instance how to test if a dropped object will sit on top of another one. | |||
=== Transformations === | |||
So-called "transforms" of a non-editable display object are more tricky. We just will demonstrate how to change the tint with a color transform. You also could skew | |||
an object with a similar strategy. However, this kind of code is really a bit too difficult to understand without some prior introduction to object-oriented programming. | |||
'''Color''': The ColorTransform class lets you adjust the color values in a display object. The color adjustment or color transformation can be applied to all four channels: red, green, blue, and alpha transparency. | |||
Here are the formula according to the [http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/geom/ColorTransform.html manual], retrieved 20:58, 8 October 2007 (MEST): | |||
* New red value = (old red value * redMultiplier) + redOffset | |||
* New green value = (old green value * greenMultiplier) + greenOffset | |||
* New blue value = (old blue value * blueMultiplier) + blueOffset | |||
* New alpha value = (old alpha value * alphaMultiplier) + alphaOffset | |||
The tricky thing is that you have to program transformations with a temporary ColorTransform object and then copy this object to the display object's colorTransform property if I understood the manual right. See the code toward the end of the full example code below. | |||
=== Cat example file === | |||
[[image:flash-cs3-mouse-events-property-changes.png|thumb|400px|none|Demonstration of some mouse events and implementation of property changes]] | |||
The (all-in-one) file with the examples we discussed above is here: | |||
: [http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/actionscript3-simple-object-manipulation.html actionscript3-simple-object-manipulation.html] | |||
: [http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/actionscript3-simple-object-manipulation.fla actionscript3-simple-object-manipulation.fla] | |||
Directory with files actionscript3-simple-object-manipulation.*: | |||
:http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/ | |||
Here is the complete ActionScript code: | |||
<source lang="actionscript"> | |||
/* ----- Change cursor form | |||
add a hand to cursor to each cat | |||
This way a user understands that he/she can do something with the object. | |||
*/ | |||
black_cat.buttonMode = true; | |||
blue_cat.buttonMode = true; | |||
red_cat.buttonMode = true; | |||
brown_dog.buttonMode = true; | |||
white_cat.buttonMode = true; | |||
empty_cat.buttonMode = true; | |||
grey_mouse.buttonMode = true; | |||
/* ---- moving ---- */ | |||
black_cat.addEventListener(MouseEvent.CLICK, moveCat); | |||
// cat can be in original position or not (true,false) | |||
var black_cat_ori_pos = true; | |||
function moveCat(event:MouseEvent):void { | |||
if (black_cat_ori_pos == true) | |||
{ | |||
black_cat.x += 200; | |||
black_cat.y += 200; | |||
black_cat_ori_pos = false; | |||
} | |||
else | |||
{ | |||
black_cat.x -= 200; | |||
black_cat.y -= 200; | |||
black_cat_ori_pos = true; | |||
} | |||
} | |||
/* ---- resizing ---- */ | |||
blue_cat.addEventListener(MouseEvent.MOUSE_DOWN, resizeCat); | |||
var cat_size = 1; | |||
function resizeCat(event:MouseEvent):void { | |||
blue_cat.width = blue_cat.width * 2; | |||
blue_cat.height = blue_cat.height * 2; | |||
cat_size = 2; | |||
} | |||
// We have to test both mouse up and mouse out since user can | |||
// press mouse and move out. Cat in this case would stay big. | |||
// Also we have to test if cat is already big when user moves in. | |||
blue_cat.addEventListener(MouseEvent.MOUSE_UP, resizeCat2); | |||
blue_cat.addEventListener(MouseEvent.MOUSE_OUT, resizeCat2); | |||
function resizeCat2(event:MouseEvent):void { | |||
if (cat_size > 1) | |||
{ | |||
blue_cat.width = blue_cat.width / 2; | |||
blue_cat.height = blue_cat.height / 2; | |||
cat_size = 1; | |||
} | |||
} | |||
/* ---- dragging ---- */ | |||
red_cat.addEventListener(MouseEvent.MOUSE_DOWN, startDragging); | |||
red_cat.addEventListener(MouseEvent.MOUSE_UP, stopDragging); | |||
function startDragging(event:MouseEvent):void { | |||
red_cat.startDrag(); | |||
} | |||
function stopDragging(event:MouseEvent):void { | |||
red_cat.stopDrag(); | |||
} | |||
/* ---- Hiding ---- */ | |||
// can't see the dog for starters | |||
brown_dog.visible=false; | |||
brown_dog.addEventListener(MouseEvent.CLICK, hideShow); | |||
white_cat.addEventListener(MouseEvent.CLICK, hideShow); | |||
function hideShow(event:MouseEvent):void { | |||
// instead of white_cat.visible = false; we just switch it to the opposite | |||
white_cat.visible = !white_cat.visible; | |||
brown_dog.visible =!brown_dog.visible; | |||
} | |||
/* ---- transforms ---- | |||
This is a bit more difficult.... */ | |||
empty_cat.addEventListener(MouseEvent.CLICK, transformCatColor); | |||
// R,G,B,A multipliers and R,G,B,A offsets | |||
// We start with a light grey cat | |||
var resultColorTransform = new ColorTransform (0.1,0.1,0.1,1,120,120,120,255); | |||
empty_cat.transform.colorTransform = resultColorTransform; | |||
function transformCatColor(event:MouseEvent):void { | |||
var resultColorTransform = empty_cat.transform.colorTransform; | |||
// Create a new color transform object and change it | |||
// red color will peak at 255, blue color offset will cycle from +255 to -100 | |||
resultColorTransform.redOffset = Math.min(resultColorTransform.redOffset+10,255); | |||
resultColorTransform.redMultiplier = Math.min(resultColorTransform.redMultiplier+0.1,1); | |||
resultColorTransform.blueOffset += 10; | |||
if (resultColorTransform.blueOffset >= 255) | |||
{ | |||
resultColorTransform.blueOffset = -100; | |||
} | |||
resultColorTransform.blueMultiplier = 0.1; | |||
// Copy that to the cat | |||
empty_cat.transform.colorTransform = resultColorTransform; | |||
//trace("redOffset="+resultColorTransform.redOffset + | |||
// " blueOffset="+resultColorTransform.blueOffset); | |||
} | |||
/* ---- permanent size change ---- */ | |||
grey_mouse.addEventListener(MouseEvent.MOUSE_WHEEL, changeMouse); | |||
function changeMouse(event:MouseEvent):void { | |||
grey_mouse.width += event.delta*3; | |||
grey_mouse.height += event.delta*3; | |||
} | |||
</source> | |||
=== Simple repositioning example with better code === | |||
The example of the previous section uses some kind of "baby programmer" code, e.g. the functions only work with very specific objects and there are many global variables. Somewhat better code will include functions that could work with any object and avoid using variables. | |||
In the following example you can associate any function with any symbol. E.g. the red cat now can be both dragged and change size using the mouse wheel. Same of the mouse. The code is also separateed it in two sections. On top, we define event handlers for objects. An end-user (Flash Designer) could just add his/her own objects and decide which event handlers to use .... | |||
The (all-in-one) file with the examples we discussed above is here: | |||
: [http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/actionscript3-simple-object-manipulation2.html actionscript3-simple-object-manipulation2.html] | |||
: [http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/actionscript3-simple-object-manipulation2.fla actionscript3-simple-object-manipulation2.fla] | |||
Directory with files actionscript3-simple-object-manipulation.*: | |||
:http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/ | |||
<source lang = "Actionscript"> | |||
/* ------- List of objects and Event handlers ------------- */ | |||
// black cat - will move next to his red friend | |||
black_cat.addEventListener(MouseEvent.CLICK, moveIt); | |||
black_cat.friend = red_cat; | |||
// blue cat - will change size on mouse down ; | |||
blue_cat.addEventListener(MouseEvent.MOUSE_DOWN, resizeIt); | |||
// We have to test both mouse up and mouse out since user can; | |||
// press mouse and move out. Cat in this case would stay big. | |||
// Also we have to test if cat is already big when user moves in. | |||
blue_cat.addEventListener(MouseEvent.MOUSE_UP, downsizeIt); | |||
blue_cat.addEventListener(MouseEvent.MOUSE_OUT, downsizeIt); | |||
// red cat and mouse - can be dragged | |||
red_cat.addEventListener(MouseEvent.MOUSE_DOWN, startDragging); | |||
red_cat.addEventListener(MouseEvent.MOUSE_UP, stopDragging); | |||
grey_mouse.addEventListener(MouseEvent.MOUSE_DOWN, startDragging); | |||
grey_mouse.addEventListener(MouseEvent.MOUSE_UP, stopDragging); | |||
// dog and cat switch | |||
// can't see the dog for starters | |||
brown_dog.buttonMode = true; // change cursor form here for a change | |||
white_cat.buttonMode = true; | |||
brown_dog.visible = false; | |||
brown_dog.addEventListener(MouseEvent.CLICK, hideShow); | |||
white_cat.addEventListener(MouseEvent.CLICK, hideShow); | |||
white_cat.friend = brown_dog; | |||
brown_dog.friend = white_cat; | |||
// mouse and red cat -- size change with wheel | |||
grey_mouse.addEventListener(MouseEvent.MOUSE_WHEEL, changeSize); | |||
red_cat.addEventListener(MouseEvent.MOUSE_WHEEL, changeSize); | |||
empty_cat.addEventListener(MouseEvent.CLICK, transformCatColor); | |||
// R,G,B,A multipliers and R,G,B,A offsets - we start with a light grey cat | |||
empty_cat.transform.colorTransform = new ColorTransform(0.1,0.1,0.1,1,120,120,120,255); | |||
</source> | |||
Below is the complete code | |||
<source lang = "Actionscript"> | |||
/* This example attempts to write more portable code. | |||
Any of the functions will work with any movie symbol. | |||
No more global variables... | |||
*/ | |||
/* ------- List of objects and Event handlers ------------- */ | |||
// black cat - will move next to his red friend | |||
black_cat.addEventListener(MouseEvent.CLICK, moveIt); | |||
black_cat.friend = red_cat; | |||
// blue cat - will change size on mouse down ; | |||
blue_cat.addEventListener(MouseEvent.MOUSE_DOWN, resizeIt); | |||
// We have to test both mouse up and mouse out since user can; | |||
// press mouse and move out. Cat in this case would stay big. | |||
// Also we have to test if cat is already big when user moves in. | |||
blue_cat.addEventListener(MouseEvent.MOUSE_UP, downsizeIt); | |||
blue_cat.addEventListener(MouseEvent.MOUSE_OUT, downsizeIt); | |||
// red cat and mouse - can be dragged | |||
red_cat.addEventListener(MouseEvent.MOUSE_DOWN, startDragging); | |||
red_cat.addEventListener(MouseEvent.MOUSE_UP, stopDragging); | |||
grey_mouse.addEventListener(MouseEvent.MOUSE_DOWN, startDragging); | |||
grey_mouse.addEventListener(MouseEvent.MOUSE_UP, stopDragging); | |||
// dog and cat switch | |||
// can't see the dog for starters | |||
brown_dog.buttonMode = true; // change cursor form here for a change | |||
white_cat.buttonMode = true; | |||
brown_dog.visible = false; | |||
brown_dog.addEventListener(MouseEvent.CLICK, hideShow); | |||
white_cat.addEventListener(MouseEvent.CLICK, hideShow); | |||
white_cat.friend = brown_dog; | |||
brown_dog.friend = white_cat; | |||
// mouse and red cat -- size change with wheel | |||
grey_mouse.addEventListener(MouseEvent.MOUSE_WHEEL, changeSize); | |||
red_cat.addEventListener(MouseEvent.MOUSE_WHEEL, changeSize); | |||
empty_cat.addEventListener(MouseEvent.CLICK, transformCatColor); | |||
// R,G,B,A multipliers and R,G,B,A offsets - we start with a light grey cat | |||
empty_cat.transform.colorTransform = new ColorTransform(0.1,0.1,0.1,1,120,120,120,255); | |||
/* ---- moving ---- */ | |||
function moveIt(event:MouseEvent):void | |||
{ | |||
var obj = event.target; | |||
// initialize original values if necessary (on first pass) | |||
// test if properties ori_ exist, if not create them | |||
if (! ("ori_x" in obj)) | |||
{ | |||
obj.ori_x = obj.x; | |||
obj.ori_y = obj.y; | |||
obj.buttonMode = true; // for better UX, this could be done before | |||
} | |||
// Is object in original position ? If so move close to friend | |||
if (obj.ori_x == obj.x) | |||
{ | |||
obj.x = obj.friend.x + 50; | |||
obj.y = obj.friend.y - 10; | |||
} | |||
else | |||
{ | |||
obj.x = obj.ori_x; | |||
obj.y = obj.ori_y; | |||
} | |||
} | |||
/* ---- resizing ---- */ | |||
function resizeIt(event:MouseEvent):void | |||
{ | |||
var obj = event.target; | |||
// initialize properties if needed | |||
if (! (obj.hasOwnProperty("bigger")) ) | |||
{ | |||
obj.bigger = false; // remembers its size big or not | |||
obj.buttonMode = true; | |||
} | |||
// make the object bigger | |||
obj.width = obj.width * 2; | |||
obj.height = obj.height * 2; | |||
obj.bigger = true; | |||
} | |||
function downsizeIt(event:MouseEvent):void | |||
{ | |||
var obj = event.target; | |||
if (! (obj.hasOwnProperty("bigger")) ) | |||
{ | |||
obj.bigger = false; // remembers its size big or not | |||
obj.buttonMode = true; | |||
} | |||
// if orginal width is not the same as current, we assume that it's bigger | |||
// and then divide it by 2 | |||
if (obj.bigger == true) | |||
{ | |||
obj.width = obj.width / 2; | |||
obj.height = obj.height / 2; | |||
} | |||
} | |||
/* ---- dragging ---- */ | |||
function startDragging(event:MouseEvent):void | |||
{ | |||
var obj = event.target; | |||
obj.startDrag(); | |||
} | |||
function stopDragging(event:MouseEvent):void | |||
{ | |||
var obj = event.target; | |||
obj.stopDrag(); | |||
} | |||
/* ---- Hiding ---- */ | |||
function hideShow(event:MouseEvent):void | |||
{ | |||
var obj = event.target; | |||
// target becomes invisible | |||
obj.visible = false; | |||
// friend becomes visible | |||
obj.friend.visible = true; | |||
} | |||
/* ---- transforms ---- | |||
This is a bit more difficult.... */ | |||
function transformCatColor(event:MouseEvent):void | |||
{ | |||
var obj = event.target; | |||
var resultColorTransform = empty_cat.transform.colorTransform; | |||
// Create a new color transform object and change it | |||
// red color will peak at 255, blue color offset will cycle from +255 to -100 | |||
resultColorTransform.redOffset = Math.min(resultColorTransform.redOffset + 10,255); | |||
resultColorTransform.redMultiplier = Math.min(resultColorTransform.redMultiplier + 0.1,1); | |||
resultColorTransform.blueOffset += 10; | |||
if (resultColorTransform.blueOffset >= 255) | |||
{ | |||
resultColorTransform.blueOffset = -100; | |||
} | |||
resultColorTransform.blueMultiplier = 0.1; | |||
// Copy that to the cat | |||
obj.transform.colorTransform = resultColorTransform; | |||
//trace("redOffset="+resultColorTransform.redOffset + | |||
// " blueOffset="+resultColorTransform.blueOffset); | |||
} | |||
/* ---- permanent size change with mouse wheel ---- */ | |||
function changeSize(event:MouseEvent):void | |||
{ | |||
var obj = event.target; | |||
obj.width += event.delta * 3; | |||
obj.height += event.delta * 3; | |||
} | |||
</source> | |||
=== Remote cat control example === | |||
[[image:flash-cs3-mouse-events-property-changes2.png|thumb|right|400px|none|Demonstration II of some mouse events and implementation of property changes]] | |||
Here is another example that demonstrates the following principles: | |||
* You can modify an object's properties from an event triggered on another object (e.g. button components) | |||
* Play an embedded animation | |||
I also simplified the way functions are written, i.e. I ripped off argument type declarations and the return type. This is not necessarily a good thing, but it should demonstrate to designers that a little bit of ActionScript is not necessarily very complex .... | |||
The example can be viewed here: | |||
* [http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/actionscript3-simple-object-manipulation-buttons.html actionscript3-simple-object-manipulation-buttons.html] | |||
* Source: [http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/actionscript3-simple-object-manipulation-buttons.fla actionscript3-simple-object-manipulation-buttons.fla] | |||
* Directory: | |||
:http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/ | |||
Here is the complete code: On the stage are several buttons (named like "bigger", "smaller", etc.), a cat movie clip instance called "cat" and a dog called "brown_dog". | |||
<source lang="actionscript"> | |||
/* ---- moving ---- */ | |||
move.addEventListener(MouseEvent.CLICK, moveCat); | |||
// cat can be in original position or not (true,false) | |||
var cat_ori_pos = true; | |||
function moveCat(ev) { | |||
if (cat_ori_pos == true) | |||
{ | |||
cat.x += 200; | |||
cat.y += 200; | |||
cat_ori_pos = false; | |||
} | |||
else | |||
{ | |||
cat.x -= 200; | |||
cat.y -= 200; | |||
cat_ori_pos = true; | |||
} | |||
} | |||
/* ---- resizing ---- */ | |||
bigger.addEventListener(MouseEvent.MOUSE_DOWN, growCat); | |||
function growCat(ev) { | |||
cat.width = cat.width * 2; | |||
cat.height = cat.height * 2; | |||
} | |||
smaller.addEventListener(MouseEvent.MOUSE_DOWN, shrinkCat); | |||
function shrinkCat(ev) { | |||
cat.width = cat.width / 2; | |||
cat.height = cat.height / 2; | |||
} | |||
/* ---- dragging ---- */ | |||
cat.buttonMode = true; | |||
cat.addEventListener(MouseEvent.MOUSE_DOWN, startDragging); | |||
cat.addEventListener(MouseEvent.MOUSE_UP, stopDragging); | |||
function startDragging(event:MouseEvent) { | |||
cat.startDrag(); | |||
} | |||
function stopDragging(event:MouseEvent) { | |||
cat.stopDrag(); | |||
} | |||
message_text.visible=false; | |||
instructions.addEventListener(MouseEvent.CLICK, messageText); | |||
function messageText(ev) { | |||
message_text.visible = !message_text.visible; | |||
} | |||
/* ---- Hiding ---- */ | |||
// can't see the dog for starters | |||
brown_dog.visible=false; | |||
hide.addEventListener(MouseEvent.CLICK, hideShow); | |||
function hideShow(ev) { | |||
// we just switch visibility to the opposite | |||
cat.visible = !cat.visible; | |||
brown_dog.visible =!brown_dog.visible; | |||
} | |||
/* ----- Playing ---- */ | |||
// There is a little problem here. If the cat movie gets bigger, the motion guide also | |||
// will grow big. Size does not refer to the cats drawing but to the composite object. | |||
// Changing just the cat requires much more advanced AS. | |||
playcat.addEventListener(MouseEvent.CLICK, playCat); | |||
function playCat(ev) { | |||
// make sure cat is visible | |||
cat.visible = true; | |||
brown_dog.visible = false; | |||
cat.play (); | |||
} | |||
</source> | |||
Notice on function definitions: | |||
If you want to write clean AS 3 code, you should define functions like this: | |||
<source lang="actionscript"> | |||
function growCat(ev:MouseEvent):void { | |||
cat.width = cat.width * 2; | |||
cat.height = cat.height * 2; | |||
} | |||
</source> | |||
The following line | |||
<source lang="actionscript"> | |||
function growCat(ev:MouseEvent):void { | |||
</source> | |||
means that we define a function (i.e. a recipe) called growCat. When an event happens, this function will | |||
be called (invoked) and given a ''mouse event'' '''argument''' to process. We called this argument i.e. the information to process ''ev'' and declared it of type ''MouseEvent''. In our code we actually never use this event information but we could for instance figure out at what exact position the user clicked. <code>:void</code> means that the function will not return any result. The function will in fact just modify properties of the cat when the event happens. We do not care about the event itself ... | |||
If you script in the timeline, this simplified code will also do | |||
<source lang="actionscript"> | |||
function growCat(ev) { | |||
cat.width = cat.width * 2; | |||
cat.height = cat.height * 2; | |||
} | |||
</source> | |||
As you can notice, in the above code we use (for demonstration purposes) both the easy "scripting" syntax and the more object-oriented one you need to adopt if you write external ActionScript code that could be loaded into your *.fla file. | |||
== Stop / start movie clips == | |||
You can stop or start an embedded movie clip like this: | |||
<source lang="actionscript"> | |||
movie_clip.start(); | |||
movie_clip.stop(); | |||
</source> | |||
; Flying Kite Example | |||
This example is discussed in the [[Flash embedded movie clip tutorial]]. Here we just include the AS code snippet that will allow you to start and stop a movie clip animation with two buttons. | |||
<source lang="actionscript"> | |||
kite.stop(); | |||
start_button.addEventListener(MouseEvent.CLICK,start_kite); | |||
stop_button.addEventListener(MouseEvent.CLICK,stop_kite); | |||
function start_kite(event:MouseEvent) { | |||
kite.play(); | |||
} | |||
function stop_kite(event:MouseEvent) { | |||
kite.stop(); | |||
} | |||
</source> | |||
: [http://tecfa.unige.ch/guides/flash/ex6/embedded-movie-clips/kite-movie.html kite-movie.html] | |||
: Source: [http://tecfa.unige.ch/guides/flash/ex6/embedded-movie-clips/kite-movie.fla kite-movie.fla] | |||
: Directory: [http://tecfa.unige.ch/guides/flash/ex6/embedded-movie-clips/ http://tecfa.unige.ch/guides/flash/ex6/embedded-movie-clips/] | |||
== Dealing with keypress events == | |||
Flash lets you intercept key presses in the same way you can intercept and deal with mouse clicks. There are some subtle differences though and I find key press events more difficult to deal with because figuring out how Flash focuses on buttons is a bit tricky. | |||
=== Moving an object with arrow keys example === | |||
The goal is to implement some code that lets you move around an object with the left/right/up/down arrow keys. | |||
The basic event handling code is very much the same as for buttons: | |||
<source lang="actionscript"> | |||
instance_of_symbol.addEventListener(KeyboardEvent.KEY_DOWN, key_even_handler); | |||
function key_event_handler(event:KeyboardEvent):void { | |||
move_it ..... | |||
} | |||
</source> | |||
The following example is based on the assumption that somewhere on the stage you have a sprite, e.g. a movie clip or a component button that is called '''missile''' and that you want to be able to move it around with around with the arrow keys. | |||
You need to implement the following things | |||
* A event listener registration like we just explained. | |||
* Tell the stage to focus on the missile | |||
<source lang="actionscript"> | |||
stage.focus = missile; | |||
</source> | |||
* The event handler function has to decide what to do with which key. | |||
Let's look at a clause of the switch statement like the following one. | |||
<source lang="actionscript"> | |||
case Keyboard.LEFT : | |||
missile.x -= big_step; | |||
break; | |||
</source> | |||
This means the following: If the user presses the left arrow key, then we will change the "x" (horizontal) position of the missile to x '''minus''' ''big_step'' (set to 9). So if the missile was in position x=100, after a mouse press event it will be in position x=91. | |||
<source lang="actionscript"> | |||
// how many pixels to move left/right | |||
var big_step = 9; | |||
// Put initial focus on missile | |||
// Focus will change when user clicks on another object (so don't) | |||
stage.focus = missile; | |||
missile.addEventListener(KeyboardEvent.KEY_DOWN, missile_control); | |||
function missile_control(event:KeyboardEvent):void { | |||
var key = event.keyCode; | |||
switch (key) { | |||
case Keyboard.LEFT : | |||
missile.x -= big_step; | |||
break; | |||
case Keyboard.RIGHT : | |||
missile.x += big_step; | |||
break; | |||
case Keyboard.UP : | |||
missile.y -= big_step; | |||
break; | |||
case Keyboard.DOWN : | |||
missile.y += big_step; | |||
break; | |||
} | |||
} | |||
</source> | |||
Here is an alternative take of the same code. The difference is that the code that will move the missile also will work for an other object, e.g. a button. The following fragment will ask from the event on which target (e.g. the missile) it was used and then move the target. | |||
<source lang="actionscript"> | |||
// how many pixels to move left/right | |||
var big_step = 9; // User clicked on missile | |||
// Put initial focus on missile | |||
// Focus will change when user clicks on another object (so don't) | |||
stage.focus = missile; | |||
missile.addEventListener(KeyboardEvent.KEY_DOWN, missile_control); | |||
function missile_control(event:KeyboardEvent):void { | |||
var key = event.keyCode; | |||
var target = event.target; | |||
// trace(event + "CODE=" + event.keyCode); | |||
switch (key) { | |||
case Keyboard.LEFT : | |||
target.x -= big_step; | |||
break; | |||
case Keyboard.RIGHT : | |||
target.x += big_step; | |||
break; | |||
case Keyboard.UP : | |||
target.y -= big_step; | |||
break;; Learning goals: | |||
case Keyboard.DOWN : | |||
target.y += big_step; | |||
break; | |||
} | |||
} | |||
</source> | |||
Sadly, this example will not work in a web browser, '''only''' in the Flash player. The missile will never receive focus. So it's probably a good idea to move to the next example. | |||
Example code: | |||
* [http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/actionscript3-keypress-move-0.html actionscript3-keypress-move-0.html] | |||
* [http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/actionscript3-keypress-move-0.swf actionscript3-keypress-move-0.swf] | |||
* Source: [http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/actionscript3-keypress-move-0.fla actionscript3-keypress-move-0.fla] | |||
* Directory: http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/ | |||
=== Dealing with the tab list problem === | |||
Flash has the feature that when you press an arrow up/left/right key it will by default move the focus on the next button. In order to inhibit this behavior I found that I had to add some extra code which is below. I don't guarantee that this is | |||
the most simple solution. | |||
<source lang="actionscript"> | |||
/* ActionScript for timeline scripting | |||
Shows how to move around a flash movie with key-presses and not loose focus | |||
Works ONLY if you have 2 objects on the stage: | |||
* A movie clip instance called "missile" | |||
* A button component instance called "button" | |||
*/ | |||
// FocusManager package has to be imported. | |||
import fl.managers.FocusManager; | |||
// how many pixels to move left/right | |||
var big_step = 9;// User clicked on missile | |||
/* If you have buttons in addition to missile on stage, then the | |||
the missile will not work as expected, i.e. it will loose focus. | |||
Extra code needed is: Tell the missile it's a button and put it on the | |||
list of "tab" buttons and also some code to put it in focus when the | |||
user clicks on it. | |||
*/ | |||
// Create a focus manager. Will help to set us the right focus | |||
var manager = new FocusManager(this); | |||
// Put initial focus on missile | |||
// since focus will change when user clicks on another object | |||
// stage.focus = missile; // works also in principle | |||
manager.setFocus(missile); | |||
// The line below is absolutely bloody vital. Missile must be on the | |||
// "tab" list, else focus will move to the button when key is hold down | |||
missile.tabEnabled = true; | |||
missile.buttonMode = true; | |||
// The missile will listen to a mouse click we will use to put focus on it again. | |||
missile.addEventListener(MouseEvent.CLICK, change_focus); | |||
function change_focus(ev:MouseEvent) { | |||
manager.setFocus(missile); | |||
// stage.focus = missile; | |||
} | |||
/* Managing keyboard events | |||
We register keyboard events for missile and the button component. The | |||
listener function is the same for both. The move_it function will ask the | |||
target over which key was pressed who it is and then move it | |||
*/ | |||
missile.addEventListener(KeyboardEvent.KEY_DOWN, missile_control); | |||
button.addEventListener(KeyboardEvent.KEY_DOWN, missile_control); | |||
function missile_control(event:KeyboardEvent):void { | |||
move_it(event); | |||
} | |||
function move_it(event) { | |||
var key = event.keyCode; | |||
var target = event.target; | |||
// trace(event + "CODE=" + event.keyCode); | |||
switch (key) { | |||
case Keyboard.LEFT : | |||
target.x -= big_step; | |||
break; | |||
case Keyboard.RIGHT : | |||
target.x += big_step; | |||
break; | |||
case Keyboard.UP : | |||
target.y -= big_step; | |||
break; | |||
case Keyboard.DOWN : | |||
target.y += big_step; | |||
break; | |||
} | |||
} | |||
</source> | |||
[[image:flash-cs3-keypress-moving.png|frame|none|Moving a Missile with key presses]] | |||
Example code: | |||
* [http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/actionscript3-keypress-move-1.html actionscript3-keypress-move-1.html] | |||
* Source: [http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/actionscript3-keypress-move-1.fla actionscript3-keypress-move-1.fla] | |||
* Directory: http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/ | |||
Note: This code is not optimal for gaming, since Flash has to wait for each key press event that the keyboard will send in order to move the missile one more step. It's probably a better idea to have the rocket keep moving as long as there isn't any keyUP event, but this requires more coding. | |||
=== Using the missile === | |||
Getting some revenge on your teacher .... | |||
* [http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/actionscript3-keypress-move.fla actionscript3-keypress-move.fla] | |||
* [http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/actionscript3-keypress-move.html actionscript3-keypress-move.html] | |||
=== Properties of the keyDown event === | |||
The keyDown event is dispatched when the user presses a key. The most important properties you may use are: | |||
* keyCode (a special code for the key, used above) | |||
* charCode (the character code value) | |||
* ctrlKey, shiftKey (know if either one of these has been pressed too) | |||
* target (the target in focus over which a key has been pressed, used above). | |||
* currentTarget (object that is processing the key event) | |||
KeyCodes are represented as numbers or constants. I prefer to use constants. | |||
* See the [http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/ui/Keyboard.html Keyboard] class documentation at Adobe. | |||
So instead of using something like: | |||
<source lang="actionscript"> | |||
if (key == 37) ... | |||
</source> | |||
use | |||
<source lang="actionscript"> | |||
if (key === Keyboard.LEFT) .... | |||
</source> | |||
== Summary of essential events and action script tricks == | |||
Let's summarize a few events and actionscript tricks that might be useful for starters and that should not be very difficult to use. | |||
=== Events === | |||
Here is a short summary of mouse events that can be intercepted by a registered | |||
event handler for a given object. So these events are only useful if you define | |||
both an event handler function and register it with an object. In the following example "cat" is an interactive object, e.g. a movie clip symbol with which we shall register a function for a mouse down event. | |||
<source lang="actionscript"> | |||
cat.addEventListener(MouseEvent.MOUSE_DOWN, resizeCat); | |||
function resizeCat(event:MouseEvent) { | |||
cat.width = blue_cat.width * 2; | |||
} | |||
</source> | |||
<table border="1"> | |||
<tr><td>MouseEvent.MOUSE_DOWN</td><td>User holds mouse button down over the object</td></tr> | |||
<tr><td>MouseEvent.MOUSE_UP</td><td>User releases mouse button</td></tr> | |||
<tr><td>MouseEvent.MOUSE_OUT</td><td>User moves mouse away from the object</td></tr> | |||
<tr><td>MouseEvent.MOUSE_WHEEL</td><td>User turns mouse wheel</td></tr> | |||
<tr><td>MouseEvent.MOUSE_OVER</td><td>User moves mouse over the object</td></tr> | |||
<tr><td>MouseEvent.CLICK</td><td>User clicks on object</td></tr> | |||
</table> | |||
Note: Technically speaking these are actually event properties (see the [[ActionScript 3 event handling tutorial]] if you want to know more). | |||
=== ActionScript tricks === | |||
'''Playing movie clips''': | |||
Movie clips symbols are embedded Flash animations. | |||
* To edit: Double click on the symbol on the stage (to see the context) or in the library (to work with an empty background) | |||
* To create | |||
** CTRL-F8 to create a new empty movie clip | |||
** ''Right-click->Create Movie Symbol; 'Movie Clip'' on a graphic to transform it | |||
* To play an stop a movie clip instance called "movie_books" | |||
<source lang="actionscript"> | |||
movie_books.stop(); | |||
movie_books.play(); | |||
</source> | |||
'''Making objects visible/invisible''', works with any display object but you should work with an object that you can name, i.e. a symbol instance. | |||
* If you have an object called ''cat'': | |||
<source lang="actionscript"> | |||
cat.visible = true; | |||
cat.visible = false; | |||
</source> | |||
'''Moving position of an object''', works with any display object | |||
* If you have an object called ''cat'' you can set both its x and y position. x starts from the left and y means "down". Therefore, x=0 y=0 means the upper left corner of the stage. | |||
Example - position cat at x is 100 and y is 200 pixels: | |||
<source lang="actionscript"> | |||
cat.x = 100; cat.y = 200; | |||
</source> | |||
Example - add 50 px to cat's current position | |||
<source lang="actionscript"> | |||
cat.x += 50; cat.y += 50; | |||
</source> | |||
'''Resize an object''', works with any display object | |||
* If you have an object called ''cat'': | |||
Example, cat will be 100 px wide and 120px tall | |||
<source lang="actionscript"> | |||
cat.width = 100; | |||
cat.height = 120; | |||
</source> | |||
Example, cat will double its size. Expression below means, set cat.width to old cat.width times 2. | |||
<source lang="actionscript"> | |||
cat.width = cat.width * 2; | |||
cat.height = cat.height * 2; | |||
</source> | |||
'''Dragging an object''', works with any interactive object | |||
* If you have an object called ''cat'', you can start/stop dragging. Usually these are bound to MOUSE_DOWN and MOUSE_UP. | |||
<source lang="actionscript"> | |||
cat.startDrag(); | |||
cat.stopDrag(); | |||
</source> | |||
'''Moving around in the timeline'''. You can either go to a frame and play it (until it encounters a stop) or go there and stop. | |||
If you want to go to frame 12 of the same scene: | |||
<source lang="actionscript"> | |||
gotoAndPlay(12); | |||
gotoAndStop(12); | |||
</source> | |||
If you want to go to frame 13 of a scene called "test": | |||
<source lang="actionscript"> | |||
gotoAndPlay(13,"test"); | |||
gotoAndStop(13,"test"); | |||
</source> | |||
== Tweening and interactivity self-revision examples == | |||
Examples from an exam (to be improved and documented at some point) | |||
=== 2007 Exam === | |||
* Frame 1 (home): Buttons should not lead you to frame 1 (home), but to the various other keyframes. Also add your name. | |||
* Frame 2 (Sailing): (a) Play the tween animation of boat with the 'what's going on here' button. (b) BONUS Point: Create and play a motion animation of a plane. | |||
* Frame 3 (Driving): (a) Create an animation that will start moving the car from right to left and slightly forward too (i.e. keep it on the road). To animate the car edit the 'old car' symbol and make it a motion tween. Then link it to the ''what's going on here'' button (b) BONUS Point: Do something with the yellow car. | |||
* Frame 4 (Island): (a) Make the trees visible when the user clicks on the ''what's going on'' button. (b) BONUS point: Improve the frame-by-frame animation of the big tree. | |||
* Frame 5 (Rocket): (a) Write code that will launch the rocket. (b) BONUS: Do something with the snakes | |||
Tip: For starters, you can navigate with the little button on top right. Do not edit layer one ! | |||
* [http://tecfa.unige.ch/guides/flash/ex/exams2007/final-exam-coap2110-solution-2007.html final-exam-coap2110-solution-2007.html] (look at the solution first) | |||
* Source exam file: [http://tecfa.unige.ch/guides/flash/ex/exams2007/final-exam-coap2110-2007.fla final-exam-coap2110-2007.fla] (download this and try reproduce the solution) | |||
* Source solution: [http://tecfa.unige.ch/guides/flash/ex/exams2007/final-exam-coap2110-solution-2007.fla final-exam-coap2110-solution-2007.fla] (if you are stuck) | |||
* Directory: http://tecfa.unige.ch/guides/flash/ex/exams2007/ | |||
=== 2008 Exam === | |||
* [http://tecfa.unige.ch/guides/flash/ex/exams2008/final-coap2110-2008-SOLUTION.html final-coap2110-2008-SOLUTION.html] Look at the solution first | |||
* [http://tecfa.unige.ch/guides/flash/ex/exams2008/final-coap2110-2008-handout.pdf Read the exam tasks] (PDF file) | |||
* Source exam file: [http://tecfa.unige.ch/guides/flash/ex/exams2008/final-coap2110-2008.fla final-coap2110-2008.fla] (download this and try to "do the exam" according to instructions) | |||
* Source solution: [http://tecfa.unige.ch/guides/flash/ex/exams2008/final-coap2110-2008-SOLUTION.fla final-coap2110-2008-SOLUTION.fla] (if you are stuck) | |||
== Links == | |||
=== Important manual pages === | |||
The [http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/index.html?filter_flashplayer=11.6# Actionscript manual] at Adobe is almost impossible to understand for non programmers, but other than that, the ActionScript documentation at Adobe is excellent. Beginners can at least figure out property names and some easy to use methods... | |||
* [http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/InteractiveObject.html InteractiveObject]. This InteractiveObject class is the abstract base class for all display objects with which the user can interact, using the mouse and keyboard. Most Events are documented here. (Make sure to list also the inherited events). | |||
* [http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/MovieClip.html Movie clip] (this subclass adds properties and methods for timeline scripting) | |||
* [http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObject.html DisplayObject]. Describes the display object, e.g. properties you can change. Note that there are additional properties for each specific kind of object, i.e. see [[Flash_ActionScript_3_overview#The_DisplayObject|the class hierarchy described in the Flash ActionScript 3 Overview]]. | |||
=== Clip Art === | |||
* [http://www.free-clip-art.com/members/content/cgi-bin/imageFolio.cgi?direct=Animal_Clip_Art Free Clip Art]. Original cat and dog | |||
* [http://www.openclipart.org/ Open Clip Art Library]. The grey mouse and the original rocket. | |||
[[Category: Multimedia]] | |||
[[Category: Flash]] | |||
[[Category: Actionscript 3]] | |||
[[Category:Flash tutorials]] |
Latest revision as of 18:40, 22 August 2016
Overview
- Learning goals
The purpose of this tutorial is go a little bit beyond dealing with mouse clicks, buttons and button components as seen in previous tutorials, i.e. you will learn how to change properties of objects (such as position, size and visibility) and how to play embedded movie clips:
- Learn about how to use mouse and key-press events.
- Learn about some object properties you can easily change with a little ActionScript code
- Learn some ActionScript control statements (if-then-else clause and assignments)
- Learn how to play embedded Flash movie clips.
- Learn how to use embedded Flash movie clips for multiple animations
- Prerequisites
- Flash CS6 desktop tutorial
- Flash drawing tutorial
- Flash button tutorial
- Flash component button tutorial
- Flash embedded movie clip tutorial
- Other recommended prior tutorials (not necessary, but can help)
- Flash video component tutorial
- Flash sound tutorial
- ActionScript 3 event handling tutorial
- Moving on
- Flash drag and drop tutorial
- Flash games tutorial
- Flash ActionScript 3 overview
- The Flash tutorials index has a list of other tutorials.
- Alternative versions
- ActionScript 3 interactive objects tutorial (CS3) (old version)
- Level and target population
- It aims at Flash designers, not beginning ActionScript 3 programmers, although programmers can read this to get a feeling for object properties before digging into a real documentation like Adobe's Flash 9 reference manual. Also, some of the code should be rewritten a bit. I skipped type declarations on purpose and should even rip off more. These don't make sense for a few lines of code written by/for non-programmers. The goal is to keep code as simple as possible. I should at some point decide whether I should remove all type declarations from the examples or consistently leave the ones that might be useful in order to receive compiler warnings.
- Quality
- This text should technical people get going and may not be good enough for self-learning beginners. It can be used as handout in a "hands-on" class. That is what Daniel K. Schneider made it for...
- Learning materials
Grab the various *.fla files from here:
Manipulating objects
The principle of (simple) object manipulation is fairly simple: change properties of a display object. The tricky thing is to know what you can change on a given kind of object. Some changes are easy to make, others are really hard. Typically, most objects are non-editable (its component objects maybe are). It's easy to change size and position of a display object, i.e. operations you could do on grouped objects and symbol instances with the transform tool or the parameters panel.
Below, we show a few little examples that demonstrate how to manipulate objects with mouse events (see the ActionScript 3 event handling tutorial for more details). All the objects on the stage (e.g. black_cat) are instances of movie clip symbols. These are a kind of interactive object and react to mouse and keyboard events. The kind of tricks will we show act on named instances movie clips.
You could imagine dozens of other simple examples, but it's not so easy to understand the technical ActionScript documentation which is made for programmers and not designers. If you feel more adventurous, you may have a look at the class hierarchy described in the Flash ActionScript 3 overview and in particular the Display Object and its children. Follow up a link to the Flash documentation and see if you can find other properties that are easy to manipulate...
Simple repositioning example
To understand what is going on below, you may want to look at:
And also load the *.fla file
In order to reposition an object, change its x and y properties.
In the following example, when you click on the interactive object (a symbol instance that is called "black_cat") it will move itself to position x= 200 and y=200. Note: Position is defined by the center of the display object (i.e. the little "+" sign who's value depends on how you made it).
black_cat.addEventListener(MouseEvent.CLICK, moveCat);
function moveCat(event:MouseEvent):void {
black_cat.x = 200;
black_cat.y = 200;
}
A statement like
cat.x = 100;
is called an assignment and means: The x property of the cat object will become "100".
If you want to move the cat forth and back you'd rather use this code:
black_cat.addEventListener(MouseEvent.CLICK, moveCat);
// cat can be in original position or not (true,false)
var black_cat_ori_pos = true;
function moveCat(event:MouseEvent):void {
if (black_cat_ori_pos == true)
{
black_cat.x += 200;
black_cat.y += 200;
black_cat_ori_pos = false;
}
else
{
black_cat.x -= 200;
black_cat.y -= 200;
black_cat_ori_pos = true;
}
}
In this function we use a so-called if-then-else statement. The line
if (black_cat_ori_pos == true)
checks if the variable black_cat_ori_pos has the value of true. If this is true we then execute the clause { black_cat.x += ... ; black_cat.y ..... }
that follows. If it is not true we execute the other {...} clause after the else.
Also note the difference between an assignment ("=") and an equality test ("=="). The latter will test if two values are the same. Note to beginners: never use just the "=" inside the conditional of an "if". Use "==".
Let's describe this at a more conceptual level: black_cat_ori_pos can be called a "flag" variable since it will register whether the cat is in a new position or the original old position. If it's in the new one, we will move it back, and the other way round. So
black_cat_ori_pas == true
tests if the cat sits in its original position.
X and Y positions are defined with respect to the upper left corner. E.g. if x is 100 and y is 100, the registered center point of the object is 100 pixels to the right and 100 pixels down. The instruction:
x += 100;
x -= 100;
means "add 100 to x" or "subtract 100 from x". So it's a shortcut for x = x + 100;, i.e. "new value of x becomes old value of x plus 100".
Code above isn't of the kind that a real programmer would use. Therefore, if you are familiar with programming, rather go for something like the following. Beginners, please ignore. The following function would work with any object (not just a given cat). It will retrieve the symbol instance from the event object. Original position of the object is remembered in the object itself, using a new property we create (ori_x and ori_y).
function moveIt(event:MouseEvent):void
{
var obj = event.target;
// initialize original values if necessary (on first pass)
// test if properties ori_ exist, if not create them
if (! ("ori_x" in obj))
{
obj.ori_x = obj.x;
obj.ori_y = obj.y;
obj.buttonMode = true; // for better UX, this could be done before
}
// Is object in original position ? If so move close to friend
if (obj.ori_x == obj.x)
{
obj.x =+ 200;
obj.y =+ 200;
}
else
{
obj.x = obj.ori_x;
obj.y = obj.ori_y;
}
}
Change size
Changing size, means to change width and height properties. In the following example, when you click on the interactive object (a symbol instance that is called "blue_cat") it will double its size when you hold down the mouse button and go back to normal when you release it. Note: If you hold down the button and then move the mouse out (still holding down), and only then release the button, the mouse will stay big since it never will catch the mouse up event.
blue_cat.addEventListener(MouseEvent.MOUSE_DOWN, resizeCat);
function resizeCat(event:MouseEvent):void {
blue_cat.width = blue_cat.width * 2;
blue_cat.height = blue_cat.height * 2;
}
blue_cat.addEventListener(MouseEvent.MOUSE_UP, resizeCat2);
function resizeCat2(event:MouseEvent):void {
blue_cat.width = blue_cat.width / 2;
blue_cat.height = blue_cat.height / 2;
}
This code may not exactly do what you want. As we said, if the user holds down the mouse button and moves it out, the MOUSE_UP event will never happen, i.e. the cat will grow permanently. A better solution can be found in the example code that we included at the end of this section.
Visibility
In the following example, we will make a white cat invisible when you click on it. Technical note: It is still there, but the user can't click on it.
white_cat.addEventListener(MouseEvent.CLICK, hideCat);
function hideCat(event:MouseEvent):void {
white_cat.visible = false;
}
Once the cat is hidden, the user never will be able to bring it back. Therefore, in the next example we decided to implement a switch between a cat and a dog:
// can't see the dog for starters
brown_dog.visible=false;
brown_dog.addEventListener(MouseEvent.CLICK, hideShow);
white_cat.addEventListener(MouseEvent.CLICK, hideShow);
function hideShow(event:MouseEvent):void {
// instead of using white_cat.visible = false; we just switch it to the opposite
white_cat.visible = !white_cat.visible;
brown_dog.visible =!brown_dog.visible;
}
The "!
" used for white_cat.visible
in the hideShow function means that the "visible" property will be set to its opposite. E.g. if the value is true it will become false, and the other way round. Same technique for the dog (which is invisible for starters).
Let the user drag example
The next example shows how to let a user drag the red cat object with the mouse (button pressed down) and then drop the cat when the user releases the mouse button.
red_cat.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
red_cat.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
function startDragging(event:MouseEvent):void
{
red_cat.startDrag();
}
function stopDragging(event:MouseEvent):void
{
red_cat.stopDrag();
}
For a tutorial on dragging and dropping, see the Flash drag and drop tutorial that demonstrates how to implement a simple children's educational game. You will learn for instance how to test if a dropped object will sit on top of another one.
Transformations
So-called "transforms" of a non-editable display object are more tricky. We just will demonstrate how to change the tint with a color transform. You also could skew an object with a similar strategy. However, this kind of code is really a bit too difficult to understand without some prior introduction to object-oriented programming.
Color: The ColorTransform class lets you adjust the color values in a display object. The color adjustment or color transformation can be applied to all four channels: red, green, blue, and alpha transparency. Here are the formula according to the manual, retrieved 20:58, 8 October 2007 (MEST):
- New red value = (old red value * redMultiplier) + redOffset
- New green value = (old green value * greenMultiplier) + greenOffset
- New blue value = (old blue value * blueMultiplier) + blueOffset
- New alpha value = (old alpha value * alphaMultiplier) + alphaOffset
The tricky thing is that you have to program transformations with a temporary ColorTransform object and then copy this object to the display object's colorTransform property if I understood the manual right. See the code toward the end of the full example code below.
Cat example file
The (all-in-one) file with the examples we discussed above is here:
Directory with files actionscript3-simple-object-manipulation.*:
Here is the complete ActionScript code:
/* ----- Change cursor form
add a hand to cursor to each cat
This way a user understands that he/she can do something with the object.
*/
black_cat.buttonMode = true;
blue_cat.buttonMode = true;
red_cat.buttonMode = true;
brown_dog.buttonMode = true;
white_cat.buttonMode = true;
empty_cat.buttonMode = true;
grey_mouse.buttonMode = true;
/* ---- moving ---- */
black_cat.addEventListener(MouseEvent.CLICK, moveCat);
// cat can be in original position or not (true,false)
var black_cat_ori_pos = true;
function moveCat(event:MouseEvent):void {
if (black_cat_ori_pos == true)
{
black_cat.x += 200;
black_cat.y += 200;
black_cat_ori_pos = false;
}
else
{
black_cat.x -= 200;
black_cat.y -= 200;
black_cat_ori_pos = true;
}
}
/* ---- resizing ---- */
blue_cat.addEventListener(MouseEvent.MOUSE_DOWN, resizeCat);
var cat_size = 1;
function resizeCat(event:MouseEvent):void {
blue_cat.width = blue_cat.width * 2;
blue_cat.height = blue_cat.height * 2;
cat_size = 2;
}
// We have to test both mouse up and mouse out since user can
// press mouse and move out. Cat in this case would stay big.
// Also we have to test if cat is already big when user moves in.
blue_cat.addEventListener(MouseEvent.MOUSE_UP, resizeCat2);
blue_cat.addEventListener(MouseEvent.MOUSE_OUT, resizeCat2);
function resizeCat2(event:MouseEvent):void {
if (cat_size > 1)
{
blue_cat.width = blue_cat.width / 2;
blue_cat.height = blue_cat.height / 2;
cat_size = 1;
}
}
/* ---- dragging ---- */
red_cat.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
red_cat.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
function startDragging(event:MouseEvent):void {
red_cat.startDrag();
}
function stopDragging(event:MouseEvent):void {
red_cat.stopDrag();
}
/* ---- Hiding ---- */
// can't see the dog for starters
brown_dog.visible=false;
brown_dog.addEventListener(MouseEvent.CLICK, hideShow);
white_cat.addEventListener(MouseEvent.CLICK, hideShow);
function hideShow(event:MouseEvent):void {
// instead of white_cat.visible = false; we just switch it to the opposite
white_cat.visible = !white_cat.visible;
brown_dog.visible =!brown_dog.visible;
}
/* ---- transforms ----
This is a bit more difficult.... */
empty_cat.addEventListener(MouseEvent.CLICK, transformCatColor);
// R,G,B,A multipliers and R,G,B,A offsets
// We start with a light grey cat
var resultColorTransform = new ColorTransform (0.1,0.1,0.1,1,120,120,120,255);
empty_cat.transform.colorTransform = resultColorTransform;
function transformCatColor(event:MouseEvent):void {
var resultColorTransform = empty_cat.transform.colorTransform;
// Create a new color transform object and change it
// red color will peak at 255, blue color offset will cycle from +255 to -100
resultColorTransform.redOffset = Math.min(resultColorTransform.redOffset+10,255);
resultColorTransform.redMultiplier = Math.min(resultColorTransform.redMultiplier+0.1,1);
resultColorTransform.blueOffset += 10;
if (resultColorTransform.blueOffset >= 255)
{
resultColorTransform.blueOffset = -100;
}
resultColorTransform.blueMultiplier = 0.1;
// Copy that to the cat
empty_cat.transform.colorTransform = resultColorTransform;
//trace("redOffset="+resultColorTransform.redOffset +
// " blueOffset="+resultColorTransform.blueOffset);
}
/* ---- permanent size change ---- */
grey_mouse.addEventListener(MouseEvent.MOUSE_WHEEL, changeMouse);
function changeMouse(event:MouseEvent):void {
grey_mouse.width += event.delta*3;
grey_mouse.height += event.delta*3;
}
Simple repositioning example with better code
The example of the previous section uses some kind of "baby programmer" code, e.g. the functions only work with very specific objects and there are many global variables. Somewhat better code will include functions that could work with any object and avoid using variables.
In the following example you can associate any function with any symbol. E.g. the red cat now can be both dragged and change size using the mouse wheel. Same of the mouse. The code is also separateed it in two sections. On top, we define event handlers for objects. An end-user (Flash Designer) could just add his/her own objects and decide which event handlers to use ....
The (all-in-one) file with the examples we discussed above is here:
Directory with files actionscript3-simple-object-manipulation.*:
/* ------- List of objects and Event handlers ------------- */
// black cat - will move next to his red friend
black_cat.addEventListener(MouseEvent.CLICK, moveIt);
black_cat.friend = red_cat;
// blue cat - will change size on mouse down ;
blue_cat.addEventListener(MouseEvent.MOUSE_DOWN, resizeIt);
// We have to test both mouse up and mouse out since user can;
// press mouse and move out. Cat in this case would stay big.
// Also we have to test if cat is already big when user moves in.
blue_cat.addEventListener(MouseEvent.MOUSE_UP, downsizeIt);
blue_cat.addEventListener(MouseEvent.MOUSE_OUT, downsizeIt);
// red cat and mouse - can be dragged
red_cat.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
red_cat.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
grey_mouse.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
grey_mouse.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
// dog and cat switch
// can't see the dog for starters
brown_dog.buttonMode = true; // change cursor form here for a change
white_cat.buttonMode = true;
brown_dog.visible = false;
brown_dog.addEventListener(MouseEvent.CLICK, hideShow);
white_cat.addEventListener(MouseEvent.CLICK, hideShow);
white_cat.friend = brown_dog;
brown_dog.friend = white_cat;
// mouse and red cat -- size change with wheel
grey_mouse.addEventListener(MouseEvent.MOUSE_WHEEL, changeSize);
red_cat.addEventListener(MouseEvent.MOUSE_WHEEL, changeSize);
empty_cat.addEventListener(MouseEvent.CLICK, transformCatColor);
// R,G,B,A multipliers and R,G,B,A offsets - we start with a light grey cat
empty_cat.transform.colorTransform = new ColorTransform(0.1,0.1,0.1,1,120,120,120,255);
Below is the complete code
/* This example attempts to write more portable code.
Any of the functions will work with any movie symbol.
No more global variables...
*/
/* ------- List of objects and Event handlers ------------- */
// black cat - will move next to his red friend
black_cat.addEventListener(MouseEvent.CLICK, moveIt);
black_cat.friend = red_cat;
// blue cat - will change size on mouse down ;
blue_cat.addEventListener(MouseEvent.MOUSE_DOWN, resizeIt);
// We have to test both mouse up and mouse out since user can;
// press mouse and move out. Cat in this case would stay big.
// Also we have to test if cat is already big when user moves in.
blue_cat.addEventListener(MouseEvent.MOUSE_UP, downsizeIt);
blue_cat.addEventListener(MouseEvent.MOUSE_OUT, downsizeIt);
// red cat and mouse - can be dragged
red_cat.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
red_cat.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
grey_mouse.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
grey_mouse.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
// dog and cat switch
// can't see the dog for starters
brown_dog.buttonMode = true; // change cursor form here for a change
white_cat.buttonMode = true;
brown_dog.visible = false;
brown_dog.addEventListener(MouseEvent.CLICK, hideShow);
white_cat.addEventListener(MouseEvent.CLICK, hideShow);
white_cat.friend = brown_dog;
brown_dog.friend = white_cat;
// mouse and red cat -- size change with wheel
grey_mouse.addEventListener(MouseEvent.MOUSE_WHEEL, changeSize);
red_cat.addEventListener(MouseEvent.MOUSE_WHEEL, changeSize);
empty_cat.addEventListener(MouseEvent.CLICK, transformCatColor);
// R,G,B,A multipliers and R,G,B,A offsets - we start with a light grey cat
empty_cat.transform.colorTransform = new ColorTransform(0.1,0.1,0.1,1,120,120,120,255);
/* ---- moving ---- */
function moveIt(event:MouseEvent):void
{
var obj = event.target;
// initialize original values if necessary (on first pass)
// test if properties ori_ exist, if not create them
if (! ("ori_x" in obj))
{
obj.ori_x = obj.x;
obj.ori_y = obj.y;
obj.buttonMode = true; // for better UX, this could be done before
}
// Is object in original position ? If so move close to friend
if (obj.ori_x == obj.x)
{
obj.x = obj.friend.x + 50;
obj.y = obj.friend.y - 10;
}
else
{
obj.x = obj.ori_x;
obj.y = obj.ori_y;
}
}
/* ---- resizing ---- */
function resizeIt(event:MouseEvent):void
{
var obj = event.target;
// initialize properties if needed
if (! (obj.hasOwnProperty("bigger")) )
{
obj.bigger = false; // remembers its size big or not
obj.buttonMode = true;
}
// make the object bigger
obj.width = obj.width * 2;
obj.height = obj.height * 2;
obj.bigger = true;
}
function downsizeIt(event:MouseEvent):void
{
var obj = event.target;
if (! (obj.hasOwnProperty("bigger")) )
{
obj.bigger = false; // remembers its size big or not
obj.buttonMode = true;
}
// if orginal width is not the same as current, we assume that it's bigger
// and then divide it by 2
if (obj.bigger == true)
{
obj.width = obj.width / 2;
obj.height = obj.height / 2;
}
}
/* ---- dragging ---- */
function startDragging(event:MouseEvent):void
{
var obj = event.target;
obj.startDrag();
}
function stopDragging(event:MouseEvent):void
{
var obj = event.target;
obj.stopDrag();
}
/* ---- Hiding ---- */
function hideShow(event:MouseEvent):void
{
var obj = event.target;
// target becomes invisible
obj.visible = false;
// friend becomes visible
obj.friend.visible = true;
}
/* ---- transforms ----
This is a bit more difficult.... */
function transformCatColor(event:MouseEvent):void
{
var obj = event.target;
var resultColorTransform = empty_cat.transform.colorTransform;
// Create a new color transform object and change it
// red color will peak at 255, blue color offset will cycle from +255 to -100
resultColorTransform.redOffset = Math.min(resultColorTransform.redOffset + 10,255);
resultColorTransform.redMultiplier = Math.min(resultColorTransform.redMultiplier + 0.1,1);
resultColorTransform.blueOffset += 10;
if (resultColorTransform.blueOffset >= 255)
{
resultColorTransform.blueOffset = -100;
}
resultColorTransform.blueMultiplier = 0.1;
// Copy that to the cat
obj.transform.colorTransform = resultColorTransform;
//trace("redOffset="+resultColorTransform.redOffset +
// " blueOffset="+resultColorTransform.blueOffset);
}
/* ---- permanent size change with mouse wheel ---- */
function changeSize(event:MouseEvent):void
{
var obj = event.target;
obj.width += event.delta * 3;
obj.height += event.delta * 3;
}
Remote cat control example
Here is another example that demonstrates the following principles:
- You can modify an object's properties from an event triggered on another object (e.g. button components)
- Play an embedded animation
I also simplified the way functions are written, i.e. I ripped off argument type declarations and the return type. This is not necessarily a good thing, but it should demonstrate to designers that a little bit of ActionScript is not necessarily very complex ....
The example can be viewed here:
- actionscript3-simple-object-manipulation-buttons.html
- Source: actionscript3-simple-object-manipulation-buttons.fla
- Directory:
Here is the complete code: On the stage are several buttons (named like "bigger", "smaller", etc.), a cat movie clip instance called "cat" and a dog called "brown_dog".
/* ---- moving ---- */
move.addEventListener(MouseEvent.CLICK, moveCat);
// cat can be in original position or not (true,false)
var cat_ori_pos = true;
function moveCat(ev) {
if (cat_ori_pos == true)
{
cat.x += 200;
cat.y += 200;
cat_ori_pos = false;
}
else
{
cat.x -= 200;
cat.y -= 200;
cat_ori_pos = true;
}
}
/* ---- resizing ---- */
bigger.addEventListener(MouseEvent.MOUSE_DOWN, growCat);
function growCat(ev) {
cat.width = cat.width * 2;
cat.height = cat.height * 2;
}
smaller.addEventListener(MouseEvent.MOUSE_DOWN, shrinkCat);
function shrinkCat(ev) {
cat.width = cat.width / 2;
cat.height = cat.height / 2;
}
/* ---- dragging ---- */
cat.buttonMode = true;
cat.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
cat.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
function startDragging(event:MouseEvent) {
cat.startDrag();
}
function stopDragging(event:MouseEvent) {
cat.stopDrag();
}
message_text.visible=false;
instructions.addEventListener(MouseEvent.CLICK, messageText);
function messageText(ev) {
message_text.visible = !message_text.visible;
}
/* ---- Hiding ---- */
// can't see the dog for starters
brown_dog.visible=false;
hide.addEventListener(MouseEvent.CLICK, hideShow);
function hideShow(ev) {
// we just switch visibility to the opposite
cat.visible = !cat.visible;
brown_dog.visible =!brown_dog.visible;
}
/* ----- Playing ---- */
// There is a little problem here. If the cat movie gets bigger, the motion guide also
// will grow big. Size does not refer to the cats drawing but to the composite object.
// Changing just the cat requires much more advanced AS.
playcat.addEventListener(MouseEvent.CLICK, playCat);
function playCat(ev) {
// make sure cat is visible
cat.visible = true;
brown_dog.visible = false;
cat.play ();
}
Notice on function definitions:
If you want to write clean AS 3 code, you should define functions like this:
function growCat(ev:MouseEvent):void {
cat.width = cat.width * 2;
cat.height = cat.height * 2;
}
The following line
function growCat(ev:MouseEvent):void {
means that we define a function (i.e. a recipe) called growCat. When an event happens, this function will
be called (invoked) and given a mouse event argument to process. We called this argument i.e. the information to process ev and declared it of type MouseEvent. In our code we actually never use this event information but we could for instance figure out at what exact position the user clicked. :void
means that the function will not return any result. The function will in fact just modify properties of the cat when the event happens. We do not care about the event itself ...
If you script in the timeline, this simplified code will also do
function growCat(ev) {
cat.width = cat.width * 2;
cat.height = cat.height * 2;
}
As you can notice, in the above code we use (for demonstration purposes) both the easy "scripting" syntax and the more object-oriented one you need to adopt if you write external ActionScript code that could be loaded into your *.fla file.
Stop / start movie clips
You can stop or start an embedded movie clip like this:
movie_clip.start();
movie_clip.stop();
- Flying Kite Example
This example is discussed in the Flash embedded movie clip tutorial. Here we just include the AS code snippet that will allow you to start and stop a movie clip animation with two buttons.
kite.stop();
start_button.addEventListener(MouseEvent.CLICK,start_kite);
stop_button.addEventListener(MouseEvent.CLICK,stop_kite);
function start_kite(event:MouseEvent) {
kite.play();
}
function stop_kite(event:MouseEvent) {
kite.stop();
}
- kite-movie.html
- Source: kite-movie.fla
- Directory: http://tecfa.unige.ch/guides/flash/ex6/embedded-movie-clips/
Dealing with keypress events
Flash lets you intercept key presses in the same way you can intercept and deal with mouse clicks. There are some subtle differences though and I find key press events more difficult to deal with because figuring out how Flash focuses on buttons is a bit tricky.
Moving an object with arrow keys example
The goal is to implement some code that lets you move around an object with the left/right/up/down arrow keys.
The basic event handling code is very much the same as for buttons:
instance_of_symbol.addEventListener(KeyboardEvent.KEY_DOWN, key_even_handler);
function key_event_handler(event:KeyboardEvent):void {
move_it .....
}
The following example is based on the assumption that somewhere on the stage you have a sprite, e.g. a movie clip or a component button that is called missile and that you want to be able to move it around with around with the arrow keys.
You need to implement the following things
- A event listener registration like we just explained.
- Tell the stage to focus on the missile
stage.focus = missile;
- The event handler function has to decide what to do with which key.
Let's look at a clause of the switch statement like the following one.
case Keyboard.LEFT :
missile.x -= big_step;
break;
This means the following: If the user presses the left arrow key, then we will change the "x" (horizontal) position of the missile to x minus big_step (set to 9). So if the missile was in position x=100, after a mouse press event it will be in position x=91.
// how many pixels to move left/right
var big_step = 9;
// Put initial focus on missile
// Focus will change when user clicks on another object (so don't)
stage.focus = missile;
missile.addEventListener(KeyboardEvent.KEY_DOWN, missile_control);
function missile_control(event:KeyboardEvent):void {
var key = event.keyCode;
switch (key) {
case Keyboard.LEFT :
missile.x -= big_step;
break;
case Keyboard.RIGHT :
missile.x += big_step;
break;
case Keyboard.UP :
missile.y -= big_step;
break;
case Keyboard.DOWN :
missile.y += big_step;
break;
}
}
Here is an alternative take of the same code. The difference is that the code that will move the missile also will work for an other object, e.g. a button. The following fragment will ask from the event on which target (e.g. the missile) it was used and then move the target.
// how many pixels to move left/right
var big_step = 9; // User clicked on missile
// Put initial focus on missile
// Focus will change when user clicks on another object (so don't)
stage.focus = missile;
missile.addEventListener(KeyboardEvent.KEY_DOWN, missile_control);
function missile_control(event:KeyboardEvent):void {
var key = event.keyCode;
var target = event.target;
// trace(event + "CODE=" + event.keyCode);
switch (key) {
case Keyboard.LEFT :
target.x -= big_step;
break;
case Keyboard.RIGHT :
target.x += big_step;
break;
case Keyboard.UP :
target.y -= big_step;
break;; Learning goals:
case Keyboard.DOWN :
target.y += big_step;
break;
}
}
Sadly, this example will not work in a web browser, only in the Flash player. The missile will never receive focus. So it's probably a good idea to move to the next example.
Example code:
- actionscript3-keypress-move-0.html
- actionscript3-keypress-move-0.swf
- Source: actionscript3-keypress-move-0.fla
- Directory: http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/
Dealing with the tab list problem
Flash has the feature that when you press an arrow up/left/right key it will by default move the focus on the next button. In order to inhibit this behavior I found that I had to add some extra code which is below. I don't guarantee that this is the most simple solution.
/* ActionScript for timeline scripting
Shows how to move around a flash movie with key-presses and not loose focus
Works ONLY if you have 2 objects on the stage:
* A movie clip instance called "missile"
* A button component instance called "button"
*/
// FocusManager package has to be imported.
import fl.managers.FocusManager;
// how many pixels to move left/right
var big_step = 9;// User clicked on missile
/* If you have buttons in addition to missile on stage, then the
the missile will not work as expected, i.e. it will loose focus.
Extra code needed is: Tell the missile it's a button and put it on the
list of "tab" buttons and also some code to put it in focus when the
user clicks on it.
*/
// Create a focus manager. Will help to set us the right focus
var manager = new FocusManager(this);
// Put initial focus on missile
// since focus will change when user clicks on another object
// stage.focus = missile; // works also in principle
manager.setFocus(missile);
// The line below is absolutely bloody vital. Missile must be on the
// "tab" list, else focus will move to the button when key is hold down
missile.tabEnabled = true;
missile.buttonMode = true;
// The missile will listen to a mouse click we will use to put focus on it again.
missile.addEventListener(MouseEvent.CLICK, change_focus);
function change_focus(ev:MouseEvent) {
manager.setFocus(missile);
// stage.focus = missile;
}
/* Managing keyboard events
We register keyboard events for missile and the button component. The
listener function is the same for both. The move_it function will ask the
target over which key was pressed who it is and then move it
*/
missile.addEventListener(KeyboardEvent.KEY_DOWN, missile_control);
button.addEventListener(KeyboardEvent.KEY_DOWN, missile_control);
function missile_control(event:KeyboardEvent):void {
move_it(event);
}
function move_it(event) {
var key = event.keyCode;
var target = event.target;
// trace(event + "CODE=" + event.keyCode);
switch (key) {
case Keyboard.LEFT :
target.x -= big_step;
break;
case Keyboard.RIGHT :
target.x += big_step;
break;
case Keyboard.UP :
target.y -= big_step;
break;
case Keyboard.DOWN :
target.y += big_step;
break;
}
}
Example code:
- actionscript3-keypress-move-1.html
- Source: actionscript3-keypress-move-1.fla
- Directory: http://tecfa.unige.ch/guides/flash/ex6/action-script-3-intro/
Note: This code is not optimal for gaming, since Flash has to wait for each key press event that the keyboard will send in order to move the missile one more step. It's probably a better idea to have the rocket keep moving as long as there isn't any keyUP event, but this requires more coding.
Using the missile
Getting some revenge on your teacher ....
Properties of the keyDown event
The keyDown event is dispatched when the user presses a key. The most important properties you may use are:
- keyCode (a special code for the key, used above)
- charCode (the character code value)
- ctrlKey, shiftKey (know if either one of these has been pressed too)
- target (the target in focus over which a key has been pressed, used above).
- currentTarget (object that is processing the key event)
KeyCodes are represented as numbers or constants. I prefer to use constants.
- See the Keyboard class documentation at Adobe.
So instead of using something like:
if (key == 37) ...
use
if (key === Keyboard.LEFT) ....
Summary of essential events and action script tricks
Let's summarize a few events and actionscript tricks that might be useful for starters and that should not be very difficult to use.
Events
Here is a short summary of mouse events that can be intercepted by a registered event handler for a given object. So these events are only useful if you define both an event handler function and register it with an object. In the following example "cat" is an interactive object, e.g. a movie clip symbol with which we shall register a function for a mouse down event.
cat.addEventListener(MouseEvent.MOUSE_DOWN, resizeCat);
function resizeCat(event:MouseEvent) {
cat.width = blue_cat.width * 2;
}
MouseEvent.MOUSE_DOWN | User holds mouse button down over the object |
MouseEvent.MOUSE_UP | User releases mouse button |
MouseEvent.MOUSE_OUT | User moves mouse away from the object |
MouseEvent.MOUSE_WHEEL | User turns mouse wheel |
MouseEvent.MOUSE_OVER | User moves mouse over the object |
MouseEvent.CLICK | User clicks on object |
Note: Technically speaking these are actually event properties (see the ActionScript 3 event handling tutorial if you want to know more).
ActionScript tricks
Playing movie clips: Movie clips symbols are embedded Flash animations.
- To edit: Double click on the symbol on the stage (to see the context) or in the library (to work with an empty background)
- To create
- CTRL-F8 to create a new empty movie clip
- Right-click->Create Movie Symbol; 'Movie Clip on a graphic to transform it
- To play an stop a movie clip instance called "movie_books"
movie_books.stop();
movie_books.play();
Making objects visible/invisible, works with any display object but you should work with an object that you can name, i.e. a symbol instance.
- If you have an object called cat:
cat.visible = true;
cat.visible = false;
Moving position of an object, works with any display object
- If you have an object called cat you can set both its x and y position. x starts from the left and y means "down". Therefore, x=0 y=0 means the upper left corner of the stage.
Example - position cat at x is 100 and y is 200 pixels:
cat.x = 100; cat.y = 200;
Example - add 50 px to cat's current position
cat.x += 50; cat.y += 50;
Resize an object, works with any display object
- If you have an object called cat:
Example, cat will be 100 px wide and 120px tall
cat.width = 100;
cat.height = 120;
Example, cat will double its size. Expression below means, set cat.width to old cat.width times 2.
cat.width = cat.width * 2;
cat.height = cat.height * 2;
Dragging an object, works with any interactive object
- If you have an object called cat, you can start/stop dragging. Usually these are bound to MOUSE_DOWN and MOUSE_UP.
cat.startDrag();
cat.stopDrag();
Moving around in the timeline. You can either go to a frame and play it (until it encounters a stop) or go there and stop.
If you want to go to frame 12 of the same scene:
gotoAndPlay(12);
gotoAndStop(12);
If you want to go to frame 13 of a scene called "test":
gotoAndPlay(13,"test");
gotoAndStop(13,"test");
Tweening and interactivity self-revision examples
Examples from an exam (to be improved and documented at some point)
2007 Exam
- Frame 1 (home): Buttons should not lead you to frame 1 (home), but to the various other keyframes. Also add your name.
- Frame 2 (Sailing): (a) Play the tween animation of boat with the 'what's going on here' button. (b) BONUS Point: Create and play a motion animation of a plane.
- Frame 3 (Driving): (a) Create an animation that will start moving the car from right to left and slightly forward too (i.e. keep it on the road). To animate the car edit the 'old car' symbol and make it a motion tween. Then link it to the what's going on here button (b) BONUS Point: Do something with the yellow car.
- Frame 4 (Island): (a) Make the trees visible when the user clicks on the what's going on button. (b) BONUS point: Improve the frame-by-frame animation of the big tree.
- Frame 5 (Rocket): (a) Write code that will launch the rocket. (b) BONUS: Do something with the snakes
Tip: For starters, you can navigate with the little button on top right. Do not edit layer one !
- final-exam-coap2110-solution-2007.html (look at the solution first)
- Source exam file: final-exam-coap2110-2007.fla (download this and try reproduce the solution)
- Source solution: final-exam-coap2110-solution-2007.fla (if you are stuck)
- Directory: http://tecfa.unige.ch/guides/flash/ex/exams2007/
2008 Exam
- final-coap2110-2008-SOLUTION.html Look at the solution first
- Read the exam tasks (PDF file)
- Source exam file: final-coap2110-2008.fla (download this and try to "do the exam" according to instructions)
- Source solution: final-coap2110-2008-SOLUTION.fla (if you are stuck)
Links
Important manual pages
The Actionscript manual at Adobe is almost impossible to understand for non programmers, but other than that, the ActionScript documentation at Adobe is excellent. Beginners can at least figure out property names and some easy to use methods...
- InteractiveObject. This InteractiveObject class is the abstract base class for all display objects with which the user can interact, using the mouse and keyboard. Most Events are documented here. (Make sure to list also the inherited events).
- Movie clip (this subclass adds properties and methods for timeline scripting)
- DisplayObject. Describes the display object, e.g. properties you can change. Note that there are additional properties for each specific kind of object, i.e. see the class hierarchy described in the Flash ActionScript 3 Overview.
Clip Art
- Free Clip Art. Original cat and dog
- Open Clip Art Library. The grey mouse and the original rocket.