Actionscript:从子类添加一个sprite到它的超类的显示列表?

时间:2010-08-15 15:52:46

标签: actionscript-3

说我有这两个类:

MAIN.as

package 
{
    import flash.display.*;     import mx.core.*;       
    import flash.events.*;      import mx.collections.*;
    import flash.geom.*;        import mx.controls.*;
    import flash.text.*;        import mx.events.*;
                                import mx.styles.*;
                                import mx.containers.*;

    public class MAIN extends Sprite
    {
        public var APPLICATION:Application = Application(Application.application);
        public var keyDownText:TextField = new TextField();
        public function MAIN()
        {
            stage.addEventListener(KeyboardEvent.KEY_DOWN,KEY_DOWN);
            addEventListener(Event.ENTER_FRAME,STEP);
            new OBJECT_square().CREATE(10,100,1);
        }

        public function STEP():void {}
        public function DRAW():void {}
        public function KEY_DOWN(event:KeyboardEvent):void 
        {
            keyDownText.text = "Key code: " + event.keyCode;
            this.addChild(keyDownText);
        }
    }
}

OBJECT_square.as

package
{
    import flash.display.*;
    import flash.events.*;

    public class OBJECT_square extends Sprite
    {
        public var X:int = 0;
        public var Y:int = 0;
        public var DEPTH:int = 0;
        public var SPRITE:Sprite = new Sprite();
        public function CREATE(X:int,Y:int,DEPTH:int):void
        {
            this.DEPTH = DEPTH;
            this.X = X;
            this.Y = Y;
            DRAW();
        }
        public function DRAW():void
        {
            SPRITE.graphics.beginFill(0xFF0000,1);
            SPRITE.graphics.drawRect(X - 10,Y - 10,20,20);
            SPRITE.graphics.endFill();
            addChild(SPRITE);
        }
    }
}

现在我怎么能将OBJECT_square类中的Sprite变量SPRITE添加到MAIN类的显示列表中?我试过addChild(SPRITE)和super.addChild(SPRITE)。如果一切正常,我应该在屏幕的某处看到一个红色正方形,但现在它全部为空白,除了在MAIN类中绘制的文本。

基本上我想要它所以我可以创建一个新的OBJECT_square,它将在没有来自MAIN类的更多指令的情况下自行绘制。

1 个答案:

答案 0 :(得分:1)

试试这个:

var obj:OBJECT_square = new OBJECT_square();
obj.CREATE(10,100,1);
addChild(obj);

或者,如果你真的想一次性完成,你可以试试这个:

主要

addChild((new OBJECT_square()).CREATE(10,100,1));

并更改绘制函数以返回方形对象

    public function DRAW():OBJECT_square
    {
        SPRITE.graphics.beginFill(0xFF0000,1);
        SPRITE.graphics.drawRect(X - 10,Y - 10,20,20);
        SPRITE.graphics.endFill();
        addChild(SPRITE);
        return this;
    }