search

Free Flash Debugger: Commando (With Premium Source Files)

Commando is a Flash debugger that lets you change variables at runtime and run your own custom commands. It will allow you to try out whatever tweaks you want, without the hassle of changing your code and recompiling every time. This debugger also comes with its own memory monitor, and an output panel that is similar to the output dialog in the Flash IDE.


See Commando in Action


Why Use Commando?

Using Commando you can change your code at runtime. Let’s pretend you are making a platformer game. You have a jumpPower variable, but when testing your game you feel that the player can’t jump high enough. So instead of going back and changing your code, you can just type set jumpPower(25) in Commando and you can try out the new value.

Of course, this is just a simple demonstration; Commando can be extended even more. Just continue reading…


Configuration

First, download the ZIP file included with this article. Then, add the SWC file to your project’s library path.

The Library Path Dialog

Once you have added the SWC to your project’s library path, all you need are three lines of code to add an instance of Commando on the stage:

import com.pxlcoder.debug.Commando;

var commando:Commando = new Commando(flash.ui.Keyboard.ENTER, this);
addChild(commando);

Now press CTRL+ENTER (CMD+ENTER on a Mac), and you will see Commando up and running in your Flash project!


Explore

Commando comes with eight built-in functions. In this section I will explain what they are and how to use them.

Math

Using the Math function you can do addition, subtraction, multiplication and division between two numbers. The Math function can also calculate the square root of a number. For example, type math 1+1 or math sqrt(144) in the Commando dialog. The answer will show up in the output dialog.

Hide

You can use the Hide function to hide objects. You can type hide monitor or hide output to hide the two panels at the bottom. You can also use the Hide function with movieclips or buttons by simply typing hide myInstanceName.

View

You can use the View function to view hidden objects. You can type view monitor or view output to show the two panels at the bottom. You can also use the View function with movieclips or buttons by simply typing view myInstanceName. If any of your objects have their visible property set to false, typing view myInstanceName will set it to true.

Set

Using the Set function you can set values of your variables or you can set properties of your objects. To use the Set function on variables type set myVariable(myValue). To use the Set function on objects, type set myInstanceName(myPropertyName,myValue).

Get

Using the Get function you can get the values of your variables and properties. To use the Get function type get myVariable. You can also get properties by typing get myInstanceName.myPropertyName.The values will show up in the output dialog.

Probe

Using the Rrobe function you can get the probe all of the properties of an object. To use the Probe function type: probe myObjectInstanceName. The properties will be traced in the Flash IDE, rather than in the Commando output dialog.

Remove

You can use the Remove function to remove objects from the stage. To use the Remove function type remove myInstanceName.

Add

You can use the Add function to add objects back on to the stage. To use the Add function type add myInstanceName.

Note: Commando’s built-in functions each evaluate a single string, so after you type your function name and press space, make sure to type your arguments without any spaces. Instead, type your arguments as one continuous word, with commas if necessary.


Extend

While Commando has many great built-in functions, you may want something more. To solve this problem, Commando comes with a function to add your own custom commands.

Here is a quick code example of how you can create your own custom commands:

import com.pxlcoder.debug.Commando;

var commando:Commando = new Commando(flash.ui.Keyboard.ENTER, this);
addChild(commando); 

commando.addCommand("output", outputFunction); //Sets the command keyword to "output" and calls the outputFunction below

public function outputFunction(s:String):void {
     commando.output(s); //A call to Commando's built-in output dialog
}

Now press CTRL+ENTER (CMD+ENTER on a Mac), to run your code. In the Commando dialog, type output hello, and press Enter. The output dialog will now say hello!

Commando says hello!

You can also remove commands from Commando by using the removeCommand() function.

import com.pxlcoder.debug.Commando;

var commando:Commando = new Commando(flash.ui.Keyboard.ENTER, this);
addChild(commando); 

commando.removeCommand("output");

Recap: Commando has three functions that you can access; addCommand(), output() and removeCommand().


Conclusion

At the end of the day, debugging is the most important part in the development process. Commando has everything you could ever ask for in a debugger. You can use it for anything and everything.

If you’re a Tuts+ Premium member, you can download the source files for Commando – just log in and head to the Source File page.

Any questions, comments or concerns? Feel free to get in touch in the comments.

Take control of your Flash projects!



View full post on Activetuts+

Why Bother With jQuery? A Guide for (Former) Flash Developers

If you, like many Flash developers, are looking into using HTML5 for your web apps, you’ll almost certainly have come across jQuery. It’s a very popular JavaScript library, used by a large percentage of the most visited websites – but what’s all the fuss about, and should you use it?


Background

If you know AS3, you basically know a lot of JavaScript already; the two languages are very similar. So it’s tempting to just jump straight in and code – but there are a few important concepts you need to understand first. One of these is the idea of the DOM.

When you load a webpage, your browser turns flat HTML into a tree-like structure of JavaScript objects called the DOM (Document Object Model). The JavaScript DOM, then, is very similar to the ActionScript Display List; and if you’re a Flex developer, you’ll be able to see the similarities between MXML and HTML.

In Flash, we can access specific display objects by navigating to them through the display list, like stage.getChildAt(3).getChildAt(0), but this is pretty ridiculous. Instead, we’re more likely to give display objects instance names (through the Flash IDE), or store references to them in variables, arrays, or object properties, like dialogBox.okButton = new SimpleButton().

In JavaScript, we could construct our DOM entirely through JS and then tell the browser to render it, but this is an unusual approach; we’re much more likely to define the DOM via HTML, perhaps with a little JS augmentation. So, JavaScript has various different methods for accessing elements of the DOM.

The simplest of these is document.getElementById(). If we have an HTML document defined like this:

<!DOCTYPE html>
<html>
<head>
<title>Example Page</title>
</head>
<body>
<div>
<span id="example">
<p>Here's some example text.</p>
</span>
</div>
</body>
</html>

…then document.getElementById("example") will get us the highlighted span object from the DOM. We could then add a second p tag like so:

var newPara = document.createElement("p");
var newTextNode = document.createTextNode("More example text that we created on the fly.");
newPara.appendChild(newTextNode);
document.getElementById("example").appendChild(newPara);

This would update the DOM, making it equivalent to what would have been created if the original HTML was as follows:

<!DOCTYPE html>
<html>
<head>
<title>Example Page</title>
</head>
<body>
<div>
<span id="example">
<p>Here's some example text.</p>
<p>More example text that we created on the fly.</p>
</span>
</div>
</body>
</html>

What if you wanted to then access the two p elements? We can’t access them directly with document.getElementById(), since they have no ID, but we can use document.getElementsByTagName("p") to obtain an array containing both of them.

And if we’d had another span, like this:

<div>
<span id="example1">
<p>Here's some example text.</p>
<p>More example text that we created on the fly.</p>
</span>
<span id="example2">
<p>A second span.</p>
<p>We don't care about these paragraphs.</p>
</span>
</div>

…and we only wanted to obtain the first two p tags, we could call document.getElementById("example1").getElementsByTagName("p") just to retrieve those two – all these DOM functions work at any level in the tree structure, just like how every Flash DisplayObjectContainer has methods like getChildAt().

This is simple enough to understand, but there are problems. The first, you may not be surprised to hear, concerns Internet Explorer.


Cross-Browser Compatibility

Impressive Webs has a great outline of Internet Explorer’s getElementById() problem. Essentially, if you have an HTML element like this:

<span name="exampleName"></span>

…then, in most browsers, document.getElementById("exampleName") will not give you the span in question, but in IE7, it will. (Other browsers could use document.getElementsByName("exampleName")[0] to return this particular span.)

This means that, to be consistent across browsers (and assuming we can’t change the HTML), we’ll need to write code like this:

var theSpan;
if (usingIE) {    //I won't explain how to detect the browser here
	var temp = document.getElementById("exampleId");
	//this might have returned an element with a name of "exampleId", so we must check:
	if (temp.getAttribute("id") == "exampleId") {
		theSpan = temp;
	}
}
else {
	theSpan = document.getElementById("exampleId");
}

More generally, we could wrap that up into a re-usable function:

function getElById(id) {
	if (usingIE) {
		var temp = document.getElementById(id);
		if (temp.getAttribute("id") == id) {
			return temp;
		}
	}
	else {
		theSpan = document.getElementById(id);
	}
}

Great! But, unfortunately, there are so many of these irritating little differences; it will probably surprise you, if you’re coming from a straight-Flash background, where “compatibility issue” generally means that the Flash Player is a little slow on certain platforms.

jQuery solves this. It papers over the cracks between different browsers with its own set of functions, so if the user’s browser is at least as new as IE6, your code can have a consistent interface.

That’s not the only way that jQuery makes JavaScript simpler…


Easy Syntax

Let’s go back to this snippet of HTML, and assume we want to retrieve the highlighted p elements from the DOM:

<div>
<span id="example1">
<p>Here's some example text.</p>
<p>More example text that we created on the fly.</p>
</span>
<span id="example2">
<p>A second span.</p>
<p>We don't care about these paragraphs.</p>
</span>
</div>

With jQuery, we can just write:

jQuery("#example1 p")

That’s all we need! #example1 says “get the element with an ID of example1” and p says “get all the p elements that are children of that element”. It returns a “jQuery object”, which is a JavaScript object that contains the two p elements themselves from the JS DOM, plus a few extra properties and methods specific to jQuery.

We can make it even shorter still, by replacing jQuery with $ – there’s no mystery here; $ is just a short variable name. Compare it to native JavaScript code:

//regular JS, without cross-browser compatibility:
document.getElementById("example1").getElementsByTagName("p")

//jQuery, with cross-browser compatibility built in:
$("#example1 p")

It’s not just shorter, it’s consistent with CSS, which makes it easy to pick up. We could use the exact same selector as inside our jQuery() call to style these specific paragraphs in a CSS stylesheet:

#example1 p { color: red }

That’s just a very simple example; I’m not going to go into detail, but I’m sure you can see the benefit of being able to use the same selectors in both CSS and jQuery.

More Than Just Selection

I mentioned that the jQuery objects returned by a $() call had additional methods and properties. These give you an easy syntax for writing other common pieces of code.

For example, we could add a mouse click event listener and handler function to both of those p elements like so:

$("#example1 p").click(function() {
	alert("You clicked a paragraph!");
});

Or, you could make them all invisible:

$("#example1 p").hide();

Or, you could run some more general JavaScript on them:

var allText = "";
$("#example1 p").each(function() {
	allText += $(this).text();
});

In each case, jQuery provides a simple, short, consistent way of writing. It means it’s faster to get code from your head to the browser – and not just because it requires fewer characters.


Tweens and Transitions

Since Flash has its roots in animation, we’re used to it having plenty of tweening capabilities built in – both in the Flash IDE and in the Tween class, not to mention the various tweening libraries available.

JavaScript is different; animation is not an intrinsic part of the platform. But little tweens and transitions are expected parts of the user interaction of modern web app: if I add a new comment on a thread, it slides into place; if I remove an item from my shopping basket, it flashes red and disappears. Without these, apps look unpolished.

jQuery adds these little transitions.

For example, let’s say we want to make either of the aforementioned paragraphs fade out when they’re clicked. Easy:

$("#example1 p").click(function() {
	$(this).fadeOut();
});

Nothing to it! And you can pass a duration and callback to the fadeOut() function, if you don’t like the defaults.

For something a little more powerful, we can use the animate() method. This is essentially the equivalent of a tween; pass it a set of CSS properties and values to animate towards, a duration, a type of easing, and a callback, and it takes care of it all for you.

It’s not exactly Greensock, but it’s far more convenient than writing these effects from scratch, and ideal for web app interfaces.

Speaking of which…


UI Widgets

HTML has a few UI components built in, of course: buttons, text fields, and so on. HTML5 defines a few new ones, like a pop-up calendar picker and color picket (though these are currently only supported in Opera).

But these aren’t enough, on their own, to make up a full, modern web app interface. There’s nothing to handle tabs within a page, or a progress bar, or even a simple dialog window (outside of alert() and prompt()).

jQuery UI, an optional library build on top of jQuery, adds these extra widgets, with methods and events that are consistent with the usual jQuery syntax. Think of it as a JavaScript equivalent to Keith Peters’ AS3 MinimalComps. The demo page shows it off better than I can explain it.

Every widget can support custom themes, so you can create a single skin that fits your site and apply it to every component, making it possible to modify their appearance all at once. Again: consistency! Plus, you can apply UI-related effects to other elements; make it possible for the user to drag or resize a DOM element, or click and drag a box around a group of elements to select them for submission.


Other Reasons jQuery is So Popular

The cross-browser compatibility, easy syntax, tween capabilities, and UI elements are the main benefits of jQuery over plain JS in my eyes. There are other reasons to like it, though:

  • It’s widely-used, and has been around for six years: it’s not some flash-in-the-pan “new hotness” that’s still unproven and might just die off in a few months. You can trust that it’ll be around for a while.
  • There’s a big community surrounding it: this means there are plenty of tutorials and books and forums and people to learn from; you’re not going to be fumbling around in the dark.
  • The documentation is excellent: seriously, take a look; it’s very clean and full of examples and demos
    • There are even alternative sets of docs with different interfaces, if that’s what you require (another example of the great community)
  • It’s open source: the community can add to it, and you can hack on it and learn from it
    • Paul Irish has two videos breaking down what he learned from just running through the source

So why wouldn’t you use jQuery? As with most technology choices, it’s a question of making sure you’re using the right tool for the job. If you have a simple DOM structure, or don’t require fancy animations and transitions, or are mainly using the canvas to render your interface, rather than widgets, jQuery probably isn’t necessary.

If you’re already using one or more JavaScript libraries – Dojo, MooTools, YUI, etc. – you may well find that you don’t need jQuery’s functionality on top of what they offer. But my goal in this article is not to try to sell you on any particular library above any other.

I hope this article has helped to explain just what the big deal is about jQuery, particularly if you’re coming from the world of AS3 and Flash. If you’d like to learn it, check out the jQuery tag over on Nettuts+ – jQuery for Absolute Beginners is a good place to start.

Let me know if you’ve any questions!



View full post on Activetuts+

Build an Active Flash Game Menu: Slides

Stop using static menus! Most players immediately base their initial impression of a Flash game on the menu that they see when they load it. Stand out from the crowd with an active menu!

This tutorial was first posted in December 2011, but has since been updated with extra steps that explain how to make the code more flexible!


Final Result Preview

Introduction: Static vs Active

The word “static” essentially means lacking in change. The majority of menus we see throughout web games are lacking in change, you simply press Play and the game starts. Menus like that are overused and show little creativity or innovation.

To make a menu “active” we must continuously cause change. So in this tutorial that is exactly what we are going to accomplish: a menu that continuously changes.


Step 1: Setting Up

The first thing we are going to need to create is a new Flash File (ActionScript 3.0). Set its width to 650px, its height to 350px, and the frames per second to 30. The background color can be left as white.

Now save the file; you can name it whatever you please, but I named mine menuSlides.fla.

In the next section we will create the nine MovieClips used in the menu. For reference, here is a list of all the colors used throughout the tutorial:

  • White – #FFFFFF
  • Gold – #E8A317
  • Light Gold – #FBB917
  • Blue – #1569C7
  • Light Blue – #1389FF
  • Green – #347235
  • Light Green – #3E8F1B
  • Red – #990000
  • Light Red – #C10202
  • Matte Grey – #222222

Step 2: Creating the Slide MovieClips

To start with we will create the slides used in the transitions, but before we begin let’s turn on some very useful Flash features.

Right-Click the stage and select Grid > Show Grid. By default it will create a 10px by 10px grid across the stage. Next, right-click the stage again and this time select Snapping > Snap to Grid.

Now we can begin drawing! Select the Rectangle Tool and draw a Light Gold rectangle, 650px wide and 350px tall (you can Alt-click on the stage to make this easier). Now change the color to Gold and draw groups of three squares, each 20x20px, to form the shape of an L in each corner,:

The basic Slide Design

Select the whole stage, right-click and choose Convert to Symbol. Name the MovieClip goldSlide and make sure that the type is MovieClip and the registration is top-left.

To save time and make things a whole lot easier, right-click the goldSlide MovieClip in the Library and select Duplicate Symbol three times to make three more copies. Change the colors in the new MovieClips to blue, green and red, then rename the MovieClips to blueSlide, greenSlide and redSlide.

Before we continue we should add some text to each slide. On goldSlide write PLAY, on blueSlide write INSTRUCTIONS, on greenSlide write OPTIONS and on redSlide write CREDITS.

Now that we have the text in place we can break it apart by right-clicking on it and selecting Break Apart twice; this will break the text down to a fill which will transition more smoothly. Plus as a bonus there will be no need to embed a font if you are just using it for the menu!

The Buttons

Now that we have drawn the 4 slides we can focus on the sideButton MovieClip that is used to move the slides either left or right.

First, draw a rectangle 30x60px with only a stroke (no fill), then draw diagonal lines 45 degrees from the top-right and bottom-right corners until they snap together in the middle of the opposite side. Now apply a Matte Grey fill to the triangle:

What your side Button Should Look Like

Next, delete the lines, then right-click the triangle and select Convert to Symbol. Name it sideButton, set the type to Button and make sure the registration is in the top-left corner.

Now insert 3 keyframes in the timeline by right-clicking the timeline and selecting Insert Keyframe. On the Up frame, select the fill of the triangle, go to the Windows tab and select Color. Change the Alpha to 50%. On the Over Frame repeat the same process, but this time set the alpha to 75%.

Now we can begin on the four numbered circle buttons, for jumping directly to a particular slide.

To start draw a white 30px circle with no stroke. Convert it to a symbol, name it circleOne, and set its type to Button and its registration point to the center. Insert three keyframes like we did before and then go to the Up frame.

Draw a black 25px circle with no stroke and center it to the middle through the coordinates or by using the Align menu. Next deselect the black circle, then reselect it and delete it. You should now have a white ring remaining. Now grab the text tool and put a white “1″ in the center of the ring. Then break this number apart until it is a fill.

circleOne Up Frame

Go to the Over frame and draw a black “1″. Center it and break it apart until it becomes a fill. Now deselect and reselect the fill, then delete it. Select everything on the frame and copy it, then go to the Down frame, select everything on it and hit delete. Paste in what we have copied.

circleOne Over Frame

Now create three more circle MovieClips, following the same process, for the numbers 2, 3 and 4.


Step 3: Positioning the MovieClips

Okay, we’re almost half-way done! First drag all of the slides onto the stage and position them with the following coordinates:

  • goldSlide: (0, 0)
  • blueSlide: (650, 0)
  • greenSlide: (1300, 0)
  • redSlide: (1950, 0)

Now drag and drop two copies of the sideButton. The first copy should be positioned at (10,145); before we can position the second copy we must first flip it!

Select the second copy and press Ctrl-T. Change the left-right to -100% and leave the up-down at 100%. Now move the second copy to (640,145).

Finally drag and drop the four circle MovieClips and position them as so:

  • circleOne: (30, 320)
  • circleTwo: (70, 320)
  • circleThree: (110, 320)
  • circleFour: (150, 320)

Your stage should now look like this:

What your stage Should Look Like

The blue, green and red slides are hidden just off to the right of the stage. Now select everything on the stage and convert to a symbol. Name it menuSlidesMC, set the type to MovieClip and the registration to the top-left corner, and export it for ActionScript as MenuSlidesMC.

Before we finish we must give each of the MovieClips inside menuSlidesMC an instance name. Select each slide in the order they appear from the left and name them slide1, slide2, slide3 and slide4 respectively. Name the circle buttons one, two, three and four, and finally name the side buttons left and right.


Step 4: Setting Up the Classes

Now that all of our MovieClips have been created we can start setting up the two classes we are going to use.

First go to your Flash file’s Properties and set its class to menuSlides; then, create a new ActionScript 3.0 file and save it as menuSlides.as.

Now copy the following code into it; I will explain it after:

package{
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;

	public class menuSlides extends MovieClip{
		public var menuSlidesMC:MenuSlidesMC = new MenuSlidesMC();
		public function menuSlides(){
			addChild(menuSlidesMC);
		}
	}
}

Pretty basic – it’s a document class, into which we imported the MovieClips and Events we will use. Then we created an instance of MenuSlidesMC, and added it to the stage.

Now create a new ActionScript 3.0 file for the menuSlidesMC instance. Save it as MenuSlidesMC.as and copy the following code into it:

package{
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;

	public class MenuSlidesMC extends MovieClip{
		public var speed:Number = new Number();
		public var activeSlide:Number = new Number();
		public function MenuSlidesMC(){
			speed = 10;
			activeSlide = 1;
			addEventListener(MouseEvent.CLICK, slidesClick);
			addEventListener(Event.ENTER_FRAME, slidesMove);
		}
	}
}

Just like last time, we imported what we are going to need, but we created two number variables. The first variable, speed, is actually how many pixels the slides are moved by each frame. (Note: this number has to evenly divide into your stage’s width to give a smooth transition). The second variable, activeSlide, tells us which slide is currently set to be on screen.

We also added two event listeners for functions we are going to create; one of them is called on a mouse click, and the other is called at the beginning of every frame.


Step 5: Creating the Event Handler Functions

To begin we will get the mouse click function out of the way. Start by creating a public function named slidesClick():

public function slidesClick(event:MouseEvent):void {

}

Next we will create some if-statements regarding the event.target.name. Basically, this property stores the name of the object that was targeted by the mouse click. We can use this to check which button is pressed:

if(event.target.name == "left"){
	if(activeSlide>1){
		activeSlide-=1;
	}
}else if(event.target.name == "right"){
	if(activeSlide<4){
		activeSlide+=1;
	}
}

if(event.target.name == "one"){
	activeSlide=1;
}else if(event.target.name == "two"){
	activeSlide=2;
}if(event.target.name == "three"){
	activeSlide=3;
}else if(event.target.name == "four"){
	activeSlide=4;
}

The code above goes in the slidesClick() function. The first set of if-statements are for the left and right side buttons; they increase or decrease the value of activeSlide, but never allow the value to become less than 1 or greater than 4 (since we only have four slides). The second set of if-statements are for the circle buttons; instead of just incrementing or decrementing the value of activeSlide they set it to the selected value.

Now let’s begin with the ENTER_FRAME handler function:

public function slidesMove(event:Event):void {

}

Add the slidesMove() function below your slidesClick() function and we’ll start adding some code to it. First, we’ll use a switch to check which slide should be on the screen, based on the value of activeSlide:

switch (activeSlide){
case 1:

break;
case 2:

break;
case 3:

break;
case 4:

break;
}

Now in each case we will create an if/else block that will check that slide’s current x-position, and move all of the slides either left, right, or not at all, depending on where the desired slide currently sits.

The first case looks like this:

if(slide1.x<0){
	slide1.x+=speed;
	slide2.x+=speed;
	slide3.x+=speed;
	slide4.x+=speed;
}else if(slide1.x>0){
	slide1.x-=speed;
	slide2.x-=speed;
	slide3.x-=speed;
	slide4.x-=speed;
}

Now all we have to do is repeat the same process for the other cases! After you are done your swtich should look like this:

switch (activeSlide){
	case 1:
		if(slide1.x<0){
			slide1.x+=speed;
			slide2.x+=speed;
			slide3.x+=speed;
			slide4.x+=speed;
		}else if(slide1.x>0){
			slide1.x-=speed;
			slide2.x-=speed;
			slide3.x-=speed;
			slide4.x-=speed;
		}
	break;
	case 2:
		if(slide2.x<0){
			slide1.x+=speed;
			slide2.x+=speed;
			slide3.x+=speed;
			slide4.x+=speed;
		}else if(slide2.x>0){
			slide1.x-=speed;
			slide2.x-=speed;
			slide3.x-=speed;
			slide4.x-=speed;
		}
	break;
	case 3:
		if(slide3.x<0){
			slide1.x+=speed;
			slide2.x+=speed;
			slide3.x+=speed;
			slide4.x+=speed;
		}else if(slide3.x>0){
			slide1.x-=speed;
			slide2.x-=speed;
			slide3.x-=speed;
			slide4.x-=speed;
		}
	break;
	case 4:
		if(slide4.x<0){
			slide1.x+=speed;
			slide2.x+=speed;
			slide3.x+=speed;
			slide4.x+=speed;
		}else if(slide4.x>0){
			slide1.x-=speed;
			slide2.x-=speed;
			slide3.x-=speed;
			slide4.x-=speed;
		}
	break;
}

And that’s it! We are all finished with the code and the menu should be working great right now.

…But wait, what if we want to add more slides or take some away?


Step 6: Adding Slides to an Array

At the moment our code isn’t very flexible due to all of those hard-coded if statements. So let’s do something bold: delete all of the code in the slidesMove() function because we will no longer be needing it, and also delete the if-statements for the circle buttons as we are going to optimize those as well.

Now declare a new variable (underneath speed and activeSlides):

public var slidesArray:Array = new Array();

The first variable, slidesArray, will be an array that contains all of our slides, which will allow us to access them by referencing an item in the array (so we can use slidesArray[2] instead of slide3).

One thing to note is that the first item in an array is given an index of 0, so we will have to make some changes to our instance names.

Select each slide in the order they appear from the left and name them slide0, slide1, slide2 and slide3, respectively. And to help us cut down on the number of lines of code we use, select each circle button in the order they appear from the left and name them circle0, circle1, circle2 and circle3, respectively.

If you are going to add more slides and buttons, now is the time to do so. Just position the extra slides at the end of the row of slides, then give them instance names following the same order. Then do the same for the circle buttons.

Now that we have the instance names correct we must add the slides to the array. Do so by adding the following code to your constructor:

slidesArray = [slide0, slide1, slide2, slide3, slide4, slide5];

Now the slides are in the array and can be accessed by their index in the array. For example, slidesArray[0] is equivalent to slide0 because that is the first item in the list.

Next, inside the “right” else-if statement, change the condition to:

if(activeSlide < slidesArray.length-1){

The value of slidesArray.length is equal to the number of elements in the array, so this new condition will now allow us to press the button and shift the slides over as long as the active slide is not the final slide.


Step 7: Handling Circle Button Presses

Now, when a circle button is clicked, we need to figure out which one it is (and which slide it refers to).

Create an array to hold all the circle buttons. First, define it, beneath the slide array:

		public var slidesArray:Array = new Array();
		public var circlesArray:Array = new Array();

Then, add the circle buttons to the array in the constructor:

			circlesArray = [circle0, circle1, circle2, circle3, circle4, circle5];

Now, move to the slidesClick() function, underneath the whole if-else block. We’re going to check whether the button clicked is in the circle buttons array:

			if (circlesArray.indexOf(event.target) != -1) {

			}

The array’s indexOf() function checks to see whether an object is in the array; if it’s not, it returns -1. So, we’re checking to see whether it’s not equal to -1, which will check to see whether it is in the array.

Assuming it is, then the indexOf() function will return the index of the button within the circle buttons array – so, if circle3 was clicked, circlesArray.indexOf(event.target) will be equal to 3. This means we can just set activeSlide to 3, and we’re done!

			if (circlesArray.indexOf(event.target) != -1) {
				activeSlide = circlesArray.indexOf(event.target);
			}

Step 8: Moving the Slides

The only thing left to do is move all of the slides. Begin by adding the same loop as we had before, in the slidesMove() function:

for(var i:int = 0; i < slidesArray.length; i++){

}

An if-else statement needs to be added now; this will use the variable activeSlide to select a slide out of the array and check where its x-position is, just like before.

if(slidesArray[activeSlide].x<0){

}else if(slidesArray[activeSlide].x>0){

}

Since activeSlide is a number, slidesArray[activeSlide] refers to one specific slide, so slidesArray[activeSlide].x is equal to that slide’s x-position.

In the first case we will add a for loop to move all of the movie clips to the right, and in the second case we will add a for loop to move all of the movie clips to the left.

Right:

for(var j:int = 0; j < slidesArray.length; j++){
	slidesArray[j].x+=speed;
}

Left:

for(var k:int = 0; k < slidesArray.length; k++){
	slidesArray[k].x-=speed;
}

If you test this now, you will notice that our optimised code has lead to a much zippier interface!


Step 9: Taking It Further

If you wanted to take this even further, you could use a for loop to position the slides and the circles, rather than needing to drag and drop them in the Flash IDE. For example, to position the slides, we’d first position slide0 in the constructor:

			slidesArray = [slide0, slide1, slide2, slide3, slide4, slide5];
			slidesArray[0].x = 0;
			slidesArray[0].y = 0;

Then, we’d loop through all the other slides, starting at slide1:

			slidesArray = [slide0, slide1, slide2, slide3, slide4, slide5];
			slidesArray[0].x = 0;
			slidesArray[0].y = 0;
			for (var i:int = 1; i < slidesArray.length; i++) {

			}

We can give all the slides an y-position of 0:

			slidesArray = [slide0, slide1, slide2, slide3, slide4, slide5];
			slidesArray[0].x = 0;
			slidesArray[0].y = 0;
			for (var i:int = 1; i < slidesArray.length; i++) {
				slidesArray[i].y = 0;
			}

…and then we can set each slide’s x-position to be 620px to the right of the slide before it:

			slidesArray = [slide0, slide1, slide2, slide3, slide4, slide5];
			slidesArray[0].x = 0;
			slidesArray[0].y = 0;
			for (var i:int = 1; i < slidesArray.length; i++) {
				slidesArray[i].x = slidesArray[i-1].x + 620;
				slidesArray[i].y = 0;
			}

If your slides aren’t 620px wide, you can even detect their width automatically!

			slidesArray = [slide0, slide1, slide2, slide3, slide4, slide5];
			slidesArray[0].x = 0;
			slidesArray[0].y = 0;
			for (var i:int = 1; i < slidesArray.length; i++) {
				slidesArray[i].x = slidesArray[i-1].x + slidesArray[i-1].width;
				slidesArray[i].y = 0;
			}

You can do the same thing with the circle buttons, but I’ll leave that up to you to experiment with.

The great thing about this is, you can add as many slides as you want to the menu; all you have to do is add them to the array, and they’ll be dealt with by this code.

(You can remove slides from the array, too, but they won’t be affected by any of the code, so you’ll probably need to reposition them in the Flash IDE.)

Conclusion

Thank you for taking the time to read through the tutorial, I hope it was helpful and that you learned a little something about active game menus.



View full post on Activetuts+

Create a Microphone-Controlled Flash Game: Code

This entry is part 2 of 2 in the series Create a Microphone-Controlled Flash Game

In this mini-series, we’re creating a spaceship game where the main control is via the microphone: shout louder to make the ship fly higher. So far, we’ve created all the required graphical elements for the game. Now, it’s time to work on our code. We’ve got a lot to do, so let’s get started!


Final Result Preview

For the purposes of keeping the tutorial simple, we have done no error checking for the existence of a microphone. This means that, if you do not have a microphone plugged in, turned on, and set up for use with Flash, the game won’t work: you’ll get an Error #1009. Check the comments in Player.as in the source files for information on how to deal with this.


A Small Note:

For some reason Flash Builder isn’t working perfectly. In particular, it’s ignoring code hinting – but, nevertheless, one should be able to follow the tutorial.


Project Setup

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


Creating the Player

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


Creating Space Objects

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


Player Animation and Collision Response

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


Setting Up Scores and Lives

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


Creating Our Background

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


Cleaning Up Our Game

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


Creating the Game Over Screen

Don’t like ads? Download the screencast, or subscribe to Activetuts+ screencasts via iTunes!


Conclusion

Thank you for watching. It’s been a huge tutorial, and afterwards I would have liked to do some things differently:

  • First off the classes have just been added one by one, but it would have made more sense for the classes to be organised in packages.
  • Even though our project works fine, we do get some run time errors, which isn’t very neat.
  • Also, it’s pretty easy to get very far by saying nothing, and just sticking to the bottom of the screen.

Nevertheless, I hope you enjoyed this tutorial, and most importantly learned something from it.



View full post on Activetuts+

Free Greensock-Based Flash Slideshow Framework (With Premium Source Files)

Something a little different for you this week: a Flash slideshow framework. As well as finding it directly useful for any presentations you may give, Premium members can download the full source code, and take it apart to see how the Greensock tweening libraries were used to put it together.


Preview

There are three example slideshows created with the framework:

The slideshows support images, SWFs, and FLV videos, and are all defined by a single simple XML file.


Download

All the files you need to actually use the slideshows are available in this free ZIP file.

If you’re a Premium member, you can download the source files as well; these use Greensock’s LoaderMax and TweenLite libraries, so make excellent examples. You could use these files as examples of how to use those libraries, or could extend them to add your own flair or new features.


Active Premium Membership

We run a Premium membership system which periodically gives members access to extra tutorials, like this one! You’ll also get access to Psd Premium, Vector Premium, Audio Premium, Net Premium, Ae Premium, Cg Premium, Photo Premium, and Mobile Premium. If you’re a Premium member, you can log in and download the tutorial. If you’re not a member, you can of course join today!



View full post on Activetuts+

Page 1 of 15312345...102030...Last »
top