View
215
Download
0
Tags:
Embed Size (px)
Citation preview
SM1205 Interactivity
Topic 04: Properties and Events
Spring 2010 SCM-CityU 1
Today’s Example
• Pingpong-like game
Spring 2010 SCM-CityU 2
Review: Functions
• Example: math function f(x, y) = x2+y2
Spring 2010 SCM-CityU 3
trace(f(1, 2)); trace(f(2, 3)); trace(f(3, 4));trace(f(4, 5));
function f(x:Number, y:Number): Number {return x*x + y*y;
}
trace(f(1, 2)); trace(f(2, 3)); trace(f(3, 4));trace(f(4, 5));
function f(x:Number, y:Number): Number {return x*x + y*y;
} function definition function definition
function calls function calls
Review: Functions
• Position of function definition doesn’t influence program flow
Spring 2010 SCM-CityU 4
trace(f(1, 2)); trace(f(2, 3)); trace(f(3, 4));trace(f(4, 5));
function f(x:Number, y:Number): Number {return x*x + y*y;
}
trace(f(1, 2)); trace(f(2, 3)); trace(f(3, 4));trace(f(4, 5));
function f(x:Number, y:Number): Number {return x*x + y*y;
}
function f(x:Number, y:Number): Number {return x*x + y*y;
}
trace(f(1, 2)); trace(f(2, 3)); trace(f(3, 4));trace(f(4, 5));
function f(x:Number, y:Number): Number {return x*x + y*y;
}
trace(f(1, 2)); trace(f(2, 3)); trace(f(3, 4));trace(f(4, 5));
trace(f(1, 2)); trace(f(2, 3));
function f(x:Number, y:Number): Number {return x*x + y*y;
}
trace(f(3, 4));trace(f(4, 5));
trace(f(1, 2)); trace(f(2, 3));
function f(x:Number, y:Number): Number {return x*x + y*y;
}
trace(f(3, 4));trace(f(4, 5));
Review: Statements and Blocks
• Simple statements are expressions followed by a semicolon (;)
Spring 2010 SCM-CityU 5
// the following code contains four simple statements var a:int = 3;trace(a); a += 5; trace(a);
// the following code contains four simple statements var a:int = 3;trace(a); a += 5; trace(a);
Review: Statements and Blocks
• Braces { and } group multiple simple statements into a compound statement or block– { and } must be matched – Indentation highly recommended– Blocks can be nested
Spring 2010 SCM-CityU 6
function genderTest(male:Boolean): void {if (male) {
trace("male");trace("playing games");
} else {trace("female");trace("going shopping");
}}genderTest(false);
function genderTest(male:Boolean): void {if (male) {
trace("male");trace("playing games");
} else {trace("female");trace("going shopping");
}}genderTest(false);
Question 1: How many blocks?
Question 2: Output?
Review: Indent Style
Spring 2010 SCM-CityU 7
var a:Boolean = true; var b:Boolean = false;if (a) {if (b) {trace(10);}trace(5);} else {trace(20);}
var a:Boolean = true; var b:Boolean = false;if (a) {if (b) {trace(10);}trace(5);} else {trace(20);}
Auto Format
var a:Boolean = true; var b:Boolean = false;if (a) {
if (b) {trace(10);
}trace(5);
} else {trace(20);
}
var a:Boolean = true; var b:Boolean = false;if (a) {
if (b) {trace(10);
}trace(5);
} else {trace(20);
}
Review: Indent Style
• Indentation reveals program structure easily
Spring 2010 SCM-CityU 8
var a:Boolean = true; var b:Boolean = false;if (a) {if (b) {trace(10);} else {trace(20);}trace(5);}
var a:Boolean = true; var b:Boolean = false;if (a) {if (b) {trace(10);} else {trace(20);}trace(5);}
var a:Boolean = true; var b:Boolean = false;if (a) {
if (b) {trace(10);
} else {trace(20);
}trace(5);
}
var a:Boolean = true; var b:Boolean = false;if (a) {
if (b) {trace(10);
} else {trace(20);
}trace(5);
}
Properties
• Symbol instances provide a lot of properties for manipulation, e.g., – x, y – width, height – scaleX, scaleY– alpha– visible
• Access properties using dot syntax – E.g., ball.rotation += 30;
Spring 2010 SCM-CityU 9
Properties
• Why bother property changing in ActionScript? – To support interactivity!
• But you can use properties panel to set initial properties
Spring 2010 SCM-CityU 10
Properties: x, y
• Using dot syntax • Units: pixels
Spring 2010 SCM-CityU 11
OX
Y
Properties: width, height
Spring 2010 SCM-CityU 12
OX
Y
box.width
box.
heig
ht
Properties: scaleX, scaleY
• Multiplies current width/height by a scale factor
Spring 2010 SCM-CityU 13
OX
Y
box.scaleX = 0.5;box.scaleY = 0.5;
Properties: rotation
• Clockwise; angle in degree
Spring 2010 SCM-CityU 14
OX
Y
Properties: alpha
• Range: [0, 1]
Spring 2010 SCM-CityU 15
box.alpha = 1; box.alpha = 0.5;
Class Exercise • Create a symbol instance similar to the one below and
change its properties in ActionScript – Fill shape with gradient color using Paint Bucket Tool
Spring 2010 SCM-CityU 16
Instance name: ball
Events & Listeners• Multiple parties might be
interested in special things, called events (e.g., clicking), happened to a target object (e.g., a button)
Spring 2010 SCM-CityU 17
Hi folks, I have been
clicked!
Hi folks, I have been
clicked!
Spring 2010 SCM-CityU 18
Hi folks, I have been
clicked!
Hi folks, I have been
clicked!
Got it. I will perform some follow-up taskGot it. I will perform some follow-up task
Who cares! I’m only interested in keyboard
events on you
Who cares! I’m only interested in keyboard
events on you
Events & Listeners
• In ActionScript,
eventTarget.addEventListener (EventType, eventListener);
– btn.addEventListener(MouseEvent.CLICK, clickTask); – btn.addEventListener(KeyboardEvent.KEY_DOWN, keyDownTask);
Spring 2010 SCM-CityU 19
Hi folks, I have been
clicked!
Hi folks, I have been
clicked!
Got it. I will perform some follow-up taskGot it. I will perform some follow-up task
Who cares. I’m only interested in keyboard
events on you
Who cares. I’m only interested in keyboard
events on you
• eventTarget can be – Any symbol instance you create, e.g., a button!– Stage, timer (to be covered soon),
Spring 2010 SCM-CityU 20
btn_prev.addEventListener(MouseEvent.CLICK, onPrevButtonClick);
function onPrevButtonClick(e:MouseEvent) : void {prevFrame();txt_index.text = currentFrame + "/" + totalFrames;
}
btn_prev.addEventListener(MouseEvent.CLICK, onPrevButtonClick);
function onPrevButtonClick(e:MouseEvent) : void {prevFrame();txt_index.text = currentFrame + "/" + totalFrames;
}
eventTarget.addEventListener (EventType, eventListener);
• Listen to an event type you only care! • There are many event types defined in Event,
TimerEvent, KeyboardEvent, MouseEvent, … – E.g., MouseEvent.CLICK
Spring 2010 SCM-CityU 21
btn_prev.addEventListener(MouseEvent.CLICK, onPrevButtonClick);
function onPrevButtonClick(e:MouseEvent) : void {prevFrame();txt_index.text = currentFrame + "/" + totalFrames;
}
btn_prev.addEventListener(MouseEvent.CLICK, onPrevButtonClick);
function onPrevButtonClick(e:MouseEvent) : void {prevFrame();txt_index.text = currentFrame + "/" + totalFrames;
}
eventTarget.addEventListener (EventType, eventListener);
• eventListener is simply a function but always with a single special parameter – Though this parameter you can get the context
where the event happens
Spring 2010 SCM-CityU 22
btn_prev.addEventListener(MouseEvent.CLICK, onPrevButtonClick);
function onPrevButtonClick(e:MouseEvent) : void {prevFrame();txt_index.text = currentFrame + "/" + totalFrames;
}
btn_prev.addEventListener(MouseEvent.CLICK, onPrevButtonClick);
function onPrevButtonClick(e:MouseEvent) : void {prevFrame();txt_index.text = currentFrame + "/" + totalFrames;
}
eventTarget.addEventListener (EventType, eventListener);
Execution Flow• When an event happens to a target, all registered
listeners that are listening to this event type are invoked
• E.g., when click event happens to btn – clickTask function will be called – But keyDownTask function won’t
Spring 2010 SCM-CityU 23
btn.addEventListener(MouseEvent.CLICK, clickTask);
btn.addEventListener(KeyboardEvent.KEY_DOWN,
keyDownTask);
btn.addEventListener(MouseEvent.CLICK, clickTask);
btn.addEventListener(KeyboardEvent.KEY_DOWN,
keyDownTask);
Timer Event
• Timer is a complex data type in ActionScript – Useful for create animation, since it can dispatch
some timer event for every short period
Spring 2010 SCM-CityU 24
I will give you a TimerEvent for every second.
I will give you a TimerEvent for every second.
Great. I will update the ball position for every second.Great. I will update the ball position for every second.
Timer Event
• For complex data types, variable definition is a bit different– var varName:ComplexType
= new ComplexType(para1,…,para2);
– E.g. var timer:Timer = new Timer(20);• First parameter specifies how often a timer event should
happen • In milliseconds (0.02 second for the above example)
Spring 2010 SCM-CityU 25
Timer Event
• Timer instance will not start to invoke events until you call its start method– Timer is a complex data type, so it can have some
functions associated with it – Those associated functions are called methods
Spring 2010 SCM-CityU 26
var timer:Timer = new Timer(20); // for 0.02 second
timer.start();var timer:Timer = new Timer(20); // for 0.02 second
timer.start();
Timer Event
• Now it’s time to add an event listener for handling timer event – We listen to only event type: TimerEvent.TIMER
Spring 2010 SCM-CityU 27
var timer:Timer = new Timer(20); // for 0.02 second timer.start();
timer.addEventListener(TimerEvent.TIMER, onTimer);function onTimer(evt:TimerEvent):void {
ball.rotation += 5;}
var timer:Timer = new Timer(20); // for 0.02 second timer.start();
timer.addEventListener(TimerEvent.TIMER, onTimer);function onTimer(evt:TimerEvent):void {
ball.rotation += 5;}
Let’s Make Ball Moving
Spring 2010 SCM-CityU 28
OX
Y
ball.x += ball_speed_x;ball.y += ball_speed_y;
Bouncing Against Boundary
Spring 2010 SCM-CityU 29
OX
Y
How ?
Bouncing Against Boundary
• If ball.y is too large (i.e., > stage.stageHeight)– Set ball.y = stage.stageHeight;– And set ball_speed_y *= -1; // moving along negative y axis
• Class Exercise
Spring 2010 SCM-CityU 30
OX
Y
y = stage.stageHeight
...if (conditionA) {
// process B}...
...if (conditionA) {
// process B}...
x = stage.stageWidth
+y -y
OX
Y
Bouncing Against Boundary
• Since ball has its radius (i.e., r = ball.width / 2), it should bounce at
y = stage.stageHeight - r; // for bottom border
• Class Exercise– Update and fix
Spring 2010 SCM-CityU 31
y = stage.stageHeight - r
Bouncing Against Catcher
• Next step: add user interaction – User controls a horizontal bar, called catcher
Spring 2010 SCM-CityU 32Instance name: catcher
Keyboard Event
• Making the catcher move horizontally by pressing left or right key– stage is a variable you can always access
Spring 2010 SCM-CityU 33
stage
Hi buddy, some key has been
pressed
Hi buddy, some key has been
pressed
OK. Let me check if left or right key has been pressedOK. Let me check if left or right key has been pressed
Keyboard Event
• KeyboardEvent provides event types for key down or up
• The info that be passed from stage to listener includes the key being pressed (keyCode)
Spring 2010 SCM-CityU 34
stage.addEventListener(KeyboardEvent.KEY_DOWN, onBarControl);
function onBarControl(e:KeyboardEvent):void {
if (e.keyCode==Keyboard.LEFT) {trace("Left key pressed");
}}
stage.addEventListener(KeyboardEvent.KEY_DOWN, onBarControl);
function onBarControl(e:KeyboardEvent):void {
if (e.keyCode==Keyboard.LEFT) {trace("Left key pressed");
}}
Class Exercise
• Change x property of catcher when left or right key is pressed– catcher.x -= catcher_speed; // for left key– catcher.x += catcher_speed; // for right key
• Catcher movement should stop if it hits the stage border – cather.x < catcher.width / 2; // for left border
Spring 2010 SCM-CityU 35
When Ball Hits Catcher
• This is true only if– ball.y > catcher.y – r AND – ball.x > catcher.x – catcher.width / 2 AND– ball.x < catcher.x + catcher.width / 2
• Class Exercise – Add code in onTimer
Spring 2010 SCM-CityU 36
Game Over
• When catcher fails to get the ball, the game is over– I.e., ball.y > stage.stageHeight – r is true
Spring 2010 SCM-CityU 37
Game Over
• Idea: if game over is detected, go to the second key frame
• Let’s insert a key frame first
• Test movie!
Spring 2010 SCM-CityU 38
Errors
• You will get errors: – TypeError: Error #1009: Cannot access a property or
method of a null object reference.• at PingPong_Try4_fla::MainTimeline/onTimer()• at flash.utils::Timer/_timerDispatch()• at flash.utils::Timer/tick()
• Why?
Spring 2010 SCM-CityU 39
Remove Event Listeners
• Try to add the following code at the beginning of AS code for Frame 1
• Does it help? Unfortunately, no• Because at Frame 2, event listeners at Frame 1
will still keep running – But all symbol instances at Frame 1 become invalid
at Frame 2Spring 2010 SCM-CityU 40
stop(); // stop movieclip animation gotoAndStop(2); // go to second framestop(); // stop movieclip animation gotoAndStop(2); // go to second frame
Remove Event Listeners • We need to remove unused event listeners at Frame 1
before jump to Frame 2• Removing event listeners is very simple. Just replace
addEventListener with removeEventListener
Spring 2010 SCM-CityU 41
timer.removeEventListener(TimerEvent.TIMER, onTimer);
stage.removeEventListener(KeyboardEvent.KEY_DOWN,
onBarControl);
timer.removeEventListener(TimerEvent.TIMER, onTimer);
stage.removeEventListener(KeyboardEvent.KEY_DOWN,
onBarControl);
Remove Event Listeners
• One remaining issue
Spring 2010 SCM-CityU 42
function onTimer(evt:TimerEvent):void {...
if (ball.y > stage.stageHeight-r) {trace("game over");timer.removeEventListener(TimerEvent.TIMER, onTimer);stage.removeEventListener(KeyboardEvent.KEY_DOWN, onBarControl);gotoAndStop(2);
}
// Remaining code possibly accesses symbol instances // However, those instances cannot be accessed at frame 2...
}
function onTimer(evt:TimerEvent):void {...
if (ball.y > stage.stageHeight-r) {trace("game over");timer.removeEventListener(TimerEvent.TIMER, onTimer);stage.removeEventListener(KeyboardEvent.KEY_DOWN, onBarControl);gotoAndStop(2);
}
// Remaining code possibly accesses symbol instances // However, those instances cannot be accessed at frame 2...
}
Function Return
Spring 2010 SCM-CityU 43
function onTimer(evt:TimerEvent):void {...
if (ball.y > stage.stageHeight-r) {trace("game over");timer.removeEventListener(TimerEvent.TIMER, onTimer);stage.removeEventListener(KeyboardEvent.KEY_DOWN, onBarControl);gotoAndStop(2);
return; // directly exit the function }
// Remaining code possibly accesses symbol instances // However, those instances cannot be accessed at frame 2...
}
function onTimer(evt:TimerEvent):void {...
if (ball.y > stage.stageHeight-r) {trace("game over");timer.removeEventListener(TimerEvent.TIMER, onTimer);stage.removeEventListener(KeyboardEvent.KEY_DOWN, onBarControl);gotoAndStop(2);
return; // directly exit the function }
// Remaining code possibly accesses symbol instances // However, those instances cannot be accessed at frame 2...
}
Function Return
• After calling “return”, it would directly exit the function and – Set the output as the returned value or void
Spring 2010 SCM-CityU 44
function returnTest(): void {return; trace("this line will never execute");
}
function returnTest2(): int {return 1; // set output = 1 and exit function return 2;
}
returnTest();trace(returnTest2());
function returnTest(): void {return; trace("this line will never execute");
}
function returnTest2(): int {return 1; // set output = 1 and exit function return 2;
}
returnTest();trace(returnTest2());
Class Exercise
• Add some AS code at Frame 2 such that pressing any key will restart the game– I.e.g, go back to frame 1
• Hints:– Add an event listener to check if there is any key
down event for stage • Similar to what we did at Frame 1
– gotoAndStop(1);
Spring 2010 SCM-CityU 45
Assignment 1
• Submission – Via ACS – Deadline: 23:59:59, Tuesday, 23 Feb, 2010
• No late submission is allowed
• In-class presentation, 24 Feb– Each student has roughly 5 minutes for presentation
• Assessment – Based on implementation difficulty + creativity +
presentation performance
Spring 2010 SCM-CityU 46
Assignment 1
• Topic: any interactive system – E.g., nonlinear storytelling
• More than one possible plotline and ending
– E.g., a small interesting game
Spring 2010 SCM-CityU 47
Assignment 1
• Topic: any interactive system – E.g., nonlinear storytelling
• More than one possible plotline and ending
– E.g., a small interesting game
Spring 2010 SCM-CityU 48
Start End 1
End 2
Assignment 1
• Requirements– Technical
• Jumping between key frames with user interaction– Reference: album demo
• Having at least three event listeners – No requirement for event types
• Use multiple else-if statements– Conditions must be related to user input
– Content • Your system must be meaningful
– Not just simply a piece of code to satisfy technical requirements
Spring 2010 SCM-CityU 49
if (...) {} else if (...) {} else if (...) {} else {}
if (...) {} else if (...) {} else if (...) {} else {}
Assignment 1
• Optional tasks– Write and use your own functions
• With or without parameters • With or without returning values
– Nested if statements
Spring 2010 SCM-CityU 50