Search code examples
actionscript-3flashactionscriptflash-cs6

Drawing line collision?


I've gotten actions on a frame, what I'm trying to do is have a hitTest that triggers gotoAndStop(<lose frame>) when the shape I am drawing collides with the touchTest. The only issue I'm having is I cannot get the hitTest to register directly when the line hits it, it only registers after the next click event. The other issue I'm encountering is a hit box on the touchTest is many times larger than the actual image of the symbol.

var myshape:Shape;
myshape = new Shape();
myshape.graphics.lineStyle(5, 0xC807DE);
var alreadyDrawn:Shape;
alreadyDrawn = new Shape();

stage.addEventListener(MouseEvent.MOUSE_DOWN, activateDraw);
function activateDraw(event:MouseEvent):void
{
    myshape.graphics.moveTo(mouseX,mouseY);
    addChild(myshape);

    stage.addEventListener(MouseEvent.MOUSE_MOVE, lineDraw);
    stage.addEventListener(MouseEvent.MOUSE_UP, stopDraw);
}

function lineDraw(event:MouseEvent):void
{
    myshape.graphics.lineTo(mouseX,mouseY);
    checkIt();
}
function stopDraw(event:MouseEvent):void
{
    alreadyDrawn.graphics.copyFrom(myshape.graphics);
    stage.removeEventListener(MouseEvent.MOUSE_MOVE, lineDraw);
    stage.removeEventListener(MouseEvent.MOUSE_UP, stopDraw);
}

function checkIt()
{
    if (alreadyDrawn.hitTestObject(touchTest) == true)
    {
        trace("wall");
        myshape.graphics.clear();
        myshape.graphics.lineStyle(5, 0xC807DE);
        alreadyDrawn.graphics.clear(); // clear this too
        stopDraw(null); // stop active draw, if any
    }
}

Solution

  • You could first use copyFrom method in your function lineDraw, because alreadyDrawn must be drawn before it's tested !

    function lineDraw(event:MouseEvent):void
    {
        myshape.graphics.lineTo(mouseX,mouseY);
        alreadyDrawn.graphics.copyFrom(myshape.graphics);
        checkIt();
    }
    

    This works, but not correctly because the hitTest considers the rectangle containing alreadyDrawn. You must consider that the point to be tested is your mouse.

    function checkIt():void
    {
        if (touchTest.hitTestPoint(mouseX, mouseY, true))
        {
            trace("wall");
        }
    }