Thursday, April 22, 2010

FYI onEnterFrame

Copied from The Globaloria Educator's Bulletin:  

As students are adding more code to their games, a few of them have hit the same roadblock: you can only use onEnterFrame once per frame. Here’s how to steer clear of the problem.

Any code between onEnterFrame’s brackets will run once per frame at the frame rate of the file.  At Flash’s default frame rate of 12 frames per second, that means the code will run twelve times per second, thus creating a game control loop.

In the mini-game example, we used onEnterFrame to make the carrot move continuously across the stage.  It worked because the code kept redrawing the carrot a few pixels to the right of its previous location.

How to Fix It:
If your student has more than one onEnterFrame in their ActionScript on a single frame (even if they’re on different layers) they need to be consolidated or the file will not work. 

Here’s an example from a student’s file:

obj1._y = 1;
onEnterFrame = function() {
     obj1._y = obj1._y + 10;
    if (trashcan.hitTest(obj1)) {
    obj1._x = 5;
    }
}

obj2._y = 10;
onEnterFrame = function() {
     obj2._y = obj2._y + 5;
    if (trashcan.hitTest(obj2)) {
    obj2._x = 5;
    }
}

And here’s how you consolidate the code:
obj1._y = 1;
obj2._y = 10;

onEnterFrame = function() {
     obj1._y = obj1._y + 10;
    if (trashcan.hitTest(obj1)) {
        obj1._x = 5;
        }
     obj2._y = obj2._y + 5;
    if (trashcan.hitTest(obj2)) {
        obj1._x = 5;
        }
}

No comments:

Post a Comment