[AS3]如何使文本显示几秒钟

时间:2014-05-14 20:14:32

标签: actionscript-3

我无法继续这样做。在我的更新函数中,我有一个if语句。

if (_score == 30)
{
       timeIncreaseText();
}

timeIncreaseText函数是

private function timeIncreaseText():void
    {
        var textformat:TextFormat = new TextFormat();
        textformat.size = 18;

        var mytextfield:TextField = new TextField();
        mytextfield.defaultTextFormat = textformat;

        addChild(mytextfield);
        mytextfield.text = "Time has increased. Better hurry!";
        mytextfield.textColor = 0xff0000;

        mytextfield.width = 500;
        mytextfield.x = 100;
        mytextfield.y = 200;
    }

这很好用,但似乎不能让它在几秒后消失。救命啊!

1 个答案:

答案 0 :(得分:1)

自定义子类是一种很好的方法。您可以扩展常规TextField类,以包含一个在指定时间后删除文本字段的计时器。

package 
{
    import flash.events.Event;
    import flash.events.TimerEvent;
    import flash.text.TextField;
    import flash.text.TextFormat;
    import flash.utils.Timer;

    //extend TextField so you get all it's functionality
    public class TimedText extends TextField
    {
        private var timer:Timer;

            //first parameter is the text you want to show, second is how many milliseconds before it disappears, third is a different textFormat if you wanted.
        public function TimeText(startingText:String, time:Number = 5000, textFormat_:TextFormat = null):void {
            super();
            this.text = startingText;

            if (!textFormat_) { //if a text format isn't passed in, create one with the default settings
                textFormat_ = new TextFormat();
                textFormat_.size = 18;
                textFormat_.color = 0xff0000;
            }

            this.defaultTextFormat = textFormat_;

            timer = new Timer(time, 1); //create a timer that runs only one time
            timer.addEventListener(TimerEvent.TIMER, timerTick, false, 0, true); //listen for the timer event
            this.addEventListener(Event.ADDED_TO_STAGE, addedToStage, false, 0, true);
        }

            //use add to stage so the timer doesn't start until the text field is actually visible
        private function addedToStage(e:Event):void {
            timer.start();
        }

        private function timerTick(e:TimerEvent):void {
            this.dispatchEvent(new Event(Event.COMPLETE)); //if you want something else to handle the removing

            //or animate / fade out first

            //or directly remove itself
            if (this.parent) {
                this.parent.removeChild(this);
            }
        }
    }

}

然后你可以这样做:

var mytextfield:TimedText = new TimedText("Time has increased. Better hurry!");
    addChild(mytextfield);

    mytextfield.width = 500;
    mytextfield.x = 100;
    mytextfield.y = 200;