如何清除屏幕上的旧线?

时间:2011-11-16 22:35:16

标签: flash actionscript-3 flash-builder

我正在将程序从AS2转换为AS3。我在屏幕上移动的球之间有一个简单的动画画线,但我无法弄清楚如何使用clear()去除旧的。这就是我得到的:

enter image description here

以下是代码:

function moveBalls(e:Event):void
        {
            var nodeA:MovieClip;
            var nodeB:MovieClip;
            var line:Sprite = new Sprite();

            for (var i:uint = 0; i < getLength(nodes); i++)
            {
                nodeA = nodes[i];
                for (var j:uint = i + 1; j < getLength(nodes); j++)
                {
                    nodeB = nodes[j];
                    var dx:Number = nodeB.x - nodeA.x;
                    var dy:Number = nodeB.y - nodeA.y;
                    var dist:Number = Math.sqrt(dx * dx + dy * dy);
                    if (dist < minDist)
                    {
                        line.graphics.lineStyle(1, 0x00ffff);
                        line.graphics.moveTo(nodeA.x+nodeA.width/2, nodeA.y+nodeA.height/2);
                        line.graphics.lineTo(nodeB.x+nodeB.width/2, nodeB.y+nodeB.height/2);
                        addChild(line);

                        var ax:Number = dx * k * .5;
                        var ay:Number = dy * k * .5;
                        nodeA.vx += ax;
                        nodeA.vy += ay;
                        nodeB.vx += ax;
                        nodeB.vy += ay;
                    }
                }
            }
        }

2 个答案:

答案 0 :(得分:1)

试试这个演示:

var s:Shape = new Shape();
addChild(s);


stage.addEventListener(MouseEvent.CLICK, _click);
function _click(e:MouseEvent=null):void
{
    s.graphics.clear();
    s.graphics.lineStyle(2, 0xFF0000);
    s.graphics.lineTo(
        Math.random()*stage.stageWidth,
        Math.random()*stage.stageHeight
    );
}

_click();

提示:ShapeSprite更轻量级,建议在您的方案中使用。

答案 1 :(得分:1)

由于linemoveBalls函数中的局部变量,因此每次调用时都会添加更多行(每次创建一个新的Shape,并保留它而不是在方法结束,因为它被添加到显示列表中。)

line设为字段变量,而不是

var line:Shape = new Shape (); 
// I took @Marty Wallace's suggestion and went with Shape here

呼叫

line.graphics.clear();

在moveBalls方法的开头。