Deprecated: Assigning the return value of new by reference is deprecated in /var/www/www.webgamemagazine.com/www/wp-settings.php on line 468

Deprecated: Assigning the return value of new by reference is deprecated in /var/www/www.webgamemagazine.com/www/wp-settings.php on line 483

Deprecated: Assigning the return value of new by reference is deprecated in /var/www/www.webgamemagazine.com/www/wp-settings.php on line 490

Deprecated: Assigning the return value of new by reference is deprecated in /var/www/www.webgamemagazine.com/www/wp-settings.php on line 526

Deprecated: Assigning the return value of new by reference is deprecated in /var/www/www.webgamemagazine.com/www/wp-includes/cache.php on line 103

Deprecated: Assigning the return value of new by reference is deprecated in /var/www/www.webgamemagazine.com/www/wp-includes/query.php on line 21

Deprecated: Assigning the return value of new by reference is deprecated in /var/www/www.webgamemagazine.com/www/wp-includes/theme.php on line 618

Deprecated: Assigning the return value of new by reference is deprecated in /var/www/www.webgamemagazine.com/www/wp-content/plugins/wp-o-matic/wpomatic.php on line 2072
Web-Game Magazine - the best free action/adventure web games and casual games, reviewed daily » Flash Tutorials

Great Games

Bow Street RunnerQuadradiusChick Chick BOOMChromaBlastMore BeerSeven Deadly SinsAgent Wing DefendersSomething AmissNewgrounds RumbleRed BaronOsiris IIIvan Drago: Justice Enforcer

Worth Checking Out

Zodiac TowerSolarsaursPapa LouieCare The MonsterUFO ManiaSanta's Sweat ShopStunt Bike DrawSlingMaggotzRailway To HeavenHead GamesIndestructoTankWorld Domination BattleSnake ClassicGo.Arrival In HellWarp ForestNodes

Link to us

Here are some button images you can download. We have buttons for fans, and buttons for developers that have been featured on the site.


 

Recent Visitors


July 10th, 2008

Learning AS2 Classes Part 1 - Posted by Psycho Goldfish

I know that ActionScript 3.0 is the big thing now, but for a lot of flash developers who started out as hobbyists with more art background than programming, a strict/rigid language is really imposing.

Because of this intimidation factor, many of today’s most creative flash developers still work with ActionScript 1 and 2, coding everything on their timelines and in #include files, but with AS3 looming overhead, they are looking to get their feet wet in the pool of structured programming.

For me, if I hadn’t learned how to work with AS2 classes, AS3 would definitely be way over my head, so I thought I’d take a little trip back in time today and write a long overdue tutorial for my olschool homeboys out there that want to learn what classes are all about.

Before you learn how to make a class, I should probably explain what a class is. Essentially a class is a type of object that has properties and methods for handling some sort of functionality.

Some of you are just blinking at the screen saying “durr.. wut?” right now, so let me compare it to something you SHOULD be familiar with… a movieclip.

In Flash, MovieClips have properties (_x, _y, _width, etc…), and they have methods (play, stop, gotoAndPlay, gotoAndStop, etc…). Properties have a value you can look at and sometimes change, and methods preform some kind of action.

Classes are a lot like this, only you have to create all the properties and methods, define how they can be accessed, and handle how they return things.
So now you have an over simplified idea of what a class is, lets go ahead and make one.

Open up flash and start a new Actionscript File.

The class we are going to create is going to be called ‘Calculation’, so we need to define this by typing:

class Calculation {

}

Anyone who has ever made a decent flash game has probably had to use the pythagorean theorem at some point to figure out the distance between two movie clips or points. We are going to add a method to our class that handles this for us.

class Calculation {

public static function getDistance(obj1, obj2)
{

var x1:Number;
var x2:Number;
var y1:Number;
var y2:Number;if (typeof(obj1) == ‘movieclip’) {

x1 = obj1._x;
y1 = obj1._y;

} else {

x1 = obj1.x;
y1 = obj1.y;

}

if (typeof(obj2) == ‘movieclip’) {

x2 = obj2._x;
y2 = obj2._y;

} else {

x2 = obj2.x;
y2 = obj2.y;

}

var xd:Number = x1-x2;
var yd:Number = y1-y2;
var zd:Number = Math.sqrt((xd*xd)+(yd*yd));

return (zd);

}

}

You are probably familiar with how functions work, so for the most part this method should make sense to you. What you probably don’t quite follow yet is what ‘public static’ is needed for.

In class functions there are 2 levels of function access: Public and Private.
Public functions can be called from any actionscript, be it on your timeline or in another class

Private functions can only be called from inside the class itself.

There are also 2 methods of function use: object and static.

A static function can be used directly like a command, where an object function only works on an instance of a class (we’ll get into that later).

Inside this function you will also see lines like “var x1:Number;”.

In a class all variables need to be declared. This strict coding is one of the things that makes classes hard to learn for some people, but there are reasons for why this is necessary.

Classes are basically a set of rules and procedures that only need to be loaded once. In order for the one-time load to be effective, the rules need to be crystal clear and flash needs to know what variables the class will be using in any given function.

By simply typing “var x1″ we tell flash that this class will be using a variable called ‘x1′ inside the function. By adding “:Number” we are also telling flash that x1 will always be a number datatype.

You don’t need to assign a datatype to a variable, but if you know for certain it will always be a certain data type it’s a good practice to get into and it helps define the rules of your class for faster performance.

If you don’t know how the value of a variable is going to be set, it’s a good idea to define them at the start of the function. In this example, we don’t know if we are pulling from a movieclip or a point object, so I pre-declared x1, x2, y1 and y2.

Once I do get those variables set, you will see I declare xd, yd and zd while giving them a value. I call this declaring on the fly, and I did it this way because those equations will ALWAYS be how these vars are set.

Finally, at the end of the function we return ‘zd’ wich is our distance value. Whenever you use a return statement the function will always end no matter how much code you have typed afterward.

So there we have it, our first class. So how the fuck do we use it?

First we need to save the file as ‘Calculation.as’ (and yes it’s case sensitive). The name of the file must be an exact match for the class name. For this tutorial we will save this as “C:\flash_tutorial\Calculation.as” (but you can use any folder you want).

To use the class, open a new Flash Movie, and on frame 1, add the following code:

import flash.geom.Point;
point1 = new Point(0,0);
point2 = new Point(100,100);
pointDistance = Calculation.getDistance(point1, point2);

trace(”the distance between the 2 points is “+pointDistance);

We are using the bundled point class to compare 2 points, but you could also pass in two instance names for 2 movieclips and it would pass the distance between their _x/_y values.

If you test your new movie without saving it, you will get an ‘undefined’ value for pointDistance. This is because flash can’t find your class.

Save the .fla file to “C:\flash_tutorial\test_class.fla” (or whatever folder you saved your class to).

Now when you test it, you will get “the distance between the 2 points is 141.42135623731″ in your output window.

When you type “Calculation.getDistance” in your script, flash knows you do not have an object or movieclip called Calculation, so it looks first in the working folder for Calculation.as, and if it finds it, it automatically includes it.

If it can’t find the file in the working folder, it moves on to the global folders. By default this is: C:\Documents and Settings\{USER}\Local Settings\Application Data\Macromedia\Flash 8\en\Configuration\Classes

That’s a rather deep location to be saving your work to. Fortunately Flash lets you add custom class paths.

In Flash, click Edit->Preferences, then select ActionScript from the category list. Press the ActionScript 2.0 Settings button at the bottom of the panel and hit the + button to add a class path. Type “C:\AS2 Classes” and hit OK.

Now you can make a folder called “AS2 Classes” on your C: drive, and move Calculation.as to the new folder.

Now, no matter what flash movie you are working in, you will be able to use the new class. You never have to type out code for the pythagorean theorem again!

Okay, so let’s open Calculation.as back up and add in another function:

class Calculation {

public static function getDistance(obj1, obj2)
{

var x1:Number;
var x2:Number;
var y1:Number;
var y2:Number;if (typeof(obj1) == ‘movieclip’) {

x1 = obj1._x;
y1 = obj1._y;

} else {

x1 = obj1.x;
y1 = obj1.y;

}

if (typeof(obj2) == ‘movieclip’) {

x2 = obj2._x;
y2 = obj2._y;

} else {

x2 = obj2.x;
y2 = obj2.y;

}

var xd:Number = x1-x2;
var yd:Number = y1-y2;
var zd:Number = Math.sqrt((xd*xd)+(yd*yd));

return (zd);

}

public static function getAngle(obj1, obj2)
{

var x1:Number;
var x2:Number;
var y1:Number;
var y2:Number;

if (typeof(obj1) == ‘movieclip’) {

x1 = obj1._x;
y1 = obj1._y;

} else {

x1 = obj1.x;
y1 = obj1.y;

}

if (typeof(obj2) == ‘movieclip’) {

x2 = obj2._x;
y2 = obj2._y;

} else {

x2 = obj2.x;
y2 = obj2.y;

}

var radians:Number = Math.atan2(y2-y1, x2-x1);
var degrees:Number = radians * 180/Math.PI;

return(degrees);

}

}

Now we have a method for figuring out the angle that 2 items are at from each other. You can see the basic function structure and declarations are the same. You can also see the chunk of code I am using to set x1, x2, y1 and y2 is the same.

For that matter, the methods to look at obj1 and obj2 and determine if they are movieclips or not is also the same.

Redundant code like this is rather inefficient, so we are going to make a new function to handle that routine and clean our code up a bit.

class Calculation {

public static function getDistance(obj1, obj2):Number
{

var firstItem:Object = getCoords(obj1);
var secondItem:Object = getCoords(obj2);

var xd:Number = firstItem.x-secondItem.x;
var yd:Number = firstItem.y-secondItem.y;
var zd:Number = Math.sqrt((xd*xd)+(yd*yd));

return (zd);

}

public static function getAngle(obj1,obj2):Number
{

var firstItem:Object = getCoords(obj1);
var secondItem:Object = getCoords(obj2);

var radians:Number = Math.atan2(secondItem.y-firstItem.y, secondItem.x-firstItem.x);
var degrees:Number = radians * 180/Math.PI;

return(degrees);

}

private static function getCoords(obj):Object
{

var coords:Object = new Object();

if (typeof(obj) == ‘movieclip’) {

coords.x = obj._x;
coords.y = obj._y;

} else {

coords.x = obj.x;
coords.y = obj.y;

}

return(coords);

}

}

First thing you should notice in our new getCoords function is that is is a PRIVATE function. If you try calling Calculation.getCoords() from your timeline, you will get an error. This function is only going to be used by this class.

Now our code is clean and efficient and, in a round-about way, we have added new commands to Flash. We can use Calculation.getDistance() and Calculation.getAngle() in any movie we want without ever having to type those bits of code again!

Congratulations, you have taken the first step into the land of writing classes. In the next tutorial I will talk about object classes. Before you go, feel free to download the samples that go with this tutorial!

Bookmark this page on Digg, Kinja, FURL, Redit & other sites

July 10th, 2008

Simple Actionscript Camera - Posted by Psycho Goldfish

While surfing around I noticed a few people had been asking about ways to move the camera around in their flash movies without using tweens.

I’m fully aware that there are some great solutions to this problem, but they may be a bit more than what people need, so I decided to whip off a very simple solution that can be used by entry-level programmers, or people with no programming background at all.

In order for this to work you will need to contain your actual animations in a movieclip. This is typically preferable to scenes anyway, so most animators probably do this anyway.

In this movie clip, create a new layer for the camera control. Now all you need to do is download simple_camera.fla and grab the MovieclipCameraControl object from the library and paste it into the new layer of your movie.

Now, whenever you make a new keyframe and re-position the camera reticle, your movie will automatically pan itself until the camera is centered, or the edge of your scene reaches the edge of the stage.

If you are interested in how it works, read on.

Unlike more robust class-based solutions, this uses actionscript contained in a movieclip for simple drag and drop functionality.

Inside of this clip, the code looks like this:

// hide the camera indicator
this.gotoAndStop(2);// grab the movie and scene dimensions
bounds = _parent.getBounds(_parent);
sw = Stage.width;
sh = Stage.height;// set the default pan speed
panSpeed = 5; //(1-100)

// main camera routine
onEnterFrame = function() {

    // grab x/y position of the camera focus
    x = this._x;
    y = this._y;// make sure the camera isn’t going to show beyond the scene’s edge
    if (x < bounds.xMin + (sw/2)) {

      x = bounds.xMin + (sw/2);

    } else if (x > bounds.xMax - (sw/2)) {

      x = bounds.xMax - (sw/2);

    }
    if (y < bounds.yMin + (sh/2)) {

      y = bounds.yMin + (sh/2);

    } else if (y > bounds.yMax - (sh/2)) {

      y = bounds.yMax - (sh/2);

    }

    // get relative positing of the camera compared to the root movie
    myX = x + _parent._x;
    xdst = (sw/2)-myX;

    myY = y + _parent._y;
    ydst = (sh/2)-myY;

    // get the actual distance from the current focus to the camera’s target coord
    dst = Math.sqrt((xdst*xdst)+(ydst*ydst));

    // only move the camera if the distance is noticable, this will prevent jitter, and save some cpu.
    if (dst > 0.5 or dst < -0.5) {

      // calculate the pan speed
      spd = dst*(panSpeed/100);// calculate horizontal and vertical speeds based on pan speed
      yspd = (ydst/dst)*spd;
      xspd = (xdst/dst)*spd;// move the scene accordingly
      _parent._x += xspd;
      _parent._y += yspd;

    }

}

First thing that happens in this script is I jump to a blank frame. You may be asking why I don’t just set the _alpha value to 0 to hide it. We’ll get to that in a minute.

Next I run getBounds on the scene clip so I will know where all the edges are and can prevent the camera from panning beyond them.

getBounds returns an object with the values xMin, xMax, yMin, yMax in relation to whatever target you specify. In this script I only need the relation within the scene itself since I will be comparing them to the _x/_y position of the scene as those values change.

Once I have this information set, I put in a default panSpeed value. this is a percentage value and the camera will move this % of the distance from the current focus, to the desired focus on each frame. 100% would simple auto focus without any panning, while 1% would pan very slowly.

The guts of the camera are in an enterFrame loop.

First you will notice I an grabbing the _x/_y data and putting in in x and y rather than just using _x and _y throughout the script.

This ties in to why I didn’t set _alpha to 0. Once you use actionscript to change any movieclip property, that movieclip will ignore any positional changes you make on the timeline and only be moveable with actionscript. Because this is designed to be used by non-programmers, I had to make sure it would work by reading the x/y data based on where the animator places the camera in any given keyframe.

Now that I have the x/y data captured, i compare it to the screen boundaries and adjust them if they are going to allow the camera to show beyond the scene edges.

The next step is to compare the relative position of the camera and scene to see how far away it is from being centered on the main stage. This gives me a distance value for x and y, wich I then use to calculate an overall distance.

Using this overall distance I can check to see if there is at least a half pixel of space to adjust to. Any less than that and the viewer won’t even notice the adjustment, and sometimes will actually see some jitter.

If the distance is enough to warrant a screen shift, we calculate the speed to move the scene based on the overall distance and panSpeed setting. We then get the % of the overall distance that it needs to move horizontally and vertically, and multiply that by the speed we calculated.

This will make the camera pan in a straight line to the new target, rather than having it move on independant x and y axis’. If we didn’t do this, you would see it pan in one direction and stop, while the other direction keeps going, and would lose the natural flow of the camera.

Once all these calculations are done, we simply move the scene and the process repeats as needed.

That’s all there is to it.

Bookmark this page on Digg, Kinja, FURL, Redit & other sites

Next Entries »