mheavers
mheavers

Reputation: 30158

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();

Upvotes: 3

Views: 1911

Answers (2)

kapex
kapex

Reputation: 29959

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.

Upvotes: 2

taskinoor
taskinoor

Reputation: 46027

You are not setting x, y properties of the circle, you are drawing at x, y position. That is different from setting x and y properties. Even if you draw at xPos, yPos your circle's x, y are zero. Instead of drawing at x, y you need to draw at 0, 0 and then move the circle at x, y by setting the properties.

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

If you want to update the lines continuously then you can listen onFrame event and update the line if any circle has moved.

Upvotes: 3

Related Questions