Sei sulla pagina 1di 20

Using the Geolocation Sensor in

Flash Using AS3


By Blue_Chi | Flash CS5 | ActionScript 3.0 | Beginner

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 New>Flash Lite 4 to create a new Flash Lite 4 movie. We
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 Actions to open up
the Actions Panel .
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;

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 isSupported() method of the Geolocation Class:
import flash.sensors.Geolocation;
import flash.events.GeolocationEvent;

if (Geolocation.isSupported){

You can learn more about the AS3 if Conditional by reviewing our tutorial on this topic.

The method above will return the value true if geolocation is supported and therefore whatever
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 new keyword. We are going to call our instance 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 DisplayChild() :
import flash.sensors.Geolocation;
import flash.events.GeolocationEvent;

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 latitude and longitude properties of
the GeolocationEvent instance:
import flash.sensors.Geolocation;
import flash.events.GeolocationEvent;
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 Control>Test>In Device Central . This should launch
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:

Now you access the Geolocation Panel on the right-side of the window (or by going
through Window>Flash>Geolocation if you can't see it). Inside this panel you can manually put
values for the latitude and longitude which you want your mobile to emulate. You can put any
value here and then click on Send to Device . Once you do that you should see your values
appear inside the emulator.
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 setRequestedUpdateInterval() method. If you do not use this method the updates will
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;

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 —The altitude value.
 heading —The angle in respect to north in which the user is heading.
 speed —The speed in meters per second.
 verticalAccuracy —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
Creating a Flash Lite Game -
Tutorial
By Blue_Chi | Flash CS3 | Intermediate
Pages 1, 2, 3, 4, 5

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.

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.
2. Initialization
All objects and variables required for the game will be created in this frame. This code needs to
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 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.

We will now create keyframes in each of these layers in accordance with the 5
Frames structure illustrated above. Start off with the Actions layer.
Create 5 separate keyframes in it.
Now for the Buttons layer, we need a keyframe in Frame 1 , Frame 2 , Frame 3 , and Frame 5 .
The Main Content layer on the other hand needs a keyframe in each of Frame 1 , Frame 2 ,
and Frame 5 .

We are going to have only one keyframe in our Background layer, make that frame span
across all the five frames.

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 Background layer, then import ( File>Import>Import To Stage ) the background.gif image to
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, lock this layer. The same background will be displayed
throughout the game so we don't have to make any changes to it.
For the main content in this frame we are going to have text that says Start Game . Select
the Main Content layer and then use the Text Tool to create such text, you can use any font,
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.

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 Buttons layer and use the Oval Tool to draw a little circle above
the stage - our button should not be seen. Now use the Selection Tool to select this circle and
then press F8 to convert it to a Button Symbol . Name it MyButton .
We will keep using an instance of this object each time we want to register keypad presses.
We will start putting some Actions now. Right-click our button, select Actions , and then paste
the following code in the Actions Panel. This code will be assigned directly onto the button.
on (keyPress "<Enter>"){
play();
}

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-
click the first frame and select 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 stop() method is one that
switches the player to fullscreen mode. Add the following code below the stop() command to do
that:
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.
2. Added the title text to the Main Content layer.
3. Added the button to the Buttons layer and assigned the play() method to the button.
4. Assigned to the Actions layer the code to stop() the movie and started the fullscreen 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.
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 ( File>Import>Import to Library ). Open
the Library ( Ctrl+L ) and drag an instance of your player onto the second frame of our Main
Contents layer . The location of the player object on stage does not matter because we will it
later position using ActionScript. We have to convert this graphic to a Movie Clip Symbol to do
that though. So select it, and then press F8 to convert it to a Symbol. Assign the name
as MyPlayer , set the type to Movie Clip , and then change the Registration Point to the top
left corner as indicated in the image below.

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 instance name player_mc to this movie clip
using the Properties Inspector .

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 target.swf file included in the
zip file you downloaded earlier, go through File>Import>Import to Library to do just that, then
open the library ( Ctrl+L ) and drag a copy of it onto the Main Contents layer. You have to
position this object somewhere above the stage because we do not need to see it during run
time. Convert to a symbol ( F8 ), set the registration point to the top left corner, name the
symbol MyTarget . Click OK and then assign the instance name target_mc to it.
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 (check the Properties Inspector ).

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 Text Tool, access the Properties
Inspector and set the text type to Dynamic . Now draw a text field next to score, set the font
to _sans , font size to 11 , and align the text to the left . You will now have to assign
the variable name score to it to display that variable when it is created.

Create another field next to the text that says lives , use the same properties as above and
assign the 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
required when using a Dynamic text field.

That completes all the visual content of this frame, we will skip the Button layer because there
are no navigation commands in this frame. We will move to the Actions now.
ActionScript

Select the Actions layer, right-click the second frame and select Actions . (Might need to use
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 speed property will be used when the game actually runs, but we
have to assign it now. The initial speed will be a random number between 0 and 10. If the speed
is actually zero, the targets will not move, so we will be adding the number 4 to whatever speed
we get. We could have used 1 instead of 4 , but playing at speed 1 is way too boring. The
code was changed this way:
//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);
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 myPosition to tell us if the player is at position 1 (the left), position 2 (the
center), or position 3 (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 player object to the Main Contents layer.
2. Added the target object to the Main Contents layer.
3. Added the score and live displays in the Main Contents layer.
4. Assigned the Actions to create the essential variables .
5. Assigned the Actions to position the player .
6. Assigned the Actions to duplicate the target .
7. Assigned the Actions 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, select the Buttons layer, open up
the library ( Ctrl+L ) and drag an instance of the MyButton symbol we created earlier, make
sure that it placed somewhere above the stage so that it is not visible during the game.
Right-click this instance of the button on the stage and select Actions . We are going to
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 myPosition variable depending on where it
currently is.
on (keyPress "<Left>"){
if (player_mc.myPosition != 1){
player_mc.myPosition--;
player_mc._x-=80;
}
}

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 1 (absolute left), then pressing
the left key button moves it to the left by 80 pixels, and as long as the position of the player is
not 3 (absolute right), then pressing the right key button moves it to the right by 80 pixels. The
player movie clip is exactly 80 pixels in width, which is also exactly 1/3 of the width of the
stage, so moving it by 80 pixels to the left or the right is a whole step to the left or the right.
I find using the myPosition property easier because I do not have to think about the actual
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

We have to assign our biggest chunk of code to Frame 3 of the Actions layer. Select that
frame and open the Actions panel. We are going to do this in segments, I will explain each one
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 _y property of each
target, we will add to them the value of the speed property we set in the previous frame. Each
object has a different speed value, so they should be falling at different speeds.
//Commands the targets to move downwards.
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 320 pixels, so if the _y property exceeds that
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 _y is negative), and the speed is set as
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._y =-random(40);
target1_mc.speed= random(score)+4;
}
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 _y property lower than 250 , and then
the player has to be at the corresponding position as the target. 1 for the absolute left , 2 for
the middle object, and 3 for the object on the absolute right . If the capture condition for any of
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._y>250 and player_mc.myPosition == 1 ){
score++;
target1_mc._y =-random(40);
target1_mc.speed= random(score)+4;
}
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 Frame 5 .
//Game Over
if (lives == 0){
removeMovieClip("target1_mc");
removeMovieClip("target2_mc");
removeMovieClip("target3_mc");
gotoAndStop(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 next frame , Frame 4 in the Actions layer.
//Plays the previous frame
gotoAndPlay(3);

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


1. Added a button to the Buttons layer and configured the key controls.
2. Assigned the Actions to make the targets move.
3. Assigned the Actions to determine what happens when the targets reach the ground.
4. Assigned the Actions to determine what happens when the targets are captured.
5. Assigned the Actions to determine what happens when all the lives are consumed.
6. Assigned the Actions to make Frame 4 loop with 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 Main Content layer and use the Text Tool to write YOUR SCORE IS at the upper
part of the stage and then write PLAY AGAIN? at the lower section of the stage as illustrated in
the image below. You will have to make sure that the type of both of these texts is static (check
the Properties Inspector ).
Displaying the Score

To display the actual score on the screen, we need to use a Dynamic Text Field . Make sure
that nothing on stage is selected, select the Text Tool , and then access the Properties
Inspector and assign the Text Type to Dynamic Text 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 80px , the font to _sans , center the text, and then assign
the variable name score to it.
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 Buttons layer, open up
the Library ( Ctrl+L ) and drag a copy of the myButton symbol we created previously. Put it
somewhere above the stage. Now right-click this button and select Actions to open up
the Actions panel. Type this code to make the game play once again when pressing
the Enter button. The code is self-explanatory. Frame 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 Main Content layer.
2. Added the Score display text field to the Main Content layer.
3. Added a button to the Buttons layer and configured the key controls to go back and play the
game.
We are done. You can now test your movie or export it to try it on your mobile device.

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.

Potrebbero piacerti anche