Making Games in Actionscript 3.0 – prototyprally https://prototyprally.com/ rapid prototyping of games using flash Sun, 19 Feb 2017 18:52:37 +0000 en-US hourly 1 https://wordpress.org/?v=5.1.1 MGAS3FD 6: Click it like it's hot https://prototyprally.com/mgas3fd-6-click-it-like-its-hot/ https://prototyprally.com/mgas3fd-6-click-it-like-its-hot/#comments Sat, 16 May 2009 12:02:17 +0000 https://prototyprally.com/?p=306 Continue reading ]]> Hello there. This is the sixth part of the Making Games in ActionScript 3 using FlashDevelop

By now we’ve got almost all the basic building blocks to make a simple game. All that is missing is how to get some input. Last time we touched on it a little bit using the mouseX and mouseY properties.
Those are the most straightforward to get at, but other inputs aren’t very complicated either. Let’s start with the mouse button.


Note that it’s mouse button, not buttons, one of the limitations of the Flash platform is that you only have access the to the left click.
Right click gives a menu, and there’s no getting around that.

To get the most of out of this part we need to start with making a Player class. Check back in part three for how to add a class but name it Player this time. Add an instance of the player to your Main class and make sure it’s on the stage. If you’re too lazy just get the prepared project here.

Getting input brings us back to the event handling we started with in last part, in your Enemy class’ constructor add an event listener for MouseEvent.CLICK:

addEventListener(MouseEvent.CLICK, handleClick);

Once this is done we add the handler method, use the neat CTRL+1 autocompletion or just type this out (copypaste is cheating).

private function handleClick(e:MouseEvent):void {
	trace("clicked enemy");
}

Give the Enemy a click, and gasp at the fantasticness of the traced output. You will notice that if you click outside the enemy nothing is traced. This is because we are listening for clicks on that specific object. If you add multiple enemies they will each have their own handler for clicks.

Sometimes this is great, other times, not so great. What if you have a whole bunch of enemies and want to do something in your main class when any one of them is clicked. You can use this exact method and let the enemy call a function on your Main class, but that’s not very pretty code.
Adding a listener to each one from the Main class is a possibility, since a handler can handle events from many “dispatchers” (things that broadcast events are called dispatchers). But, we don’t want to repeat ourselves unless we absolutely have to.

So, we’re going to do it the neat way. Add another listener, this time in the Main class. Do it the exact same way, but let’s put a different trace in so we can tell them apart:

private function handleClick(e:MouseEvent):void {
	trace("clicked in main");
}

For this example to work we’ll need a couple of extra enemies. Since we don’t really need a reference to them we can do it like this:

for (var i:int = 0; i < 5; i++) {
	var tmpEnemy:Enemy = new Enemy();
	tmpEnemy.x = Math.random() * 800;
	tmpEnemy.y = Math.random() * 600;
	addChild(tmpEnemy);
}

What we do here is first a small loop, this is a classic for loop, if you need to read up on what the arguments are a quick googling should help you out. Then we create a temporary variable to hold a reference to the enemy we’re about to create. We use that to position the enemy at a random spot on the stage. Math.random() returns a random number between zero and one, we multiply that with the stage size we’ve set in the project properties (800×600 is the default in FlashDevelop). The Math class contains all the math related methods, so we’ll see more of that in a later parts of these tutorials.

Run it and give any Enemy a good clickin’, you should see both the trace statements in your output. The attentive log reader notices that the enemy’s trace always arrives before the main trace. This is because of something called event bubbling.

This means that when a object added as a child to something receives a click (or any other event) this event will bubble up the hiearachy to it’s parent. The parent will in turn bubble it further and so on. Thus, by listening for click events on our Main class we’re getting all clicks in the whole application. Almost.

The click registration respects the objects shape (it doesn’t handle images with alpha though). A good way to visualise this is to set the enemys propety buttonMode to true. This will give you the hand cursor whenever you’re in a position that would click that object.

If you want to listen for all clicks you will need to add a listener to the stage. This will give you all clicks even those that aren’t really on anything, but we’re not going to need that right now.

Knowing what got clicked is real easy when you’re only listening for clicks on a specific object, but as you’ve seen that’s not always the case.

You have probably noticed that the event handling functions accept an argument. I (and Flash Develop) almost always name this e:

private function handleClick(e:MouseEvent):void

But you can name it however you want, it will have to be there however  since that’s where all the information about the event goes.

You can use FlashDevelops autocompletion to take a look what properties are available, there’s quite a lot of them. We’ll focus on the one named target for now.
The target is the object that initally dispatched the event. In our case that will be either one of the enemies or your new Player class, assuming this is the listener we set up in Main.

This property is an object which is one of the most basic datatypes in Flash. This is because the thing that dispatched the event could be of any type. To get at the actual Enemy we’ll need to cast it.

If all you care about is what class the target was you can do it like this:

if (e.target is Enemy) {
	trace("run away");
}

This is pretty straightforward, the is operator compares the target to a class and evaluates to true if it’s a match. But there are other neat tricks you can do which are especially useful if you want to do something with the target.

Try assigning your enemy to a variable in the handler:

var targetEnemy:Enemy = e.target;

The compiler will whine about this, since we’re trying to put a generic object into something that’s meant to hold an enemy. To get around this we need to specify that this infact is what we want to do:

var targetEnemy:Enemy = e.target as Enemy;

Now, if this succeeds the enemy will be accesible via the variable, if it fails the variable will be null. This combined with the fact that in actionscript everything can be evaluated as a Boolean lets us do like this:

var targetEnemy:Enemy = e.target as Enemy;

if(targetEnemy) {
	targetEnemy.y += 20;
}

If you click the player the cast will fail and targetEnemy will be null. null will evaluate as false, and a reference will be true so we can safely do stuff with our enemy inside. Neat, huh?

]]>
https://prototyprally.com/mgas3fd-6-click-it-like-its-hot/feed/ 39
MGAS3FD 5: Enter the frame https://prototyprally.com/mgas3fd-5-enter-the-frame/ https://prototyprally.com/mgas3fd-5-enter-the-frame/#comments Wed, 25 Mar 2009 12:00:11 +0000 https://prototyprally.com/?p=268 Continue reading ]]> Welcome to the fifth part of Making Games in ActionScript 3 using FlashDevelop.

Wow, when I  got started on this whole tutorial thing I never expected it’d take four parts just to get to the enter-frame part. But here we are.

This post will be about making stuff move. But before that we’ll need a quick primer on Events. They is one of the mainstays of actionscript, especially version 3.

The basic concept is that an event can come from any place at any time and whoever listens gets notified. This is what drives Flash at it’s core, everything that is done is in response to an event.  There are events for alot of things and they’ll come back in pretty much every step from here on, so listen up.

To get things moving about we need to run some code each frame. The way to do this is to set up an even listener for the ENTER_FRAME event:

addEventListener(Event.ENTER_FRAME, handleEnterFrame);

If you type this out in the constructor for your Main class you will notice that FlashDevelop gives you a whole bunch of suggestions, these are all events you can listen for, but right now we want the ENTER_FRAME one.

The second parameter is the function that will handle this, you can name these whatever you please, but I find it good practice to prefix them with handle just to make it clear what they do.

Next we need to add this function we are refering to, if you want to you can place your cursor over the function name and press CTRL+1, this will invoke the contextual code generator that will create that little snippet for you. If not just type this code out below the constructor:

private function handleEnterFrame(e:Event):void {
	trace("enter the frame!");
}

Now run your code, if everything’s okay you should get a flood of enter the frame in your output window.

Now we can start making stuff move around, try adding to one of your enemies properties:

enemy.x = enemy.x + 1;

When doing things like this i normally use the shorthand for adding to a property, it does the exact same things, it’s just a little bit less long winded:

enemy.x += 1;

If you run the code now, you should have a moving gnome!

While this is very neat, it’s not very interactive. Let’s get my favourite input method involved.

Each DisplayObject (in this case your Main- and Enemy class) has a pair of properties called mouseX and mouseY, these are the relative position of the mouse pointer to their registration point:

enemy.x = mouseX;

Now it should be a walk in the park to get the gnome to rotate and follow the mouse pointer. For an added challenge try making him rotate around his nose instead of upper left corner.

In the next part, number six, we get some interactivity into the mix.

]]>
https://prototyprally.com/mgas3fd-5-enter-the-frame/feed/ 23
MGAS3FD 4: More embedding https://prototyprally.com/mgas3fd-4-more-embedding/ https://prototyprally.com/mgas3fd-4-more-embedding/#comments Wed, 18 Mar 2009 12:00:18 +0000 https://prototyprally.com/?p=256 Continue reading ]]> This is the fourth part of Making Games in ActionScript 3 using FlashDevelop.

gardengnomeLast time we got our first enemy on the stage. Now we’ll take a quick look at embedding other formats into your classes. Grab the gnome here to the right and put him in your assets folder.

The syntax is basically the same to embed other formats (png/jpg).

[Embed(source='../../../../../../assets/gardengnome.png')]

FlashDevelop will generate this little string for you if you doubleclick your wanted image in the Project panel. Place the [Embed] tag right before the class declaration as we did last time.

If you compile and run now you will get a runtime exception from the player. This is because our enemy is still defined as a Sprite, and sprites are vector based. We need to change the base class to Bitmap. Do that, and make sure your imports are in order before you compile. Now it all should run just fine again.

Flash does not resize your image, it will be embedded in it’s full resolution. So make sure that it’s a proper size before embedding it, resizing it in code will just add unnecessary bloat to your file and will affect performance.

Having to change the base class like this can be a bit of a hassle, especially when you have multiple levels of inheritance going (maybe a baseclass like GameObject). So there’s a cleaner way to do this. Create these two  properties on your enemy:

private static const GfxGnome:Class;
private var gfx:Bitmap;

The first one is both a static constant, this means this property is attached to the actual class, and not to the instances of it you create. Wether you make them private or public is up to you, I prefer having things private until otherwise needed, so that’s what I went with.

For now we set the base class for the enemy back to Sprite. But instead of having the [Embed]-tag before the Enemy class we put it before the GfxGnome class. This will make the gardengnome.png attach to that class instead.

Now we need to instantiate that into our gfx property. We do that in the constructor like this:

gfx = new Enemy.GfxGnome();

Since GfxGnome is attached to the class and not this specific instance we need to specify that by using Enemy before it’s name.

If you run your code now you will notice that nothing is showing up. This is because we need to add our graphics as a child, right now they’re just hiding out in memory somewhere.

Adding the graphics as a child works the same way here as it did in our Main class where we first added the Enemy:

addChild(gfx);

Now you should be all set for getting graphics into your games. If you got lost somewhere on the way, the project files are available for download.

This is what your enemy class should look like:

package com.grapefrukt.tutorial.supergame.enemies {

	import flash.display.Bitmap;
	import flash.display.Sprite;
	
	public class Enemy extends Sprite {
		
		[Embed(source='../../../../../../assets/gardengnome.png')]
		private static const GfxGnome:Class;
		private var gfx:Bitmap;
		
		public function Enemy() {
			trace("I'm alive");
			gfx = new Enemy.GfxGnome();
			addChild(gfx);
		}
		
	}
	
}

Next time we’ll make stuff move around!

]]>
https://prototyprally.com/mgas3fd-4-more-embedding/feed/ 20
MGAS3FD 3: Getting on with it https://prototyprally.com/mgas3fd-3-getting-on-with-it/ https://prototyprally.com/mgas3fd-3-getting-on-with-it/#comments Fri, 13 Mar 2009 12:00:23 +0000 https://prototyprally.com/?p=183 Continue reading ]]> This is the third part of Making Games in ActionScript 3 using FlashDevelop.

Okay kids. Lots of boring setup stuff in the first two parts. It’s time to get some graphics in the mix!

As a side note, since we’re using what’s called the mxmlc compiler everything I do in this tutorial can be done using whatever IDE you please as long as it uses that compiler, if you’re really into this whole command line thing you don’t even need the IDE.

Making your first class

Today we’ll start by making a new class for our first enemy. In FlashDevelop, right click the folder where you have your Main.as file, and select Add -> New Folder…
Name it enemies.

Now, right click that folder and select Add -> New Class…
Name your new class file Enemy.as

That will give us a bare bone class to start with. The first thing we will want it to do is to make it extend Sprite.

// Change this line:
public class Enemy {
// into this:
public class Enemy extends Sprite {

If you manually write it in FlashDevelop will import the Sprite class for you automatically. If it doesn’t, just add this after the package row:

import flash.display.Sprite;

So, what does this extends stuff mean?

Well, Flash has a whole bunch of basic classes for all kinds of things. Right now we’ll focus on the ones geared towards displaying stuff. A Sprite is basically a graphical object that can have children (ie you can add other stuff inside it, but more about that later). If you’ve used Actionscript 2 the best way to describe it is that it’s a MovieClip without a timeline, it only has one frame.

Getting the enemy on the stage

The stage in Flash is what most things revolve around, it’s the big white area you see when you run your application. It works in a tree style structure, your Main class is automatically added as a child to the stage, and anything you want to display you will have to add as a child to your Main or any of it’s children.

The first step to getting your enemy on the stage is to instantiate it. To do that we need to define a variable in our Main class to keep track of it:

Add this line before your Main function:

public var enemy:Enemy;

That gives us a place to store the Enemy.
Now, we need to actually create him too. We do that in the constructor for our Main class. The constructor is the function with the same name as the class, this runs when you create an instance of a class. We create an instance by using the new operator and then use addChild() to add him as a child of Main.

enemy = new Enemy();
addChild(enemy)

Only classes that extend certain other classes can be added as children, so make sure your enemy extends Sprite.

We’ll add a trace in the constructor for Enemy so we know everything is working properly:

By now your Main class should look like this:

package com.grapefrukt.tutorial.supergame {

	import com.grapefrukt.tutorial.supergame.enemies.Enemy;
	import flash.display.Sprite;

	public class Main extends Sprite {

		// a place to store the enemy
		public var enemy:Enemy;

		// this is the first code that is run in our application
		public function Main():void {

			// we create the enemy and store him in our variable
			enemy = new Enemy();

			// finally we add the enemy to the stage
			addChild(enemy)
		}

	}

}

If you try and run your code now it should output “I’m alive” to the output panel. That means we’re in business.
First we need to add some actual graphics for our enemy.

Getting graphics in there

A LeekAs previously mentioned there are several ways of getting graphics into the mix.

We’ll start with what I consider the best one, an swf. Make a new directory in the root of your project folder called assets and save this nice picture of a leek in there.

If you go back to FlashDevelop and open that folder in your Project panel you will notice that the leek.swf has a little plus to the side. Click that.

This allows you to explore what’s inside that flash file. What we want is the Leek symbol I’ve prepared. There’s a class in there too, but that’s just an empty placeholder so we can ignore that.

Now, open up your Enemy class and position your text caret on the line right before the declaration of the class itself (the one that starts with public class…) and double click the Leek symbol in the Project panel. This will insert the code needed to link that symbol to your class. So once you click compile the compiler will go into that file, extract those graphics and embed them into your new .swf

By now your Enemy class should look like this:

package com.grapefrukt.tutorial.supergame.enemies {

	import flash.display.Sprite;

	[Embed(source = '../../../../../../assets/leek.swf', symbol = 'Leek')]

	public class Enemy extends Sprite {

		public function Enemy() {
			trace("I'm alive");
		}

	}

}

If you compile now you will see a tiny bit of a leek peeking out from the upper left corner. This is because it’s still at the default position of 0, 0. To get it to show properly you will need to adjust it’s x and y position.

Add this after your row with addChild in your main class to change the position of your enemy:

enemy.x = 500;
enemy.y = 300;

Note that Flash uses a Cartesian coordinate system with it’s origin in the top left. In laymans terms this means that the coordinates 0, 0 is in the top left corner. A larger x value moves towards the right, a larger y value moves down.

Compile and run again and you should be able to see your leek just fine!
There’s a whole bunch of useful properties you can set this way, try fiddling around with alpha, width, height, and rotation. You can also try and add more leeks.

The whole project is available as a zip if you want to get a quick start.

Next time we’ll use png’s and jpg’s for graphics and do some basic interaction!

If you have any questions, just write a comment and I’ll respond as best as I can!

In part four we do some more embedding.

]]>
https://prototyprally.com/mgas3fd-3-getting-on-with-it/feed/ 24
MGAS3FD 2: The Beginning https://prototyprally.com/making-games-in-actionscript-3-using-flashdevelop-part-2-the-beginning/ https://prototyprally.com/making-games-in-actionscript-3-using-flashdevelop-part-2-the-beginning/#comments Wed, 04 Mar 2009 12:00:23 +0000 https://prototyprally.com/?p=159 Continue reading ]]> You have arrived at the second part of Making Games in ActionScript 3 using FlashDevelop.

Last time we got stuff setup. Not all that amusing really, just a tiny bit more setting up to go before we can get some stuff on the screen.

Your first project

Time to get your feet wet.
Go Project -> New Project…
What we want is an “AS3 Project”, normally the Preloader version is the way to go, but for clarity we’ll use the plain one this time around.

Set the name to whatever you please, I chose SuperGame, for location, use whatever seems suitable.

You can set a package name if you want too, this is just to keep your code separated from other people’s code if you ever use it in your games. The convention here is to use reverse domain naming for packages. So, by that logic I use com.grapefrukt.tutorial.supergame
You don’t need to own the domain or anything, it’s just to keep things separated. You can read more about this in the excellent ActionScript 3.0 Cookbook, but it’s not really that important for now.

That should be it for that dialog. Now, FlashDevelop will create a few template files for you.

As previously mentioned, the package structure is just a way to organize your code, and you can name it whatever you please. However, to enforce a good package structure Flash requires the files to be in folders corresponding to the package naming. So, with the folder src being our source “root”, and com.grapefrukt.tutorial.supergame my package structure, you can see the folders created to accommodate that. The compiler won’t be happy if you don’t put your code in the proper folders.

That’s enough about packages for now (and hopefully for the rest of this tutorial, they’re pretty boring)

Let’s move on to the code.

The file we’re interested in is the one called Main.as, open up that file using the Project panel.

For some reason FlashDevelop will include some code to make sure everything is loaded before running, but we can strip that out for now. Remove the whole init() function and the contents of the Main()

What you should be left with is something that looks like this (although your package may differ)

package com.grapefrukt.tutorial.supergame {

	import flash.display.Sprite;

	public class Main extends Sprite {

		public function Main():void {

		}

	}

}

This is about as bare-bones as it gets, Main will be what is normally called your document class. It needs to extend Sprite (there are a few other options aswell, but we’ll get to those later), this is one of the basic Display classes available in Flash.

Hello trace()

The trace() function is one of your best friends as a flash developer. Also, we need to make sure the debugging stuff works, so it’s a great place to start.

public function Main():void {
	trace("Hello world!");
}

Once you’ve gotten that little line into your Main() method, check that FlashDevelop is set to compile in Debug mode.
Also, make sure you’ve got your Output panel up, it’s in View -> Output Panel

If you got the External flash player, this is the time to set it up, go into: Project -> Properties… and set the Test movie-dropdown to “Play in external player”. This step isn’t required, you can stick with the default if you like that better.

Once that’s done, click the cute little arrow next to the debug/release field (you can also press F5 if you’re feeling “pro”)

If all goes well there should be a bit of chugging as the largish java driven compiler awakens from it’s slumber and then a loud explosion of impressiveness as it actually compiles your code.

A new tab/window should appear with your as of yet humble Flash game in it, it will be hard to tell if it’s working since we’re not doing any graphics yet, but if everything went as expected the Output panel should hold what we’re looking for:

[there's some more stuff here, but i cut it for brevity]
Build succeeded
Done (0)
[Capturing traces with FDB]
Hello world!

If the compile seemed to work nicely but you didn’t get that last “Hello world!”-line, you likely only have the Release player installed. It does (unsurprisingly) not bother with sending debug events to the debugger inside FlashDevelop. If so, go back to the first installment of this series and grab the link from there.

That’s it for the second part, next time we’ll be making some graphics appear!

If you want to go and do some reading on your own I really recommend the Flash documentation, it’s among the best docs I’ve ever seen.

As usual, any and all comments/questions are very welcome. Either as comments here, or if you’re so inclined  tweet me!

You can find part three right here.

]]>
https://prototyprally.com/making-games-in-actionscript-3-using-flashdevelop-part-2-the-beginning/feed/ 52
MGAS3FD 1: The Setup https://prototyprally.com/making-games-in-actionscript-3-using-flashdevelop-part-1-the-setup/ https://prototyprally.com/making-games-in-actionscript-3-using-flashdevelop-part-1-the-setup/#comments Wed, 25 Feb 2009 12:00:32 +0000 https://prototyprally.com/?p=149 Continue reading ]]> Welcome to the first part of Making Games in ActionScript 3 using FlashDevelop (just rolls of the tongue, doesn’t it?)

People keep asking me if I know any good tutorials for making games in Flash, and I keep answering that I don’t. Most of the one’s I’ve seen have only barely been ported from AS2, keeping the “old flash” mindset and not really making use of the new fancy stuff you can do in AS3. I think that’s a pity!

So, here’s my way of doing it.

This tutorial will assume some basic familiarity with Object oriented programming a graphical tool of your choice and general computer literacy. If anything is unclear, feel free to ask in the comments.

Downloading.

First, there’s some stuff we need to download:

  • The latest version of FlashDevelop (at the time of writing this was Beta9)
  • The Flex SDK (I use version 3.1.0, build 2710 but that shouldn’t matter too much)
  • A debug Flash player (I like the standalone one for development, but get the ones for the browsers too!)
  • Also, get Java 1.6+ if you don’t have it, the Flex compiler needs that

I use the Flash CS3 authoring tool to make my graphics, however, you can use any tool that can export swf’s and for the sake of completeness will show you how to use plain old png’s aswell. But the authoring tool is very hard to beat when doing animations, so consider getting it.
If you don’t have the Flash authoring there’s a trial for the CS4 version.

Installing.

Start with FlashDevelop, that should be a no-brainer.
(Now would be a good time to install Java if you don’t have that)
Then extract the SDK to whatever folder you’re comfortable with, all you will need to do is to point FlashDevelop to it later, then you can forget about it altogether.
Install the debug player for your browser, FlashDevelops internal player (IIRC) will use the version you install for IE.
Finally put the standalone Flash Player in a suitable directory, it will associate itself with the proper file formats when you run it, so just drop it wherever you want it and run it once.

Starting it up.

Now, it’s time to start FlashDevelop.
You should be greeted by a nice Start Page. The first thing we will need to do is to setup where we put the Flex SDK.
Go to Tools -> Program Settings… -> AS3Context -> Flex SDK Location (see the picture) and point it to the directory where you unpacked the SDK.

And that’s it. You’re ready to go. Go get yourself something unhealthy to eat as a celebration.

Next time we get started on our first project.

]]>
https://prototyprally.com/making-games-in-actionscript-3-using-flashdevelop-part-1-the-setup/feed/ 16