Button

Starling natively supports the concepts of buttons. Here is the signature of the Button constructor:

public function Button(upState:Texture, text:String="", downState:Texture=null)

By default, the Button class creates an internal TextField to support labels and the text is centered inside the button. In the following code, we create a simple button out of an embedded bitmap that we use as a skin:

package
{

    import flash.display.Bitmap;

    import starling.display.Button;
    import starling.display.Sprite;
    import starling.events.Event;
    import starling.textures.Texture;

    public class Game extends Sprite
    {

        [Embed(source = "../media/textures/button_normal.png")]
        private static const ButtonTexture:Class;

        public function Game()
        {
            addEventListener(Event.ADDED_TO_STAGE, onAdded);
        }

        private function onAdded (e:Event):void
        {
            // create a Bitmap object out of the embedded image
            var buttonSkin:Bitmap = new ButtonTexture();

            // create a Texture object to feed the Button object
            var texture:Texture = Texture.fromBitmap(buttonSkin);

            // create a button using this skin as up state
            var myButton:Button = new Button(texture, "Play");

            // createa container for the menu (buttons)
            var menuContainer:Sprite = new Sprite();

            // add the button to our container
            menuContainer.addChild(myButton);

            // centers the menu
            menuContainer.x = stage.stageWidth - menuContainer.width >> 1;
            menuContainer.y = stage.stageHeight - menuContainer.height >> 1;

            // show the button
            addChild(menuContainer);
        }

    }
}

Note that we use here the

Get Introducing Starling now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.