Search code examples
actionscript-3flash

How to remove objects from stage when hit detection is registered


I am trying to remove a object on the screen when my hit detection has been registered. Below was my best try but it didnt work.

 stage.addEventListener(Event.ENTER_FRAME, detectCollision2);
 function detectCollision2(event:Event)
 {
if (character.hitTestObject(stick))
{
    stick1.visible = false;
    stickVisible = false;
    health--;
    removeChild(stick);
}

what i was trying to do was add a simple collision detection and when my character hit the stick instance the health goes down by 1. After my health went down by 1 i wanted to remove the object stick because what happened was the character was stil on the stick and the health kept decreasing very quickly. I just want the health to decrease by 1 and stop, i need help please i dont know how to go about this.


Solution

  • After you removeChild the stick you can set the stick variable to null (stick = null) to remove all reference to that object. The 'stick1' and 'stickVisible' variables seem surplus to requirements, so at this stage (no pun intended) I'd recommend removing those lines. If you are getting errors, it is probably because Flash doesn't know what those variables are.
    Additionally, prior to checking for the collision, you might want to check that 'stick' exists. So your detectCollision2 function should look like this:

    function detectCollision2(event:Event):void {
        if (stick) {
            if (character.hitTestObject(stick)) {
                health--;
                removeChild(stick);
                stick = null;
            }
        }
    }