Skip to main content

Home

Daniel C. Fergus

Artist & Educator

VCB-331 Rich Media I

Conditionals (Flash AS3)

Introduction

A conditional is a statement of code that compares two (or more) pieces of data and then makes a decision based on some prescribed set of criteria. For example, let's say you create an object that lights up when a user achieves a certain score on a game; you would use a conditional to check the score and see if it's time for the object to light up. There are different kinds of conditionals, but the most common is the if statement. It's typically structured like this:

if (some condition is met) {
    do something;
}

Or, to be more specific:

if (score == 100) {
    gotoAndStop ("end")
}

So let's make something that uses conditionals.

Proximity Checker

This exercise is based on one found in the text, Foundation Flash CS3 for Designers. We'll create a simple program that causes a star to change opacity when it's dragged near another object.

  1. Launch Flash and open a new (AS3) Flash file.
  2. Create two objects—a star and a circle. Convert each to a movie clip and give them the instance names star_mc and circle_mc.
  3. Create a new layer and call it actions.
  4. First we'll get the star working. We'll create a couple of listeners and also give the star a buttonMode so the little hand will appear when the user mouses over it:
    star_mc.addEventListener(MouseEvent.MOUSE_DOWN, dragStar);
    star_mc.addEventListener(MouseEvent.MOUSE_UP, dropStar);
    star_mc.buttonMode = true;
  5. Now the first function:
    function dragStar(myEvent:Object):void { 
        star_mc.startDrag(); 
        var topPos:uint=this.numChildren-1; 
        this.setChildIndex(star_mc, topPos); 	
        star_mc.addEventListener(MouseEvent.MOUSE_MOVE, positionCheck); 
      }
    This function does three things: first it causes the object to move; second it sets the star's position to the top of the stacking order (which is not that critical in this case, but a good thing to do whenever you're making draggable objects); and third, it adds a MOUSE_MOVE listener. This listener calls its function whenever its associated object is being moved by the mouse.
  6. Now the release function:
    function dropStar(myEvent:Object):void {
        star_mc.stopDrag(); 
        star_mc.removeEventListener(MouseEvent.MOUSE_MOVE, positionCheck); 
      }
    Note that this function in addition to stopping the object's movement, removes the listener added in the previous function, which is no longer needed once the object is released and would just slow things down.
  7. Now for the positionCheck function:
    function positionCheck(myEvent:Object):void { 
        if (star_mc.x > circle_mc.x) { 
            star_mc.alpha = 0.4; 
        } 
    }
    Finally we get to the conditional. Here we have an if statement that is used to check the position of the star. Specifically, it's comparing the x (horizontal) position of both objects. If the x position of the star is greater, that is, it is further to the right of the circle, the star will dim (its alpha will be reduced).
  8. But notice what happens when the star is dragged back to the left of the circle—it stays the same. To restore the star we need to add another element to the conditional—an else statement that describes the proper state of the star if the condition is not met. Add the new code in black:
    function positionCheck(myEvent:Object):void { 
        if (star_mc.x > circle_mc.x) { 
            star_mc.alpha = 0.4; 
        } else { 
            star_mc.alpha=1; 
        } 
    }
    Now if that condition is not met, the star's opacity remains at 1 (100%). Try it out.
  9. Okay that's cool, but all it does is check to see if the star is dragged past the circle. What if we wanted the dimming effect to occur whenever the star was near the circle? Well, let's make the conditional more specific by adding some "and" statements and a little math:
    function positionCheck(myEvent:Object):void { 
        if (star_mc.x+50 > circle_mc.x && star_mc.x-50 < circle_mc.x && 
                    star_mc.y+50 > circle_mc.y && star_mc.y-50 < circle_mc.y) { 
            star_mc.alpha = 0.4; 
        } else { 
            star_mc.alpha=1; 
        } 
    }
    The conditional now checks for four things—whether the star is more than 50 pixels to the left, right, top, or bottom of the circle. If it's within that range, it dims; otherwise it remains opaque. Try it again.
  10. Let's add another object. Draw a square on the stage, convert it to a movie clip, and call it square_mc.
  11. This time we'll have the star rotate slightly when it gets near the target object. Since we're adding another check to our conditional, we'll use an else if statement. Add the new code:
    function positionCheck(myEvent:Object):void { 
        if (star_mc.x+50 > circle_mc.x && star_mc.x-50 < circle_mc.x && 
                    star_mc.y+50 > circle_mc.y && star_mc.y-50 < circle_mc.y) { 
            star_mc.alpha = 0.4; 
        } else if (star_mc.x+50 > square_mc.x && star_mc.x-50 < square_mc.x && 
                    star_mc.y+50 > square_mc.y && star_mc.y-50 < square_mc.y) { 
            star_mc.rotation=45; 
        } else { 
            star_mc.alpha=1; 
            star_mc.rotation=0; 
        } 
    }
  12. Try adding a third target object that triggers yet another effect. Some suggestions: width, height, scaleX, scaleY, x, y, and/or visible.

Hit tests

Comparing the x and y positions of objects is one way to test for proximity; another is to use one of several "hit test" methods like hitTestObject() or hitTestPoint().

Replace the positionCheck() function with the following code:

function positionCheck(myEvent:Object):void {
  if (star_mc.hitTestObject(circle_mc)) {
      star_mc.alpha=0.4;
  } else {
      star_mc.alpha=1;
  }
}

The hitTestObject() method checks to see of the specified objects are in contact with each other. Be aware however, that Flash considers the bounding box around the shape to be part of the object, so non-rectangular objects will often register a "hit" even if they don't appear to touch.

Another option is to use the hitTestPoint() which checks to see if an object comes into contact with a specific point in an object (like it's center):

function positionCheck(myEvent:Object):void {
   if (star_mc.hitTestPoint(circle_mc.x, circle_mc.y)) {
       star_mc.alpha=0.4;
   } else {
       star_mc.alpha=1;
   } 

In this case, we're checking to see if the star (or more specifically its bounding box) contacts the registration point of the circle (its x and y position). Of course, if the registration point of the circle is not in the center, the star will appear to miss hitting it somewhat.

Your Turn

What can you do with a proximity checker and/or hit test? Can you think of a fun or clever application? Consider:

  • Changing the objects to something more interesting than circles, squares and triangles.
  • Experimenting with different results of the check—you could alter the rotation, alpha, position, visibility of course. You could also trigger a movie clip to play (or stop playing).

Grading rubric

10 pts Went above & beyond and made something special
9 pts Above and beyond the basics—multiple customizations or inovations
8 pts Changed the image or added the ring
7 pts Did the basics; it works, but it's nothing fancy.
6 pts Something's not working right.
0-5 pts Poor showing; mostly incomplete or full of errors.
decorative thumbnail

All text, images, and multimedia pieces (unless otherwise specified) copyright 2005–2011 Daniel C. Fergus. All rights reserved. No reproduction without permission.