Search code examples
actionscript-3mouseeventflashdevelopflash-cs6hittest

How to register hitTest only if Mouse Down is true?


I was wondering on how to register a Hittest between two Movie Clips only if the MOUSE_DOWN event is equal to true.

So I have a Movie Clip called playerHook that acts as the Mouse and whenever that movie clip comes in contact with another movie clip called octopusBoss and Clicks on it I want it to register a hittest and subtract a point from its health.

Here is what I have so far but not sure what to do next:

In my main constructor function:

playerHook.addEventListener(Event.ENTER_FRAME, playerHookMove);
playerHook.addEventListener(MouseEvent.MOUSE_DOWN, onMDown);
playerHook.addEventListener(MouseEvent.MOUSE_UP, onMUp);

Then I have two booleas set up in the two functions onMDown and onMUp:

private function onMDown(e:MouseEvent):void 
{
    mouseIsDown = true;
}

private function onMUp(e:MouseEvent):void 
{
    mouseIsUp = false;          

}

Then I have this function which is currently in my gameloop that I would want to happen only if the user clicks on the OctopusBoss:

private function checkPlayerHitOctopusBoss():void 
{
    if (playerHook.hitTestObject(octopusBoss))
    {
         trace("Hit Octopus");
         octopusBossHealth --;              
    }else 
    if (octopusBossHealth <= 0)
    {
         octopusBoss.destroyOctopusBoss();
    }
}

But I am having trouble passing the mouse booleans to the if statement. I know I am missing something crucial!


Solution

  • First you need some name to your octopusBoss like so:

    octopusBoss.name = "octopusBoss";

    Modify your onMDown function like so:

    private function onMDown(e:MouseEvent):void 
    {
        if(e.target.name == "octopusBoss") //Check if octopusBoss is under mouse
        mouseIsDown = true;
    }
    

    And your checkPlayerHitOctopusBoss function like so:

    private function checkPlayerHitOctopusBoss():void 
    {
       if (playerHook.hitTestObject(octopusBoss) && mouseIsDown) // check mouse down
       {
           trace("Hit Octopus");
           octopusBossHealth --;              
       }else 
       if (octopusBossHealth <= 0)
       {
           octopusBoss.destroyOctopusBoss();
       }
    }
    

    UPDATE: If it's ok to add MouseEvents directly to octopusBoss like so:

    octopusBoss.addEventListener(MouseEvent.MOUSE_DOWN, onMDown); octopusBoss.addEventListener(MouseEvent.MOUSE_UP, onMUp);

    Then, you can also use e.currentTarget.name.