How do I run code inside an event function for an ENTER_FRAME listener that does not run once every frame?

648 views Asked by At

So, I have code similar to this (this is for demonstration purposes):

addEventListener(Event.ENTER_FRAME, enterFrameFunction);  

    function enterFrameFunction(e:Event):void{ 

    if(sampleMovieClip1.hitTestObject(sampleMovieClip2)){  
    runAFunctionIDontWantToBeRunOnEveryFrame();
    }

    }

The problem is that in order to test wether sampleMovieClip2 is colliding with sampleMovieClip1, I need to test it every frame with enterFrameFunction, so any code I put inside that function runs every frame the test returns true, but I want the runAFunctionIDontWantToBeRunOnEveryFrame(); function to only run it once.

I have been successful in doing this by adding a variable to determine if the condition has been true before, but i'm having complications with that now and would like to know if theres a different, less tedious way getting the result. Something like an event listener to test a boolean returning true?

2

There are 2 answers

1
SSpoke On

Once the hit occurs you should remove the event listener.

removeEventListener(Event.ENTER_FRAME, enterFrameFunction);

Otherwise your only other solution would be

addEventListener(Event.ENTER_FRAME, enterFrameFunction);  

    function enterFrameFunction(e:Event):void{ 

    if(sampleMovieClip1.hitTestObject(sampleMovieClip2)&&!alreadyHit){
      alreadyHit=true;
      runAFunctionIDontWantToBeRunOnEveryFrame();
    } else {
      alreadyHit=false;
    }
    }

This does have a problem unsetting it back to false, non-stop when it's not hit, but will that make a problem?

0
mihai On

just place your method outside of the handler for the event listener:

this will call the second method on every frame where the IF statement returns true if you want it to call once use this example where its allowed only once... if you want it to run again change the allowMethodCall to true;

var allowMethodCall:Boolean = true;
addEventListener(Event.ENTER_FRAME, enterFrameFunction);  

/** method runs on enter frame */
function enterFrameFunction(e:Event):void{ 
    if(sampleMovieClip1.hitTestObject(sampleMovieClip2)){  
        if (allowMehodCall) {
            runAFunctionIDontWantToBeRunOnEveryFrame();
        }
    }
}

/** method runs only when called once */
function runAFunctionIDontWantToBeRunOnEveryFrame():void{
    //this runs only once when called
}