Helpful Code

Keeping Score

You will need a variable to hold the score.

First you must declare the variable. In this case the variable is called score.

var score

You may wish to initialize the variable as you declare it.

var score = 1000

You will need a textbox in which you display the score. In this example the textbox is called tScore. When creating your textbox be sure that it is large enough to display your score, format your text, name the instance and set the anti-alias to Display Device Fonts.

To display the score you will need code similar to this:

tScore.text=score

To increase or decrease the score you will need the following code. In this example the variable score is used and the variable will increase or decrease by 20. This code will be triggered by the event of your choice. It will appear most often within an if statement or some other decision structure.

score-=20;

 score+=20;

You will also need to update the score by adding the code after the score is changed.

tScore.text=score

Limiting Stage Boundaries

To keep an object within  stage boundaries you must use some simple math to create a new function. In this example the function is called limitStageBorder, the object that is being kept within the boundaries is called object.

function limitStageBorder(object:MovieClip) {

   // Variables are declared that store half the objects width and height.
var objectHalfWidth:uint=object.width/2;
var objectHalfHeight:uint=object.height/2;

// If the object moves beyond the stage width, the object is pushed back by adding or subtracting the half the width of the object.
if (object.x+objectHalfWidth>stage.stageWidth) {
object.x=stage.stageWidth-objectHalfWidth;
}
else if (object.x –  objectHalfWidth <0) {
object.x=0+objectHalfWidth;
}

// If the object moves beyond the stage height, the object is pushed back by adding or subtracting half of the height of the object.
if (object.y-objectHalfHeight<0) {
object.y=0+objectHalfHeight;
}
else if (object.y + objectHalfHeight > stage.stageHeight) {
object.y=stage.stageHeight-objectHalfHeight;
}
}

You will need to add the limitStageBorder() function to enable the limiting of the stage boundaries. Place the line of code inside the function that controls the objects movement function.

limitStageBorder(object);