Boolean values: True or False

In the movie below the ball leaves the stage on the right and re-enters on the left. We use an if statement to determine when the ball has left the stage.
The ball has the registration point in the top left corner, so we know that it is off the edge on the right when ball.x is greater than the width of the stage. (stage.stageWidth) Review the exercise on movie clips and the stage if necessary.

Get Adobe Flash player

The code is shown below:

//The ball leaves on the right and reenters on the left
var dx:Number=3;  //initial speed in x direction

this.addEventListener(Event.ENTER_FRAME,moveBall);
function moveBall(e:Event): void {
	ball.x=ball.x+dx;
	if(ball.x>stage.stageWidth)  {
		ball.x=-ball.width;
	} 
} //moveBall

The if statement is used to make a statement or group of statement execute only under certain conditions. The word if is followed by a Boolean expression (something that can be evaluated as true or false) inside parenthesis. The statement to execute is immediately after the parenthesis with no semicolon. The format is:

if(Boolean expression) statement;

When you want more than one statement to execute when the Boolean expression is true, you must enclose the group of statement inside curly braces:

  if(Boolean expression) {
    statement1;
    statement2;
  } //end of if block

It is very easy to add another statement after an if and forget to add the curly braces. Most programmers use the curly braces even if there is just one statement in the block.

Experiment: Make the ball move to the left and re-enter on the right when it leaves on the left. Make it move from top to bottom or vice-versa.


Download the flash file

NEXT: Greetings: Boolean Operators