AS3 - stop onEnterFrame Function from constantly running

1.4k views Asked by At

Okay, I have a collisionTest function that is tied to my "onEnterFrameHandler" function.

So to simplify the way it looks:

onEnterFrameHandler(e:Event):void{
testCollision();
}

testCollision():void{
  trace("always running");
  if(1_MC.hitTestObject(2_MC)){
    //do stuff
  }
}

The thing is, it is always running. Constantly running in order to test for a collision. I have a feeling that it is what may be causing the lag on this project.

Do you know of a good way to control a function that needs to be able to check, at any time, an event, yet not run while the even is not occurring?

3

There are 3 answers

0
Neil On BEST ANSWER

Usually you are always checking for collisions in a game loop. You provide a flag to indicate if something needs to be checked or not.

On a side note, consider using collision detection kit, I think you'll find it takes care of just about every scenario you can have regarding collisions.

0
Daniel On

It's hard to answer this question as it is pretty vague when you're not checking for collision. To improve the performance it's not about changing how to collision test, but when to do the check.

so you could do this by simply adding an if statement like so:

if (doCollisionTest){testCollision();}

but that doesn't solve when doCollisionTest is true or false, and that's the tricky part, that cannot be answered from the information you provided.

3
BadFeelingAboutThis On

If you don't need to check every single frame, you can use a Timer to only check as often as you like, for instance, if you deemed it good enough to check 3 times per second, you'd set it up like this:

var timer:Timer = new Timer(333); //run 3 times a second
timer.addEventListneer(TimerEvent.TIMER, collisionTest, false, 0, true);
timer.start();

function collisionTest(e:Event = null):void {
   //do you collision stuffs
}

Then, if for whatever reason you want to temporarily disable it, use timer.stop() , then timer.start() again