user2101341
user2101341

Reputation: 23

Draw line from object to Mouse (AS3)

My code is here:

        graphics.clear();
        graphics.lineStyle(1, 0, 1);
        graphics.moveTo(cannon.x, cannon.y);
        graphics.lineTo(mouseX, mouseY);

It doesn't seem to be drawing anything. BTW it's in ENTER_FRAME right now.

Upvotes: 2

Views: 7046

Answers (1)

bitmapdata.com
bitmapdata.com

Reputation: 9600

refer a following code. this is my simple code draw app. And paste the code below:

startX and startY should instead changes to the your object(cannon).

If you want remove prior line. call a this.graphics.clear(); at onDrawReady Handler.

var isDrawingReady:Boolean;
var startX:Number, startY:Number;
stage.addEventListener(MouseEvent.MOUSE_DOWN, onDrawReady);
stage.addEventListener(MouseEvent.MOUSE_UP, onDrawStop);
stage.addEventListener(MouseEvent.MOUSE_MOVE, onDraw);
function onDrawReady(e:MouseEvent):void
{
    startX = e.stageX;
    startY = e.stageY;
    isDrawingReady = true;
}

function onDraw(e:MouseEvent):void
{
    if(isDrawingReady)
    {
        this.graphics.lineStyle(2,0xff0000);
        this.graphics.moveTo(startX,startY);
        this.graphics.lineTo(e.stageX,e.stageY);

        startX = e.stageX;
        startY = e.stageY;
    }

    e.updateAfterEvent();
}

function onDrawStop(e:MouseEvent):void
{
    isDrawingReady = false;
}

EDIT

If you want always draw line when mouse move. tried as follows:

var startX:Number, startY:Number;
stage.addEventListener(MouseEvent.MOUSE_MOVE, onDraw);
function onDraw(e:MouseEvent):void
{
    this.graphics.lineStyle(2,0xff0000);
    this.graphics.moveTo(startX,startY);
    this.graphics.lineTo(e.stageX,e.stageY);

    startX = e.stageX;
    startY = e.stageY;

    e.updateAfterEvent();
}

Upvotes: 4

Related Questions