Screen Wrap a Moving Object

If Statement

Let's start by opening the ball_move.fla we've been working on. We may want to go back in case we ruin it, so click File > Save As and name our new file: ball_wrap

When we left off, our ActionScript window looked like this:

var speed:Number = 2;
var ball1:ball = new ball();
ball1.x=100;
ball1.y=150;
addChild(ball1);
addEventListener(Event.ENTER_FRAME,moveBall);
function moveBall(event:Event){
ball1.y += speed;
}

Our instance of ball, ball1, is added to the Stage at (100,150). From there it slowly moves down the screen.

We want ball1 to wrap to the top of the Stage (ball1.y=0) if it disappears off the bottom. The key word is IF. We need to run an if statement (also called a conditional statement) that continually checks to see if the Y value of ball1 is greater than the stage height. Actually, let's just see if it's greater than 300 for now.

Check this out... further explanations below:

Content on this page requires a newer version of Adobe Flash Player.

Get Adobe Flash player

The if statement begins with a logical test. The computer simply checks if one value is greater than, less than, or equal to a second value. It either is (true), or it isn't (false). In our case we are asking the computer to check if the value of ball1.y is greater than 300:

Now we tell Flash what we want it to do if the condition is true. We only want it to do one thing (ball1.y=0) and then we close the if statement with a right brace:

Flash is continually checking to see if ball1.y>300. If it is, then ball1.y=0 (so it moves to the top of the Stage). If ball1.y is NOT greater than 300, nothing happens:

Content on this page requires a newer version of Adobe Flash Player.

Get Adobe Flash player

If statements are the cornerstone of any computer programming language. I guarantee. Heck, you even use if statements in Excel!