开发者

Basic Flash/AS3 Extended Sprite. What am I missing?

I'm right at the beginning of trying to learn Actionscript 3. I'm currently working with FlashDevelop as my IDE. Whilst I can code in other languages, AS3 is very new to me (as is Flash).

I have created a basic class:

package 
{
    import flash.display.Sprite;

    public class BouncingBox extends Sprite
    {
        public function BouncingBox() 
        {
            x = 10;
            y = 10;
            width = 100;
            height = 100;
            graphics.clear();
            graphics.beginFill(0xD4D4D4); // grey color
            graphics.drawRoundRect(0, 0, 100, 100, 10, 10); /开发者_JAVA百科/ x, y, width, height, ellipseW, ellipseH
            graphics.endFill();
        }
    }
}

Then, from my Main() class, I do:

package 
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.text.TextField;

    public class Main extends Sprite 
    {
        var mySprite:BouncingBox;

        public function Main():void 
        {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }

        private function init(e:Event = null):void 
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            // entry point
            mySprite = new BouncingBox();
            addChild(mySprite);         

            var t:TextField = new TextField();
            t.text = "Testing!";
            addChild(t);        
        }
    }
}

What I expected to happen was the text to appear at the top (which it does), and the instance of BouncingBox to appear at 10, 10 on the stage (which is doesn't).

What have I missed to make this sprite appear on the stage?


This.

width = 100;
height = 100;

You set it when sprite is empty, and it messed up its transformation matrix. When rectangle is drawn, it will give sprite this size by itself. Set width and height if you want to scale it later.


Your object is not really initialized until after is attached to the display list. Try to add the following code.

package 
{
    import flash.display.Sprite;

    public class BouncingBox extends Sprite
    {
    public function BouncingBox() 
    {
         if (stage) init();
        else addEventListener(Event.ADDED_TO_STAGE, init);
    }

    private function init(e:Event = null):void 
    {
        x = 10;
        y = 10;
        //width = 100;
        //height = 100;
        graphics.clear();
        graphics.beginFill(0xD4D4D4); // grey color
        graphics.drawRoundRect(0, 0, 100, 100, 10, 10); // x, y, width, height, ellipseW, ellipseH
        graphics.endFill();
    }
    }
}

Also, you could attach your box, and then initialize its position, etc.

mySprite = new BouncingBox();
addChild(mySprite); 
mySprite.x = mySprite.y = 10;

Also, consider what @alxx wrote in his answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜