Sunday, 24 January 2010

Magic 8 ball tutorial in AS3 part 2

This is part 2 of the Magic 8 ball tutorial where I will be using XML to display the responses of the magic 8 ball. XML is a mark up language used to structure external content. This tutorial assumes you have completed the previous tutorial as additional code will be added to this one.

Magic 8 ball tutorial in AS3 part 2

Step 1

Open up notepad and copy the following XML code, and save is as magic8answers.xml in the same folder as the magic 8 ball FLA file. XML is made up from plain text so can be created in any text editor.

<?xml version="1.0" encoding="utf-8"?>
<Answer title="Response0"> YES </Answer>
<Answer title="Response1"> MOST LIKELY </Answer>
<Answer title="Response2"> IT IS CERTAIN </Answer>
<Answer title="Response3"> OUTLOOK GOOD </Answer>
<Answer title="Response4"> NO </Answer>
<Answer title="Response5"> DOUBTFUL </Answer>
<Answer title="Response6"> REPY IS NO </Answer>
<Answer title="Response7"> ASK AGAIN </Answer>
<Answer title="Response8"> TRY AGAIN </Answer>
<Answer title="Response9"> BETTER NOT </Answer>
<Answer title="Response10"> MAYBE </Answer>

Step 2

Open up the magic 8 ball FLA file then on the timeline open the Actions panel and enter the following code.

//Array to hold all the responses.
var responseArr:Array;
//Creates a new instances URL loader class.
var my_loader:URLLoader = new URLLoader();
//Variable to hold the load XML.
var my_xml:XML;
//The load method use to load the XML file.
my_loader.load(new URLRequest("magic8answers.xml"));

//Event listener to listen to when the file has finished loading.
my_loader.addEventListener(Event.COMPLETE, xmlLoader);

function xmlLoader(event:Event):void{
my_xml = new XML(;

//Array to hold all the responses.
responseArr = new Array();

//Loop through the answer tag in the XML.
for each(var item:XML in my_xml.Answer){
//store values in the response array.

Step 3

Inside the showAnswer() function remove the response array and all the responses
elements, so that the first line of code in the function should be.
var r:int=Math.floor(Math.random()*responseArr.length);

Step 4

Test your movie clip Ctrl + Enter. Your responses should now be generated using


  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP