Actionscript 3 Imports

September 7th, 2009 Rslegion No comments

Just a short post today, alot of you have been asking me why you need to use import statements when you’re code seems to work with or without them anyway.

Here’s the answer:

Most of the time developers / Tut writers get you to put in the import as good practice for when you start using classes. Everything used in a class has to be imported. This is usually to increase loading times and decrease file size.

Just for all you that wondered how to do an import, heres an example:

  1. import flash.display.*;

This will import everything in the /flash/display folder of you’re classpath

Categories: Other Tags:

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.

Mmmm…Cookies

August 18th, 2009 Matthew Lodge No comments

Time for a tutorial on PHP Cookies now. Every time you log into a site chances are you’re kept logged in with the help of cookies. Here I will show you a quick guide to cookies.

Syntax and rules.

setcookie(name, value, expire, path, domain);

Cookies must be set before any information is displayed on the page. So set your cookies before the tag and before you echo() or print() anything.

Ok let’s do this…

$expire=time()+60*60*24*6;
setcookie(”name”, “Matthew Lodge”, $expire);

The first part of the code sets an expiry date for the cookie. Here it is set for a week from when the cookie is set. (60 seconds, 60 minutes, 24 hours and 6 days). This cookie is called name and will have a value of Matthew Lodge.

This code is fine for setting a cookie but it will reset the cookie every time the page is refreshed. so to keep the current cookie we can use an if statement.

if(!isset($_COOKIE["name"])){
$expire=time()+60*60*24*6;
setcookie(”name”, “Matthew Lodge”, $expire);
}

This if statement checks whether the cookie exists and if it doesn’t it sets it.

Showing the value of a cookie is easy as shown below

echo $_COOKIE["name"];
//This will show the cookie that is called name

print_r “$_COOKIE”;
//This will print all the cookies in an array

To delete cookies you must set them in the past.

setcookie(”name”, ” “, time()-3600;
//Sets the cookie an hour in the past and destroys it.

So that’s cookies. Remember that some people do not have cookies enabled so always have a contingency plan if you want your application to be used by all.

Categories: PHP Tags: , ,

Declaring Variables In Visual Basic.Net

August 16th, 2009 Rslegion No comments

Variables in VB.Net are declared using this stereotypical programming format.

1.) The language must be told that you are declaring a variable.
2.) The name of the variable must be given.
3.) The variable type must be set.

In a language such as AS3 the code would look like this:

var myVar:String

In visual basic, as it is intended to be a language for beginners, the code would look like this:

dim myVar as String

In visual basic, the word var is unused and is replaced by dim. Why dim is used is have no idea.

However, you will notice that the colon in AS3 is replaced by as .

This is the beauty of learning Visual Basic.Net as a first programming language. If you know to replace the word dim with declare, and you know that a string is text.

This line of code is written in Pure English.

declare myVariable as text

You don’t need to be an expert to understand this. Do ya’?

This is the case with a lot of VB.Net code and is a reason why a lot of people opt to learn this language before moving on to more complex languages such as PHP or C++

Categories: Visual Basic.Net Tags:

PHP & mySQL: An intro

August 14th, 2009 Matthew Lodge No comments

The main benefit of PHP is its compatibility with mySQL. In this tutorial you will learn the basics of PHP and mySQL.

<?php

$connection = mysql_connect(’SEVER’, ‘USER’, ‘PASSWORD’);
$selectdb = mysql_select_db(’DB NAME’);

if(!$connection){
die(’Error connecting to database server’);
}
if(!$selectdb){
die(’Error connecting to selected database’);
}

//This code connects the page to the database ready to make a query. By holding //the connection functions in variables we can create a custom error message.

?>

Next I will teach you about query syntax. A basic query follows this rule:

SELECT name FROM table

The SELECT tells mySQL to return a value from the specified field (in this example the field is called “name”). Alternatively you can use the * wild card. This requests all the information from the table selected in the FROM parameter.
The FROM tells mySQL which table in the database the field can be found.

For example to retrieve a name from a table called users the code would look like this:

$query = mysql_query(”SELECT * FROM users”);
if(!$query){
die(’Error in query’);
}

while($row = mysql_fetch_array($query)){
echo $row['firstname'];
echo “<br />”;
}

First of all we query the database for a set of results. Then we echo out all the results using a WHILE loop. The $row variable contains all the information so we specify what information we want from the query using ['']. This returns the information from that field.

The full code

<?php$connection = mysql_connect(’SEVER’, ‘USER’, ‘PASSWORD’);
$selectdb = mysql_select_db(’DB NAME’);

if(!$connection){
die(’Error connecting to database server’);
}
if(!$selectdb){
die(’Error connecting to selected database’);
}

$query = mysql_query(”SELECT * FROM users”);
if(!$query){
die(’Error in query’);
}

while($row = mysql_fetch_array($query)){
echo $row['firstname'];
echo “<br />”; //Add a line break for formatting
}

mysql_close($connection);

?>

The mysql_close() function will close the connection to the database

So as you can see PHP and mySQL can be a formidable combination. By integrating them into your site you can give users an enhanced experience.

Categories: PHP Tags: , ,

An Introduction To Visual Basic.Net

August 11th, 2009 Rslegion No comments

Visual Basic, in my opinion is an extremely easy programming language to learn. It where i first started many years ago. One of the the reasons that visual basic is easy to learn on a beginner level is because most of its commands are in the English language.

For Example in Actionscript 3, you’ll see code like this:

if(someCode == true)
{
someMoreCode = false
}

Whereas in Visual Basic.Net, the same code would look more like this:

If someCode = true Then someMoreCode = false

As you can see, Visual basic code looks much more simple to the beginner than AS3. Even though both example do exactly the same thing.

This is the reason why i recommend learning Visual Basic.Net as you’re first programming language.

Check back regularly for more Visual Basic.Net tutorials.

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: