ActionScript 3 interactive objects tutorial (CS3): Difference between revisions

The educational technology and digital learning wiki
Jump to navigation Jump to search
Line 584: Line 584:


Here is a short summary of mouse events that can be intercepted by a registered
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
event handler for a given object. So these events are only useful if you define
both an event handler function and if you register it with an object like in the following example:
both an event handler function and if you register it with an object like in the following example. "cat" is an interactive object, e.g. a movie clip symbol
<pre>
<pre>
  cat.addEventListener(MouseEvent.MOUSE_DOWN, resizeCat);
  cat.addEventListener(MouseEvent.MOUSE_DOWN, resizeCat);
Line 600: Line 600:
<tr><td>MouseEvent.MOUSE_WHEEL</td><td>User turns mouse wheel</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</td></tr>
<tr><td>MouseEvent.MOUSE_OVER</td><td>User moves mouse</td></tr>
<tr><td>MouseEvent.CLICK</td><td></td>User clicks</tr>
<tr><td>MouseEvent.CLICK</td><td>User clicks</td></tr>
</table>
</table>


Line 623: Line 623:


'''Moving position of an object''', works with any display object
'''Moving position of an object''', works with any display object
* If you have an object called ''cat'' you can set both x and y position. x startsfrom the left and y means "down".
* If you have an object called ''cat'' you can set both x and y position. x starts from the left and y means "down".
Exemple, put cat at x=100 and y=200 pixels:
Exemple, put cat at x=100 and y=200 pixels:
  cat.x = 100; cat.y = 200;
  cat.x = 100; cat.y = 200;
Line 642: Line 642:
  cat.startDrag();
  cat.startDrag();
  cat.stopDrag();
  cat.stopDrag();
'''Moving around in the timeline'''
If you want to go to frame 12, either play it or stop there.
gotoAndPlay(12);
gotoAndStop(12);


== Links ==
== Links ==

Revision as of 12:41, 9 October 2007

Overview

This is part of the flash tutorials.

Learning goals
Learn about how to use mouse and keypress events.
Learn about some object properties you can easily change with a little ActionScript code

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. learn how to change properties of objects (such as position, size and visibility) and how to play embedded movie clips.

Prerequisites
Flash CS3 desktop tutorial
Flash drawing tutorial
Flash button tutorial
Flash components 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 article has a list of other tutorials.
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...
Level
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. Note: I skipped type declarations on purpose. These don't make sense for a few lines of code written by/for non-programmers. I tried to keep the code as simple as possible.
Learning materials

Grab the various *.fla files from here:

http://tecfa.unige.ch/guides/flash/ex/action-script-3-intro/

Manipulation of movie clips

Movie clips are Flash animations. In a fla file you can have several kinds of embedded movie clips behaving in a similar way.

  • Movie symbols (and instances)
  • Movie clips (and instances) that were imported as *.swf files
  • Compiled movie clips imported through the *.swc format

The goal of having such embedded animations is to create animation with "moving/changing" objects. You may have a look at early Flash frame-by-frame animation tutorial, i.e. the little rocket we made and then use in motion animations as explained in the Flash motion tweening tutorial. The new thing is that you should learn how to play/stop and make visible/invisible these clips.

Note: Your whole *.fla also is a movie clip that you could import to other Flash animation.

Creation of an embedded movie clip

To create a new movie clip within a flash animation do the following:

  • Menu Insert->New Symbol
  • Select Movie Clip and give a good name
  • To edit, double click on the icon of this clip in your library.

Alternatively you also can

  • Draw an object on the stage
  • right-click->Create Movie Symbol. Select Movie Clip

You can edit either by clicking on the item in the library or an instance on the stage. If you click on the instance on the stage you will edit the symbol, but you can see it in its context.

Defining its reference point:

  • Each object has a center. You can define it when you create the new movie symbol (see screen capture below):
Create a movie clip symbol - set the registration point to center

You can later change this reference point by moving the drawing in symbol edit mode. The registration point is defined by the little cross (+ sign).

Editing a movie clip

  • Double click on the symbol's icon (not it's name) in the library. You now can edit, e.g. a add a motion animation or change its drawing
  • If you double-click on an instance, you can edit the same symbol, but you will see the objects of the stage while you edit.
  • Do not forget to go back to the scene at some point ....

Using a movie clip

See also the [[Flash_video_component_tutorial#Working_with_cue_points Flash video component tutorial] for an example.

If there is no instance of the on the stage, drag it there, then give it an instance name !

Let's assume that the instance name is movie_books.

Playing a movie clip
movie_books.play();
Stopping a movie clip
movie_books.stop();
Making it visible or invisible
movie_books.visible=false;
movie_books.visible=true;

Tip: Movie clips start playing as soon as they are found in the current frame. E.g. if you put them in frame one, they will play (forever until the main timeline moves to another frame). If this is not desired, stop the movie as you may recall from other tutorials.

  • Edit the movie clip (double click)
  • Add a layer called "script"
  • Add
stop();

Manipulating objects

The principle of (simple) object manipulation is fairly simple: change the property of an object. The tricky thing is to know what you can can change on an object. Typically, most objects are non-editable (it's component objects maybe) so the easy thing is to change size and position, i.e. operations you can do with the transform tool.

Below we show a few little examples that show how to manipulate objects with mouse events (see the ActionScript 3 event handling tutorial). You could imagine dozens of other simple examples. All the objects on the state (e.g. black_cat) are instances of movie clip symbols. These are a kind of interactive objects and react to mouse and keyboard events.

Simple repositioning example

When you click on an interactive object (a symbol instance that is called "black_cat") it will move the object to position x= 200 and y=200. Note: Position is defined by the center of the object (i.e. the little "+" sign and that depends on how you made the object).

black_cat.addEventListener(MouseEvent.CLICK, moveCat);

function moveCat(event:MouseEvent):void {
 black_cat.x = 200;
 black_cat.y = 200;
}

If you want to move the cat forth an back you'd rather use this:

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

A "flag" variable will register if the cat is in a new or the old position. If it's in the new one will move it back and the other way round. So

black_cat_ori_pas == true

tests if the cat is in its original position.

X and Y positions are defined with respect to the upper left corner. E.g. x==100 and y==100 means that the registered center point of the object is 100 pixels to the left and 100 pixels down. The instruction:

x += 100

means "add 100 to x".

Change size

When you click on an 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, then move the mouse out (still holding down), then release, 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. 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. See a better solution in the example below.

Visibility

This will make the 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;
  // should add a mouse to toggle it back.
  white_
cat.visible = false;
}

Once the cat is hidden, you never will be able to bring it back. Therefore, in the example we 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 white_cat.visible = false; we just switch it to the opposite
	white_cat.visible = !white_cat.visible;
	brown_dog.visible =!brown_dog.visible;
}

white_cat.visible = !white_cat.visible;

means that the "visible" property will be set to its opposite. E.g. if it 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

This will let you drag the red cat object.

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 Flash drag and drop tutorial that demonstrate how to implement a simple children's educational game.

Transformations

Transformation of a non-editable display object are more tricky.

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 do transformations to temporary ColorTransform object and then copy (if I understood the manual right). See the full example below.

Example file

File with a few examples is here:

  • Directory with files actionscript3-simple-object-manipulation.*:
http://tecfa.unige.ch/guides/flash/ex/action-script-3-intro/
Demonstration of some mouse events and implementation of property changes

Here is the complete code:

/* ---- 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;
}

Dealing with keypress events

Flash lets you intercept key presses in the same way as you can intercept and deal with mouse clicks. There are some subtle differences though.

Simple moving an object with arrow key 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;
		case Keyboard.DOWN :
			target.y += big_step;
			break;
	}
}

This example will not work in a webbrowser, 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:

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 I found that I had to add some extra code which is below.


/* ActionScript for timeline scripting
   Shows how to move around a flash movie with keypresses 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;
	}
}
Moving a Missile with key presses

Example code:

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. Moving would be much smoother but then you'd also have to slow it down ...

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 actionscript tricks

Here is a short list of events and actionscript tricks that might be useful for starters.

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 if you register it with an object like in the following example. "cat" is an interactive object, e.g. a movie clip symbol

 cat.addEventListener(MouseEvent.MOUSE_DOWN, resizeCat);

 function resizeCat(event:MouseEvent) {
    cat.width =  blue_cat.width * 2;
 }
MouseEvent.MOUSE_DOWNUser holds mouse button down
MouseEvent.MOUSE_UPUser releases mouse button
MouseEvent.MOUSE_OUTUser moves mouse away
MouseEvent.MOUSE_WHEELUser turns mouse wheel
MouseEvent.MOUSE_OVERUser moves mouse
MouseEvent.CLICKUser clicks

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 x and y position. x starts from the left and y means "down".

Exemple, put cat at x=100 and y=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 dipslay 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 If you want to go to frame 12, either play it or stop there.

gotoAndPlay(12);
gotoAndStop(12);

Links

Important manual pages

These are almost impossible to understand for non programmers, but otherwise the documentation at Adobe is excellent.

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

Clip Art