Archive

Archive for the ‘Actionscript 3’ Category

Useful Functions (Tips)

September 1st, 2009 Matthew Lodge No comments

The following code generates an array then adds all the numbers in the array together. Really quite useless.

However the methods used to create this snippet are extremely useful.

Here I break them down.

var randomNumber:int = new int();
var myArray:Array = new Array();
var total:int = new int();
var totalNumbers:int = new int();
totalNumbers = 10;
First of all I declare some variables by doing this the variables can be used in and outside of functions. This is called variable scope
function generateNumbers(){
 for(var i:uint; i<totalNumbers; i++){
Here I start a loop with a variable as the number to count to. This lets you modify the code easily
randomNumber = Math.ceil((Math.random()*(5^i^3)));
Here is the code that generates the random numbers. Math.ceil() rounds the numbers up to an interger. Math.random() generates a random number with is then multiplied by 5 to the power of "i"
myArray.push(randomNumber);
The push() function in an array add the value in the argument as a new value in the array.
}
 for(var il:uint; il<totalNumbers; il++){
 total += myArray[il];
Here the variable "il" counts up until it equals "totalNumbers" whilst it does that it cycles through the array and adds the values to the variable "total" using the operator +=
}
}
generateNumbers();
Calling the function
trace(myArray);
trace(total);
Here I trace to the output panel in flash to check the function is working. It is useful for debugging to put trace() functions in to see where the code is failing So as you can see AS3 has many useful functions to help cut the time spent coding. Use these and you're on your way to becoming an ace programmer.
Categories: Actionscript 3 Tags: , , ,

Creating Custom Classes And Packages In AS3

August 31st, 2009 Rslegion No comments

Custom classes are one of the new features in AS3 and they are very useful to competent Actionscript 3.0 coders.

The main idea of the custom class is just like that of a custom function. Both of which were designed to:

  • Help organize code
  • Rid of the need for repeating code
  • Increase application performance

On a very basic level, both classes and functions both do this, however classes allow the user to be much more dynamic with there code.

An empty class looks like this:

  1. package
  2. {
  3. import flash.display.MovieClip;
  4. public class ExampleClass extends MovieClip
  5. {
  6. public function NewClass()
  7. {
  8. }
  9. }
  10. }

The order of code for a class looks like this:

1.) Declare ‘package’
2.) Imports (Everything needs to be imported in a package / class)
3.) Declare class name + its parent type (”MovieClip, Sprite, EventListener)
4.) Main function (Run on class initiation)

This is the basics of custom class syntax, in the next tutorial, i will explain the use of these classes and how the improve you’re coding.

Categories: Actionscript 3 Tags: ,

Setting Up The Box2D B2World Object

August 26th, 2009 Rslegion No comments

When coding Box2D the first thing that needs to be setup is the Box2D world, known as the b2World.

Inside the b2World object, we set the attributes for:

  • Size – How large we want our b2World to be.
  • Gravity – How strong we want our gravity to be.
  • Sleeping Object – Used to speed our app.

Here is an example of how to set up a b2World:

public function setupWorld ():void
{
// Setup our universe size
var universeSize:b2AABB = new b2AABB();
universeSize.lowerBound.Set (-3000 / RATIO ,-3000 / RATIO);
universeSize.upperBound.Set (3000 / RATIO ,3000 / RATIO);

// Setup our gravity
var gravity:b2Vec2 = new b2Vec2(0 , 9.8);

// Setup sleeping
var ignoreSleeping:Boolean = true;

// Create our world
myWorld = new b2World(universeSize,gravity,ignoreSleeping)
}

Firstly we set our attributes for the size of our world, the universe size is set using a class called the b2AABB. It is basically a rectangle and the parameters UpperBound and LowerBound must be Set. In this example we our applying physics between -3000 px and 3000 px.

After that we must set up our gravity. The gravity is of a b2Vec2 class. The parameters required are X and Y. In this example, as all box2D lengths and in meters,the gravity has been set to 0 meters per second right and 9.8 meters per second down.

Next we have to create a variable to tell box2D whether to ignore sleeping objects. This is mainly just for performance. When an object is not moving, it is classed as sleeping. When an object is sleeping box2D can ignore it for performance increase. Usually, you’ll want this on.

Lastly we must actually create our world. This is of a b2World class and has the parameters:

  • world:b2AABB
  • gravity:b2Vec2
  • doSleep:Boolean

That sums up our tutorial on setting up the Box2D B2World object, in our next tutorial in this series we will look at how to create static objects in box2D

Categories: Actionscript 3, Box2D Tags:

An Introduction To The Box2D Physics Engine

August 22nd, 2009 Rslegion No comments

This is the first of a range of tutorials covering use of the open source Box2D physics engine. This engine the physics engine of choice of AS3 and has more than likely been used to create some of you’re favorite games like ‘Fantastic Contraption’ and ‘Super Stacker’

I know what you’re thinking,

How am I going to learn how to code all these gravity and physics things?

The great part is, all the actual physics of the game have already been coded in the Box2D classes already. All we have to do is create the object, know as bodies in the Box2D world, and set there attributes!

In this tutorial i will cover the basics of Box2D and how it works.

The Difference

If you’re already an competent AS3 Coder, which you should be if you’re learning box2D, there are a few fundamental differences to the way things work.

In normal AS3 coding you have you’re sprites and MovieClips, they:

  • Are Smart
  • Calculate where to move by themselves
  • Have an Event.Enter_Frame attached to them

However sprites in Box2D are completey different, they:

  • Aren’t so smart
  • Go where box2D tells them to go

That’s the main difference when coding Box2D, its mainly because the engine is ported directly from the world of C++

In the next tutorial, i will cover how to set up Box2D so it knows where abouts on our flash movies that physics should be applied. Also know as the B2World.

Creating A Simple Preloader In As3

August 7th, 2009 Rslegion No comments

For all you that have been follow this blog from the start, you’re probably up to the point where you can create games and applications. For the large of these loading times can be a problem. After all, the chances of someone sitting there looking at a black screen for a minute while you’re game loads is unlikely.

This is where a preloader comes in, for everyone that doesn’t know, a preloader is a small piece of code that executes almost instantly and tells you how long until the rest of the game or app is loaded.

In this tutorial, i will show how to make one.

Step 1
Create a dynamic text field. Give it an instance name of percentComplete

Step 2
In code view, add these 2 lines:

stop();
this.stop();

These will the our app from continuing while loading commences.

Step 3
Add an event listener that is triggered each time part of our app loads and one for loading completion:

this.loaderInfo.addEventListener(ProgressEvent.PROGRESS, updatePercent);
this.loaderInfo.addEventListener(Event.COMPLETE, loadComplete)

Step 4
Create our function and work out the percentage complete:

function updatePercent (e:ProgressEvent)
var percent:Number = (e.bytesLoaded / e.bytesTotal) * 100;

To work out the percentage complete will take the amount of app we have loaded and divide it but the total size of the app. Then times by 100.

Step 5
Add in a line to set the text of the textfield underneath the previous:

percentComplete.text = (percent + “%”)

Step 6
Create a function to handle the loading completion and move to the next frame.

function loadComplete (e:Event)
{
this.removeEventListener(ProgressEvent.PROGRESS, updatePercent)
gotoAndStop(2)
}

And there you have it, a simple preloader in AS3

Categories: Actionscript 3 Tags:

Dynamic Text In Flash Cs3

August 6th, 2009 Rslegion No comments

There are 3 different types of TexArea you can use in Flash CS3.

  • Static Text
  • Dynamic Text
  • Input Text

The Input Text and Dynamic Text can be given instance names so that they can be referenced in code.

You can change the type of text area in the properties menu just above the instance name.

When referencing you’re text are in As3 you can change the text of a dynamic textarea like this:

myDynamicText.text = “Hello World”
Categories: Actionscript 3, Flash CS3 Tags:

Complex / Nested Arrays In AS3

August 5th, 2009 Rslegion No comments

This tutorial may be complex for a programming novice

In a previous tutorial we looked at the use of Arrays in As3 and how we can incorporate them into and games and applications.

In this tutorial we will look at how the more complex arrays, aka nested arrays work and why they are useful

Here is an example of a simple Array:

var myArray:Array = new Array ([100],[50])

And here is an example of a Nested Array:

var myNestedArray:Array = new Array ([ [100], [500] ], [ [200], [100] ])

I know that it looks very complex but once you understand the syntax of the array it becomes a lot easier.

If you look closely at the array, you will notice that it is actually split into 2 separate parts.

The first being:

[ [100], [500] ]

The second being:

[ [200], [100] ]

If you were to imagine that the 2 end square brackets on each part were actually parenthesis the entire array would look like this:

( ( [100], [500] ), ( [200], [100] ) )

Hopefully now this is starting to make a bit more sense, a nested array is basically many arrays placed one after the other as a single array. All the square brackets that we imagined as parenthesis just separate the arrays from each other.

If you’re still confused let me show you how you access the values in the code:

var myVariable:Number = myNestedArray[0] // [1]


In order to retrieve just one variable from this array you must include the second number, in this case [1], however for this example i am commenting it out.

I was talking earlier about the nested array being split into 2 parts. The first number we use selects this part. In this example myNestedArray[0] would retrieve the first part of the array,
[ [100], [500] ]

Now. If we again imagine that the end square brackets are parenthesis we are now left with a regular array like this:

( [100], [500] )

This is what the second number is for. As we used [1] it selects the 2nd value which in this case is 500

this means that in this case the uncommented value of myVariable would be 500.

I know that this was an extremely complicated tutorial, if you have any questions on this please feel free to leave them in the comments and i will gladly answer them.

Categories: Actionscript 3 Tags:

Creating You’re First Game In As3 Part 1

August 4th, 2009 Rslegion No comments

Sorry about the wait for this one guys, been on holiday for a while.

So now you know some basic AS3 code, I bet you’re itching to create you’re first game and receive some comments about it.

In this 3 part series i will show you how to create a very simple game from scratch and were to showcase you’re game for in my opinion, the most helpful comments

Lets get down to it!

Our game will consist of 2 text areas, 1 dynamic and 1 static. Go ahead and create these using the toolbar on the left. The type of text area, Eg. Dynamic, Static; can be changed easily in the properties menu.

Text Type

Place the dynamic text in the bottom center of the screen and the static text in the top center of the screen.

Once you’ve done that, create a button from the components menu and place it in the center of the screen.

You’re screen should now look something like this:

Canvas

Change the parameters of you’re button so that the text says something along on the lines of “Click!” or “Hit!” and name the button to ButtonClick

Change the name of the dynamic text box to ClickCount

After completing this steps, you’re ready to move onto the next part of the tutorial that i will release shortly.

Categories: Actionscript 3 Tags:

As3 Keyboard Controls

July 19th, 2009 Rslegion 1 comment

In many apps and games created in AS3 there is the need to use the keyboard. Unfortunately in AS3 this has been made more complex than it needs to be. In this tutorial i will show you how to make use of the keyboard in AS3.

The use of the keyboard in actionscript 3 is made available through the use of the EventListener.

Here is an example of the keyboard event listener.

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown)

This event listener will run when any key on the keyboard is pressed down. To make an operation run only when a certain key is run we have to use an If statement inside the keyDown function.

function keyDown (e:KeyboardEvent)
{

if (e.keyCode == 38)
{
key_Up = true;
}

}

When referencing keys on the keyboard they have to be referenced via there keycode. In this example we are using keycode 38 which is the up key.

The If statement here sets the variable Key_Up to true. This variable could be used to move something in a Event.ENTER_FRAME event listener.

function moveShip (e:Event)
{

if (Key_Up == true)
{
myShip.y += 10
}

}

This will move my rocket ship variable, myShip up 10 pixel per frame if the Key_Up variable’s value is true.

Here are some more Keycodes to help you out:

37 – left
38 – up
39 – right

32 – space

Categories: Actionscript 3 Tags:

As3 FOR loops

July 18th, 2009 Rslegion No comments

In any coding language there is always a need for loops; small bits of code that are rerun with only 1 or 2 small changes. In As3 this has been made extremely simple.

Here is of an example of a FOR loop:

for (var i = 0; i < 10; i++)
{
// Some Code
}

Loops work in a similar way to functions, any code inbetween the to curly brackets will be run each time the loop commences.

This loop will run 10 times in all. The first part of the loop, var i = 0; , creates the temporary variable in which the code inside the loop will most likely use.

The second part of the loop is the criteria in which the loop will run, in this case, i < 10;
This loop will run while the variable i is less than 10.

The third part of the variable, i++ tells the loop what to do each time the loop completes, if this part is coded wrongly, the loop could become infinite and could crash you’re editor.

This is one of the reason’s you are encouraged to save you’re work before each compile.

Categories: Actionscript 3 Tags: