Вы находитесь на странице: 1из 20

By Blue_Chi | Flash CS5 | ActionScript 3.0 | Beginner

Using the Geolocation Sensor in Flash Using AS3

This tutorial will teach you how to use the Geolocation Sensor in a Flash movie your mobile device to retrieve the geographical position of the user. This feature is only compatible with Flash Lite 4, Adobe AIR Mobile, and the iPhone. The most basic function of geolocation is to retrieve the latitude and longitude positions of the user, so that you can locate the user on a map. The sensor could also be used to retrieve additional details such as the speed at which the user is moving. This is a beginner AS3 tutorial that will only require you to know the basics of AS3 Variables and Event Handling.

Starting Off

This tutorial can be followed as a Flash Lite 4 project, an Adobe AIR project, and an iPhone project. We are going to create a Flash Lite 4 project because it is easier to test the device in Device Central using this format as AIR Mobile and iPhone applications cannot be tested in Device Central at the time of writing this tutorial. Our tutorial will simply retrieve the geolocation data and display them on the screen inside a text field.

Start up Flash CS5 and go through

do not need any graphical elements on the screen as we can create our text field by using AS3

later. Just right-click the only frame you have on the timeline and select

the

We are going to begin our code, the first step is importing the classes needed to use the geolocation sensor - the Geolocation Class and the GeolocationEvent Class:

import flash.sensors.Geolocation; import flash.events.GeolocationEvent;

New>Flash Lite 4

to create a new Flash Lite 4 movie. We

Actions
Actions

to open up

Actions Panel

.

We can now use geolocation capabilities in our project, but before we do that we need to detect whether the device that will run the movie supports geolocation - as you should not not all mobile phones have GPS features. It is necessary to make sure that you can have an alternative option or a warning message if the user's device doesn't support geolocation or if the user has disabled geolocation access to your application. We can check for geolocation support

by using the

import flash.sensors.Geolocation; import flash.events.GeolocationEvent;

isSupported()

method of the Geolocation Class:

if (Geolocation.isSupported){

}

You can learn more about the AS3

if
if

Conditional by reviewing our tutorial on this topic.

The method above will return the value

we put between the curly brackets of the conditional will only then be executed. Our first action to carry out once we have verified that geolocation is support is to create an instance of our geolocation class. In order to use any ActionScript Class we have to create an instance of it and then play around with that instance of the class. To create an instance of the

class we use the

true
true

if geolocation is supported and therefore whatever

new
new

keyword. We are going to call our instance

my_geo :
my_geo
:

import flash.sensors.Geolocation; import flash.events.GeolocationEvent;

if (Geolocation.isSupported){

var my_geo:Geolocation = new Geolocation();

}

You can learn more about AS3 Variables and Classes by reviewing our tutorial on this topic.

The geolocation class sends updates on the status of the location repeatedly, we have to register the geolocation update event and retrieve the data we need from an event listener function that we will have that as its specific task. import flash.sensors.Geolocation; import flash.events.GeolocationEvent;

if (Geolocation.isSupported){

var my_geo:Geolocation = new Geolocation(); my_geo.addEventListener(GeolocationEvent.UPDATE, onGeoUpdate);

}

You can learn more about AS3 Event Handling by reviewing our tutorial on this topic.

We now need to create a text field which will display our location coordinates. We can do that easily by using the TextField Class, once created we will make the textfield wrap the text properly in case the longitude values are long and then display the empty text field on the

screen by using the Display List method

import flash.sensors.Geolocation; import flash.events.GeolocationEvent;

DisplayChild()

:

if (Geolocation.isSupported){

var my_geo:Geolocation = new Geolocation(); my_geo.addEventListener(GeolocationEvent.UPDATE, onGeoUpdate);

var my_txt:TextField = new TextField(); my_txt.wordWrap=true; addChild(my_txt);

}

You can learn more about AS3 TextField Class and AS3 Display List by reviewing our tutorials on these topics.

It is now time to create the function that will retrieve our geolocation details. We can define this function outside the conditional as it will only be triggered if called by the event listener. The

function will set the value of the text field by using the

the

import flash.sensors.Geolocation; import flash.events.GeolocationEvent;

latitude
latitude

and

longitude
longitude

properties of

GeolocationEvent

instance:

if (Geolocation.isSupported){

var my_geo:Geolocation = new Geolocation(); my_geo.addEventListener(GeolocationEvent.UPDATE, onGeoUpdate);

var my_txt:TextField = new TextField(); my_txt.wordWrap=true; addChild(my_txt);

}

function onGeoUpdate(e:GeolocationEvent):void{

my_txt.text = "My Latitude is "+e.latitude+" and my Longitude is "+e.longitude;

}

We are set, this is everything you need to use the Geolocation Sensor on your mobile device,

you can test your movie by going through

Device Central and play your movie, you might have to set the Test Device in Device Central so that you are using a Flash Lite 4 device:

Control>Test>In Device Central

. This should launch

Control>Test>In Device Central . This should launch Now you access the Geolocation Panel on the right-side

Now you access the Geolocation Panel on the right-side of the window (or by going

through

values for the

value here and then click on appear inside the emulator.

Window>Flash>Geolocation

latitude

and

longitude

if you can't see it). Inside this panel you can manually put which you want your mobile to emulate. You can put any

. Once you do that you should see your values

Send to Device

Our use is obviously basic, but it shows you how to retrieve the location data.

Our use is obviously basic, but it shows you how to retrieve the location data.

Update Frequency

In a real world application your location would change as you move around, the frequency at which Flash will be updated about changes in your location can be configured by using

the

depend on the default values of your device which vary from one device to another. This method can be used directly on an instance of the Geolocation Class and accepts a value in milliseconds this way:

import flash.sensors.Geolocation; import flash.events.GeolocationEvent;

setRequestedUpdateInterval()

method. If you do not use this method the updates will

if (Geolocation.isSupported){

var my_geo:Geolocation = new Geolocation(); my_geo.addEventListener(GeolocationEvent.UPDATE, onGeoUpdate);

my_geo.setRequestedUpdateInterval(50);

var my_txt:TextField = new TextField(); my_txt.wordWrap=true; addChild(my_txt);

}

function onGeoUpdate(e:GeolocationEvent):void{ my_txt.text = "My Latitude is "+e.latitude+" and my Longitude is "+e.longitude;

}

You should be careful about setting very short intervals for your geolocation sensor as that will rapidly consume the battery of your device. You should always unregister your event after you are done retrieving the data that you need as well.

Additional Values

In addition to the latitude and longitude values which we have used in our example above you can also retrieve the following pieces of information:

altitude heading speed verticalAccuracy
altitude
heading
speed
verticalAccuracy

The altitude value.

The angle in respect to north in which the user is heading.

The speed in meters per second.

The vertical accuracy.

horizontalAccuracy

The horizontal accuracy.

These values would only be helpful to someone creating an advanced location based application such as a navigation system. This concludes our tutorial, you can try integrating geolocation with a Google Maps application to show the location on a map. You should note however that the Google Maps application does not work in iPhone Flash Applications as it requires loading code at runtime. If you have any questions feel free to post them at the Republic of Code Forum. - End of Tutorial

By Blue_Chi | Flash CS3 | Intermediate

By Blue_Chi | Flash CS3 | Intermediate

Pages 1, 2, 3, 4, 5

By Blue_Chi | Flash CS3 | Intermediate Pages 1, 2 , 3 , 4 , 5

Creating a Flash Lite Game - Tutorial

Making rich media for mobile consumption has never been easier since the release of the Flash Lite player for mobile devices. You can make a vector graphics game that could be played on any device regardless of its operating system or screen resolution easily as long as that device is equipped with the Flash Lite player - and lets not forget that you can play that game on a PC as well without using any emulators because the file is still a Flash movie that could be played on the Flash Player. This tutorial will teach you how to create a Flash Lite game playable on the Flash Lite Player version 1.1 - one of the earliest versions and most restricted, but the most widely spread version as well. Our basic game could be created without using the advanced features provided in later versions. Adopting Flash Lite 1.1 will guarantee that the game will be compatible with the largest possible number of Flash Lite powered devices. The game we will create is a very basic arcade game, the player merely collects the objects before they reach the ground. If he fails to collect three objects then the game ends. Our game will use very simple ActionScript concepts such as variables and conditionals. You really do not need to know much else.

conditionals . You really do not need to know much else. To play the game on
conditionals . You really do not need to know much else. To play the game on

To play the game on your phone, unzip this file and send it to your phone. You can alternatively play the game on your computer if you have the standalone player installed.

What's Behind the Code?

As previously stated, our game uses very basic ActionScript concepts, as each of the objects fall, the value of their location on the _y axis increases, we run a conditional that checks if the player coincides with any of the fallen objects at the same position, if it is that is the case, the player gains an extra score point. Another conditional checks if the object reached the ground, if it does, the player loses one life. It is that easy!

Game Structure

Our game will require five frames only, they are as follows:

1. Game Start The user will see a screen that says start game, he has to press a button to start playing.

be executed once only and that is why it is separated from the rest of the code that will have to be repeatedly executed.

3. Game Execution Loop This frame will have the actual code to run the game, it will control the movement of the objects during gameplay and will continuously run throughout the game.

4. Game Loop 2 This frame has the simple task of making the previous frame loop. It does not have any other task or code.

5. Game Over The player is transferred to this screen when he consumes all his lives. This screen will show him his final score and will also give him the option to play again.

This is the basic structure for creating a game on any platform. Making a game in Flash is easier to understand because you can separate the code of each of these sections in different physical frames. We will go through them one by one, but first we will create the basic layer structure to organise the content in each of our frames.

Starting Off - Layer Structure

Create a new Flash Lite movie, you can use Adobe Device Central, or alternatively create a regular Flash file and change the ActionScript version from the Publish settings. Set the

ActionScript version to Flash Lite 1.1 , the dimensions to 240x320px and the framerate to
ActionScript version to
Flash Lite 1.1
, the dimensions to
240x320px
and the framerate
to
12fps
.
You should have one layer in your movie. Add
three extra
layers to the timeline, and rename
them to
Actions
, Buttons
, Main Content
, and
Background
. Each of these layers will host a

specific type of content as labelled.

layers will host a specific type of content as labelled. We will now create keyframes in

We will now create keyframes in each of these layers in accordance with the 5

Frames structure illustrated above. Start off with the

Create

Actions
Actions

layer.

5
5

separate

keyframes

in it.

with the 5 Frames structure illustrated above. Start off with the Create Actions layer. 5 separate

Now for the

The

and

Buttons Main Content Frame 5 .
Buttons
Main Content
Frame 5
.

layer, we need a keyframe in

Frame 1 , Frame 2 , Frame 3 , and Frame 5 . Frame 1
Frame 1
, Frame 2
,
Frame 3
, and
Frame 5
.
Frame 1
,
Frame 2
,

layer on the other hand needs a keyframe in each of

2 , layer on the other hand needs a keyframe in each of We are going

We are going to have only across all the five frames.

one keyframe

in our

Background

layer, make that frame span

one keyframe in our Background layer, make that frame span Our timeline is now ready. We

Our timeline is now ready. We will start working on each of the frames in turn:

Frame 1: Game Start - Page 2

Frame 2: Initialization - Page 3

Frames 3 and 4: Game Execution Loop and Game Loop 2 - Page 4

Frame 5: Game Over - Page 5

You are now set to start making the game, the Game Start Frame is naturally next. We will create in this section the Game Start Frame. This frame will stop the game from playing instantly and will contain the title text and the button to make the game start when the player presses the 'Enter' button. In order to follow this tutorial, you will have to download this file that contains the graphics for our game.

'Game Start' Frame

We will start working from the bottom layer going up. Starting with the background, select

the

it. If the image is not automatically aligned at the right place, you have to make sure it does by

doing that manually. Once you do that,

throughout the game so we don't have to make any changes to it.

Background

layer, then import (

File>Import>Import To Stage

lock
lock

) the

background.gif

image to

this layer. The same background will be displayed

For the main content in this frame we are going to have text that says

For the main content in this frame we are going to have text that says

the

colour, and font size you wish for this. You can also add any graphics for a logo or anything of that sort in this frame. Make sure that you have your text type set to Static (Check the Properties Inspector), if you use any other text type you will have to embed the characters before hand to make the text visible at run-time.

Start Game

. Select

Main Content

layer and then use the

Text Tool

to create such text, you can use any font,

use the Text Tool to create such text, you can use any font, Even though no

Even though no physical button will be required as the navigation is going to be through the phone keypad, Flash Lite 1 can only register key presses through a button symbol, so we will

have to create one. Select the

the stage - our button should not be seen. Now use the

then press

We will keep using an instance of this object each time we want to register keypad presses.

Buttons
Buttons

layer and use the

. Name it

Oval Tool Selection Tool MyButton .
Oval Tool
Selection Tool
MyButton
.

to draw a little circle above

to select this circle and

F8
F8

to convert it to a

Button Symbol

We will start putting some Actions now. the following code in the Actions Panel. This

We will start putting some Actions now.

the following code in the Actions Panel. This code will be assigned directly onto the button. on (keyPress "<Enter>"){ play();

Right-click

our button, select

Actions
Actions

, and then paste

}

The code is self-explanatory, if the button "Enter" is pressed, the movie will be played. Of course, the movie by default should be playing, but we do not want to it to do that, so we will

make it stop. To do this, first close the Actions panel,

select the Actions layer, then right-
select
the
Actions
layer, then
right-
click
click

the first frame and select

Actions
Actions

. Paste the following code:

stop();

Just noticed something annoying about Flash CS3, if you want to assign a script to a certain frame, you will have to do the following: (1) select the layer of that contains the frame, (2) click on a faraway empty frame in the same layer - for example, frame 10 in our case, (3) now right- click the frame that you want to assign (frame 1 in our case) and select Actions. It doesn't make sense, but that's how it works.

An essential command to set at the first frame along with the

switches the player to fullscreen mode. Add the following code below the that:

stop()
stop()

method is one that

stop()
stop()

command to do

fscommand2("fullscreen", true);

We are done with our Game Start Frame, here is a summary of what we did:

1. Added the background to the

Background layer. Main Content layer. Buttons Actions layer the code to stop()
Background
layer.
Main Content
layer.
Buttons
Actions
layer the code to
stop()

2. Added the title text to the

3. Added the button to the

4. Assigned to the

layer and assigned the

method to the button.the button to the 4. Assigned to the layer and assigned the fullscreen the movie and

fullscreen

the movie and started the

mode.

I hope that you found this section easy. We will now move to the Initialization Frame next. In this stage we will create the Game Initialization Frame, the code in this frame runs only once to create all the objects we need for the game, it also creates the starting values for variables in the game such as the game score and the number of lives the player has. We will start with the different types of content we have from the bottom up, the background is already

done from the first frame, so we will move straight into the Main Object layer.
done from the first frame, so we will move straight into the
Main Object
layer.
Creating the Player and the Target Objects
Our
Main Contents
layer will host the
Player
and the
Target
that will be caught during the

game. Assuming that you have already unzipped the file given in the previous page. Import the

included player.swf movie into your library (

the

Library ( Ctrl+L
Library
( Ctrl+L
File>Import>Import to Library

File>Import>Import to Library

File>Import>Import to Library second frame
File>Import>Import to Library second frame
second frame

second frame

). Open

) and drag an instance of your player onto the

of our

Main
Main

Contents layer

later position using ActionScript. We have to convert this graphic to a Movie Clip Symbol to do

. The location of the player object on stage does not matter because we will it

that though. So select it, and then press

as MyPlayer left corner
as
MyPlayer
left corner

, set the type to

F8 Movie Clip
F8
Movie Clip

to convert it to a Symbol. Assign the name

Registration Point

, and then change the

to the

as indicated in the image below.

and then change the to the as indicated in the image below. top Registration Point: Setting
top
top

Registration Point: Setting the registration point to the left makes it easier to position the object in our game. When you set the _x position to Zero this means that the left side of the object would be at the point Zero and not the center of the object ilke what happens with default settings. This makes things so much easier, especially as player's width equals exactly the 1/3 of the stage's width, so the three positions that it has to be at are 0, 1/3, and 2/3 of the width of the stage.

Before we forget, you have to also assign the

using the

Properties Inspector

.

instance name player_mc
instance name
player_mc

to this movie clip

Inspector . instance name player_mc to this movie clip Our game is going to have three

Our game is going to have three targets falling at the same time, we will create these three targets using ActionScript, but we need to have the source template for the target from which

we will duplicate our additional copies. You will have to import the

zip file you downloaded earlier, go through

open the library (

position this object somewhere above the stage because we do not need to see it during run

time.

symbol

to do just that, then

target.swf

file included in the

File>Import>Import to Library

Main Contents

Ctrl+L
Ctrl+L

) and drag a copy of it onto the

), set the

layer. You have to

name
name
Convert to a MyTarget
Convert
to a
MyTarget
symbol ( F8 OK
symbol
( F8
OK

. Click

registration point

to the

top left target_mc
top left
target_mc

corner,

to it.

the

and then assign the

instance name

( F8 OK . Click registration point to the top left target_mc corner, to it. the
Adding the Score and number of Lives display The player needs to see the number

Adding the Score and number of Lives display

The player needs to see the number of points he scored and how many lives he has remaining. We will do that by creating the text labels and then a couple of dynamic text fields to show the

actual numbers. Start off by using the

Text Tool

to write two texts that say

score

and

lives

,

make sure that the text type of each of these texts is

static
static

(check the

Properties Inspector

).

is static (check the Properties Inspector ). We will now create the dynamic texts that will

We will now create the dynamic texts that will actually display the numbers for each of these

variables. Make sure that no text is selected, pick the

. Now draw a text field next to score, set the font

to

the

Text Tool,

access the

Properties

Inspector

_sans

and set the text type to

, font size to

11 score
11
score
Dynamic
Dynamic

, and align the text to the

left
left

. You will now have to assign

variable name

to it to display that variable when it is created.

name to it to display that variable when it is created. Create another field next to

Create another field next to the text that says

assign the

lives
lives

, use the same properties as above and

variable name lives
variable name
lives

to it. You should end up with a screen similar to the one below.

We used the system font _sans to avoid embedding any characters as would usually be

We used the system font _sans to avoid embedding any characters as would usually be required when using a Dynamic text field.

That completes all the visual content of this frame, we will skip the

are no navigation commands in this frame. We will move to the Actions now.

ActionScript

layer because therein this frame. We will move to the Actions now. ActionScript Select the Actions layer, right-click

Select
Select

the

Actions
Actions

layer,

right-click

the

second frame

and select

. (Might need to usethe Actions layer, right-click the second frame and select the trick mentioned in the previous page

the trick mentioned in the previous page regarding Frame selection for ActionScript). Paste the code below to initialize the game assets. The code is pretty simple. The first two lines are the basic variables which we are using, the score (starts at zero) and the lives (player has three lives). we are setting the _x and _y properties of the player_mc object, and then duplicating the target_mc three times, the actual target_mc will not be used again. Each of the new targets will be set at their position horizontally, and will be placed at a random position above the screen before falling, I used a random value here to make sure that they don't all fall together making it hard for the player to catch all three objects at the same instance. //Essential Variables

score=0;

lives=3;

//Positions the player on the stage. player_mc x=0; player_mc y=280;

//Creates 3 targets by duplicating the one on stage duplicateMovieClip("target_mc","target1_mc",1);

duplicateMovieClip("target_mc","target2_mc",2);

duplicateMovieClip("target_mc","target3_mc",3);

//Positions the new targets above the stage ready to play target1_mc x=0;

target1_mc y=-random(40);

target2_mc x=80; target2_mc y=-random(40);

target3_mc x=160; target3_mc y=-random(40);

We would like our targets to fall at different speeds, so we will assign a different speed property

to each of these targets. The

have to assign it now. The initial speed will be a random number between 0 and 10. If the speed

to whatever speed

is actually zero, the targets will not move, so we will be adding the number

we get. We could have used code was changed this way:

//Essential Variables

property will be used when the game actually runs, but wehave used code was changed this way: //Essential Variables instead of 4 , but playing at

instead ofproperty will be used when the game actually runs, but we 4 , but playing at

4
4

, but playing at speed

1
1
4
4

is way too boring. The

score=0;

lives=3;

//Positions the player on the stage. player_mc x=0; player_mc y=280;

//Creates 3 targets by duplicating the one on stage duplicateMovieClip("target_mc","target1_mc",1);

duplicateMovieClip("target_mc","target2_mc",2);

duplicateMovieClip("target_mc","target3_mc",3);

//Positions the new targets above the stage ready to play target1_mc x=0; target1_mc y=-random(40);

target1_mc.speed=random(10)+4;

target2_mc x=80; target2_mc y=-random(40);

target2_mc.speed=random(10)+4;

target3_mc x=160; target3_mc y=-random(40);

target3_mc.speed=random(10)+4;

We need to create a variable to store the location of the player on the stage and to check for it at the time the objects fall, we can recall the position at run time, but checking for a number like that can be messy, to have a nicer and a more understandable code we are going to create a

property called

center), or position

myPosition 3
myPosition
3

to tell us if the player is at position

1
1

(the left), position

2
2

(the

(the right). At the start, the player is as the left (_x=0), so his position is 1.

This will make much more sense by the end of the next frame.

//Essential Variables

score=0;

lives=3;

//Positions the player on the stage. player_mc x=0;

player_mc y=280;

player_mc.myPosition=1;

//Creates 3 targets by duplicating the one on stage

duplicateMovieClip("target_mc","target1_mc",1);

duplicateMovieClip("target_mc","target2_mc",2);

duplicateMovieClip("target_mc","target3_mc",3);

//Positions the new targets above the stage ready to play target1_mc x=0; target1_mc y=-random(40);

target1_mc.speed=random(10)+4;

target2_mc x=80; target2_mc y=-random(40);

target2_mc.speed=random(10)+4;

target3_mc x=160; target3_mc y=-random(40);

target3_mc.speed=random(10)+4;

Initialization is now done. In this stage, we did the following:

1. Added the

Added the

player target score and live Actions Actions Actions Actions
player
target
score
and
live
Actions
Actions
Actions
Actions

object to the

Main Contents layer. Main Contents layer. Main Contents variables . player . target .
Main Contents
layer.
Main Contents
layer.
Main Contents
variables
.
player
.
target
.

2. Added the

3.

4. Assigned the

object to the

displays in the

layer.

to create the essential

5. Assigned the

to position the

6. Assigned the

to duplicate the

7. Assigned the

to position and configure these new targets.

Glad you have made it to this frame, the main Game Execution loop Frame is next. The Game Execution loop Frame holds the code that runs the game, controls the objects, counts the score and takes away lives when you fail to catch the object. Our frame will also configure the controls for moving the player on the screen, we will start with this last part first. We have already created and aligned all our visual objects in our previous frame so we can move straight into the stage to create the button that captures key presses and then code the game loop.

Creating the Game Controls

We need to create the button to hold the control code,

the

sure that it placed somewhere above the stage so that it is not visible during the game.

select MyButton
select
MyButton

the

Buttons
Buttons

layer, open up

library ( Ctrl+L
library
(
Ctrl+L

) and drag an instance of the

symbol we created earlier, make

Right-click this instance of the button on the stage and select . We are going

Right-click

this instance of the button on the stage and select

. We are going tothis instance of the button on the stage and select use two buttons only to control

use two buttons only to control the player, we are going to use a very simple conditional to

move the player and change the value of its currently is. on (keyPress "<Left>"){ if (player_mc.myPosition != 1){ player_mc.myPosition--; player_mc x-=80;

myPosition

variable depending on where it

}

}

on (keyPress "<Right>"){ if (player_mc.myPosition != 3){ player_mc.myPosition++; player_mc x+=80;

}

}

The code is simple, as long as the position of the player is not

the left key button moves it to the left by

not

player movie clip is exactly

(absolute left), then pressingmoves it to the left by not player movie clip is exactly pixels, and as long

pixels, and as long as the position of the player is

80 right
80
right
3
3

(absolute right), then pressing the

80 80 myPosition
80
80
myPosition

key button moves it to the right by

1/3
1/3
80
80

pixels. The

pixels in width, which is also exactly

of the width of the

stage, so moving it by

I find using the

positions when making my conditionals, although those would work the same if you use the exact values. We will also be using this variable later on below to check if the targets are caught.

Coding the Game loop

pixels to the left or the right is a whole step to the left or the right.

property easier because I do not have to think about the actual

We have to assign our biggest chunk of code to

frame and open the

as we go through. Most of our code will be duplicated three times, each for one of the targets.

Our first task is to make our objects fall down, we do that by increasing the

Frame 3
Frame 3

of the

Actions
Actions

layer. Select that

Actions
Actions

panel. We are going to do this in segments, I will explain each one

_y
_y

property of each

target, we will add to them the value of the

object has a different

//Commands the targets to move downwards.

speed
speed

property we set in the previous frame. Each

speed
speed

value, so they should be falling at different speeds.

target1_mc

y

+= target1_mc.speed;

target2_mc

y

+= target2_mc.speed;

target3_mc

y

+= target3_mc.speed;

The next task is to configure what happens when the balls reach the ground without being

caught. We know that the height of the stage is

the target has fallen down. If that is true, then the player loses a life, and then the ball is thrown

up to a random place above the stage (that's the new

a random value between zero and the current score (plus 4 to avoid zero speed). This makes the game become faster as you score more. You paste the following below the first segment:

//The targets fall down. if (target1_mc y>320){ lives--;

target1_mc

target1_mc.speed= random(score)+4;

320
320

pixels, so if the

_y
_y
_y
_y

property exceeds that

speed
speed

is set as

is negative), and the

y

=-random(40);

}

if (target2_mc y>320){

lives--;

target2_mc

y

=-random(40);

target2_mc.speed= random(score)+4;

}

if (target3_mc y>320){

lives--;

target3_mc

y

=-random(40);

target3_mc.speed= random(score)+4;

}

Now what happens if our targets are actually caught? First, each target will be caught under a

different condition, each will have to have its

the

the

the targets is satisfied, the players gains one extra score point, and then the target is thrown up at a random position with random speed to start again. //The targets are caught.

if (target1_mc score++;

target1_mc

target1_mc.speed= random(score)+4;

_y
_y

property lower than

250 , and then 1 for the absolute left , 2
250 , and then
1 for the
absolute left
, 2

has to be at the corresponding position as the target.lower than 250 , and then 1 for the absolute left , 2 object, and for

object, and, 2 has to be at the corresponding position as the target. for 3 for the

for

3
3

for the object on the

absolute right

. If the capture condition for any of

y>250

and player_mc.myPosition == 1 ){

y

=-random(40);

}

if (target2_mc

y>250

and player_mc.myPosition == 2 ){

score++;

target2_mc

y

=-random(40);

target2_mc.speed= random(score)+4;

}

if (target3_mc

y>250

and player_mc.myPosition == 3 ){

score++;

target3_mc

y

=-random(40);

target3_mc.speed= random(score)+4;

}

Our final task is to check for Game Over, if the number of lives reaches zero, then we have to remove all of our targets from the stage and then go to and stop at the Game Over Frame -

ie

//Game Over if (lives == 0){

removeMovieClip("target1_mc");

removeMovieClip("target2_mc");

removeMovieClip("target3_mc");

gotoAndStop(5);

Frame 5 .
Frame 5
.

}

We only need to remove objects we created dynamically via ActionScript as those will not be removed when you leave the frame that contains them. The player movie clip does not have to be removed because it is an actual object on the stage and it will not be visible once we leave the frame that contains it.

The loop 2 (Frame 4)

That completes our game engine, but if you noticed, this was all just one frame and to make it

loop we will add this code to the

//Plays the previous frame

gotoAndPlay(3);

Our Game loop is done, here is what we did here:

next frame , Frame 4
next frame
, Frame 4

in the

Actions
Actions

layer.

1. Added a button to the

2. Assigned the

3. Assigned the

4. Assigned the

5. Assigned the

6. Assigned the

Buttons Actions Actions Actions Actions Actions to make Frame 4
Buttons
Actions
Actions
Actions
Actions
Actions
to make
Frame 4

layer and configured the key controls.

to make the targets move.

to determine what happens when the targets reach the ground.

to determine what happens when the targets are captured.

to determine what happens when all the lives are consumed.

loop with

Frame 3
Frame 3

. (Game Execution loop).

The very last frame, Game Over Frame, is next. The player will be directed to the Game Over Frame if he loses all his lives. The Game Over screen will display the final score achieved and will give the player the option to play the game once more. This means that we will have to put some static text, dynamic text to display the score, and a button to make key commands to restart the game. We will do these from the bottom up.

Adding Text

Select the

part of the stage and then write

the image below. You will have to make sure that the type of both of these texts is

the

Main Content

layer and use the

Text Tool PLAY AGAIN?
Text Tool

Text Tool

Text Tool PLAY AGAIN?
PLAY AGAIN?

PLAY AGAIN?

to write

YOUR SCORE IS

at the upper

at the lower section of the stage as illustrated in

static
static

(check

Properties Inspector

).

Displaying the Score To display the actual score on the screen, we need to use

Displaying the Score

To display the actual score on the screen, we need to use a

that nothing on stage is selected, select the

Inspector

and assign the

Text Tool Text Type to Dynamic Text
Text Tool
Text Type
to
Dynamic Text
Dynamic Text Field

Dynamic Text Field

Dynamic Text Field Properties
Dynamic Text Field Properties
Properties

Properties

. Make sure

, and then access the

to be able to draw such a text field. Now

draw a big rectangular field between the two lines of text you have on stage. While your text

field is still selected, set the size to

the variable name

80px
80px

, the font to

_sans , center
_sans
,
center

the text, and then assign

score
score

to it.

selected, set the size to the variable name 80px , the font to _sans , center

Adding Key Controls

To register the key command for the game to be played again would require us to create a

button the same way we did for the previous commands. Select the

the

somewhere above the stage. Now right-click this button and select

Buttons
Buttons

layer, open up

Library ( Ctrl+L
Library
(
Ctrl+L

) and drag a copy of the

myButton

symbol we created previously. Put it

Actions
Actions

to open up

the

panel. Type this code to make the game play once again when pressing

the

Actions Enter
Actions
Enter

button. The code is self-explanatory. Frame

2
2

is the Intialization Frame which sets

all the variables and objects required to start the game, the game will follow from there automatically. on (keyPress "<Enter>"){

gotoAndPlay(2);

}

We are done! In this final stage you did the following:

1. Added the Game Over text to the

2. Added the

3. Added a button to the game.

Main Content layer. Main Content Buttons
Main Content
layer.
Main Content
Buttons
Score
Score

display text field to the

layer.

layer and configured the key controls to go back and play the

We are done. You can now test your movie or export it to try it on your mobile device.

your movie or export it to try it on your mobile device. The game we created
your movie or export it to try it on your mobile device. The game we created

The game we created here is a very basic one, I added a couple more features to make this game richer, you can download it to get an idea on how you expand your game.

I hope you found this tutorial helpful. Feel free to post the Oman3D Forum if you have any questions.

- End of Tutorial.