0

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 Answers2

0

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?

SSpoke
  • 5,656
  • 10
  • 72
  • 124
  • This is a good solution, but it doesn't really help me in my context (still useful to me in general though). I need to test every frame if the 2 movieclips are touching, and then run a function. There will be multiple instances when they are not touching and are touching (depending on the game's player), so I need to keep the event listener in tact. – user3168412 Jan 07 '14 at 11:06
0

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
}
mihai
  • 4,184
  • 3
  • 26
  • 27