Search code examples
actionscript-3flashdrawing

flash as3 drawing a line between two circles


I'm trying to draw two circles at random positions and draw a line between those two circles - but flash doesn't seem to register the xy coordinates of the circle in my code.

How would I do this? Better yet, how would I do this so that if I were to drag one of the circles, the line would maintain the connection between those circles?

Here's my code:

var sw = stage.stageWidth;
var sh = stage.stageHeight;
var cr = 6; //circle radius
var circleColor = 0x000000;
var numCircles = 2;
var circleArray = [];
var lineCanvas:Sprite = new Sprite();
addChild(lineCanvas);
var lineColor = 0x000000;
var lineWeight = 1;

function init(){
    drawCircle();
}

function drawCircle(){
    for (var i = 0; i<numCircles; i++){
        var xPos = randomRange(cr, sw-cr);
        var yPos = randomRange(cr, sh-cr);
        var newCircle:Shape = new Shape();
        newCircle.graphics.beginFill(circleColor);
        newCircle.graphics.drawCircle(xPos,yPos,cr);
        newCircle.graphics.endFill();
        circleArray.push(newCircle);
        addChild(newCircle);
    }
    drawLine();
}

function drawLine(){
    for (var i = 0; i<numCircles-1; i++){
        trace (circleArray[i].x);
        lineCanvas.graphics.lineStyle(lineWeight,lineColor);
        lineCanvas.graphics.moveTo(circleArray[i].x,circleArray[i].y);
        lineCanvas.graphics.lineTo(circleArray[i+1].x,circleArray[i+1].y);
    }
}

function randomRange(minNum:Number, maxNum:Number):Number {  
    return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);  
}

init();

Solution

  • The sprite containing the circle is technically still at 0,0, you just have drawn the circle at a random position. If you don't save that position, you won't be able to refer to it after that.

    Instead of drawing the circle with an offset,you should draw it at the center of the sprite - and move that sprite to the random position:

    newCircle.graphics.drawCircle(0, 0, cr);
    newCircle.x = xPos;
    newCircle.y = yPos;
    

    To update the line when you are moving the circles, you should add an event listener MouseEvent.MOUSE_MOVE or Event.ENTER_FRAME. When you are dragging the circles, the event should call your drawLine() function. Also, add lineCanvas.graphics.clear(); to the beginning of drawLine.