Jern Doers
Jern Doers

Reputation: 5

How to loop code without setting a definite ending in AS3

I have a frame that has actions in it. The code isn't in a function and as such it loops. Now that I added a new scene it just immediately jumps to the new scene. Is there a loop I can use that it only executes until a collision happens between player1 and thisBall?

Upvotes: 1

Views: 55

Answers (2)

Amy Blankenship
Amy Blankenship

Reputation: 6961

If in your root timeline, you have two MovieClips, one on frame 1 and one on frame 2, you can have this in your main document Class:

public class Main extends MovieClip {
   public function Main() {
       super();
       stop();
       addEventListener('collision', onCollision);
   }
   private function onCollision(e:Event) {
       nextFrame();
   }
}

Then, anywhere in the MC on frame 1 (hopefully in an attached Class), you can have this code:

dispatchEvent(new Event('collision', true));

Your main document Class will "hear" that event and go to the next frame, which will contain whatever you want to see next.

Upvotes: 0

Atriace
Atriace

Reputation: 2558

As null commented, don't use scenes (they really are a bag of hurt). In spite of that, you appear to be needing a game loop. This is common enough...

addEventListener(Event.ENTER_FRAME, onEnter);
function onEnter(e:Event):void {
    //do stuff
}

The way you need to think of it is like looking at a video. Each "frame" you're running some logic, such as ball.x += 1; which would move the ball to the right of the screen, each time the screen updates (a.k.a., a new "frame"). If you wanted to do something else when your condition was met, you could add it to your loop logic.

function onEnter(e:Event):void {
    ball.x += 1;

    if (ball.x == player.x) {
        trace("You've hit the player with the ball.")
    }
}

This is very rudimentary, and I wouldn't tackle it this way if you're using classes, or a larger framework, but this should get you by for now.

Upvotes: 2

Related Questions