AS3 Sprite added to Stage but not visible

I'm trying to get a simple AS3 app up and running, and for some reason, I cannot get a sprite to show. At this point, all I want to do is get a red sprite to fill the stage.

public class Main extends Sprite 
{       
    public function Main():void 
    {
        super();

        stage.scaleMode = StageScaleMode.NO_SCALE;
        stage.align = StageAlign.TOP_LEFT;

        var square:Sprite = new Sprite();   

        square.width = stage.stageWidth;
        square.height = stage.stageHeight;
        square.x = square.width / 2;
        square.y = square.height / 2;

        square.graphics.clear();
        square.graphics.lineStyle(3, 0xFF0000);
        square.graphics.beginFill(0xFF0000);
        square.graphics.drawRect(0, 0, width, height);
        square.graphics.endFill();

        square.addEventListener(Event.ADDED_TO_STAGE, addedToStage);
        square.addEventListener(MouseEvent.CLICK, onClick);

        addChild(square);
     }

     private function addedToStage(e:Event):void 
     {
          trace("Added sprite to stage");           
     }
     private function onClick(e:Event):void 
     {
          trace("Got click on sprite");         
     }      
}

The trace shows that the sprite was added to the stage, but nothing is displayed, and if I click on it, the onClick function never gets called. If I use a TextField instead of a Sprite, it displays just fine. There must be something weird about Sprites.

What am I doing wrong?

Thanks!

Answers


Trying to set the width and height for a empty Sprite will return 0. Have a look at here.

and

Refer Mr.Marty Wallace's answer.


Your issue is here:

square.graphics.drawRect(0, 0, width, height);

The values for width and height in this line are 0. The reason being that they are referring to the width and height properties of the class you're working within (Main - properties inherited from DisplayObject) which will be zero based on what I can see.

You're essentially saying:

square.graphics.drawRect(0, 0, 0, 0);

Which will render nothing.


Need Your Help

Create and pass Map to a request scoped attribute

java jsp spring-mvc jstl jsp-tags

In my JSP model I have a bean of class MyBean in the scope.

How can I get my generic method to work?

c# generics lambda expression extension-methods

I am writing a small extension to my WPF viewModel base class that allows me to define dependencies between properties in a cleaner way than the standard method of raising multiple PropertyChanged ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.