[AS3]How to make text appear for a few seconds - actionscript-3

Im having trouble keeping doing this. In my update function i have an if statement.
if (_score == 30)
{
timeIncreaseText();
}
timeIncreaseText function is
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;
}
This works great but i cant seem to make it go away after a few seconds. Help!

A custom subClass would be a good way to do this. You can extend the regular TextField class to include a timer that removes the text field after the specified time.
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);
}
}
}
}
Then you can just do this:
var mytextfield:TimedText = new TimedText("Time has increased. Better hurry!");
addChild(mytextfield);
mytextfield.width = 500;
mytextfield.x = 100;
mytextfield.y = 200;

Related

Updating and displaying a variable in AS3

I have been following an AS3 tutorial for an avoider game, the trouble is the tutorial is for CS5 and I am using Flash Develop. I am completely stuck trying to update and display the score. I have read through several posts on SO and elsewhere and still can't seem to fix it.
Here is the Score class that I call to display the score and it contains the function that updates the "score" value.
package
{
import flash.display.Sprite;
import flash.events.TextEvent;
import flash.text.TextField
import flash.text.TextFormat
public class Score extends Sprite
{
public var scoreDisplay:String;
public var currentValue:int;
public function Score()
{
updateDisplay()
}
public function updateDisplay():void
{
scoreDisplay = currentValue.toString();
var format:TextFormat = new TextFormat();
format.size = 25;
format.font = "Verdana"
var myText:TextField = new TextField();
myText.defaultTextFormat = format;
myText.text = scoreDisplay;
myText.background = true;
myText.autoSize
myText.width = 50;
myText.height = 35;
addChild(myText)
myText.x = 340
myText.y = 10
myText.mouseEnabled = false
}
public function addToValue( amountToAdd:Number ):void
{
trace("addToValue")
trace(currentValue)
currentValue = currentValue + amountToAdd;
trace(currentValue + " 1")
}
}
}
and here is the Game class I am running to increase the "score" per tick.
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.utils.Timer;
import Score;
public class Game extends Sprite
{
public var army:Array;
public var gameTimer:Timer;
public var player:Player;
public var background:Sprite;
public function Game()
{
army = new Array();
var newenemy:Enemy = new Enemy(100, -15);
army.push(newenemy);
addChild(newenemy);
player = new Player();
addChild(player);
player.x = mouseX;
player.y = mouseY;
gameTimer = new Timer(20);
gameTimer.addEventListener(TimerEvent.TIMER, move);
gameTimer.addEventListener(TimerEvent.TIMER, onTick);
gameTimer.start();
}
private function move(timerEvent:TimerEvent):void
{
player.x = mouseX;
player.y = mouseY;
for each (var enemy:Enemy in army)
{
enemy.moveDownABit();
if (player.hitTestObject(enemy))
{
gameTimer.stop();
dispatchEvent( new AvatarEvent( AvatarEvent.DEAD));
}
}
}
public function onTick(e:Event):void
{
if (Math.random() < .1)
{
var randomX:Number = Math.random() * 400;
var newEnemy:Enemy = new Enemy(randomX, -15);
army.push(newEnemy);
addChild(newEnemy);
var instanceScore:Score = new Score();
instanceScore.addToValue(10)
}
}
}
}
My trace function outputs "addToValue, 0, 10 1" and repeats that, never changing the 'curentValue' variable past 0. I can tell that the 'amountToAdd' is functioning properly but have no idea why 'currentValue' is always reset to 0.
questions on SO that I viewed;
Display dynamic variable on next key frame AS3
Avoider Game Tutorial: Score not working
The problem is this:
var instanceScore:Score = new Score();
This means that every time there is a tick, you create new score. When you create new score, it starts from 0. You update it to 10, and on the next tick, you ignore the old value of 10 by creating a whole new class. The new class has a value of 0, as it never has it's value increased before. Then you increase it again.. and a new tick starts (looping)
What you need to do is to instantiate score instance ONLY ONCE and save it as a class member variable. Then you can call increase to it.

Changing the UrlLoader.load

package {
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.text.StyleSheet;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.text.TextFormat;
import flash.text.*
import flash.net.*
public class SpeechBox extends MovieClip{
public var textLoader:URLLoader = new URLLoader();
public var box:Sprite = new Sprite();
public var nextBox:Sprite = new Sprite();
private var nextText:TextField = new TextField();
private var textBox:TextField = new TextField();
private var speechText:String;
public var _speechBoxCheck:Timer = new Timer(1000);
public var clickedNext:Boolean = false;
public function SpeechBox()
{
textLoader.addEventListener(Event.COMPLETE, onLoaded);
textBox.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownScroll);
_speechBoxCheck.addEventListener(TimerEvent.TIMER, speechBoxCheck);
_speechBoxCheck.start();
//////////////////SPEECH BOX///////////////////
box.graphics.lineStyle(3.5,0xffffff);
box.graphics.beginFill(0x003366, .35);
box.graphics.drawRoundRect(0,0,650,145,20);
box.graphics.endFill();
box.x = 100;
box.y = 450;
addChild(box);
//////////////////SPEECH TEXT///////////////////
var speechFont = new DataText();
var textFormat:TextFormat = new TextFormat();
textFormat.font = speechFont.fontName;
textFormat.align = TextFormatAlign.LEFT;
textFormat.leading = 3;
textFormat.color = 0xFFFFFF;
textFormat.size = 16;
textBox.defaultTextFormat = textFormat;
textBox.width = 620;
textBox.height = 115;
textBox.x = box.x + 14;
textBox.y = box.y + 14;
textBox.multiline = true;
textBox.wordWrap = true;
textBox.selectable = false;
addChild(textBox);
//////////////////NEXT BUTTON///////////////////
nextBox.graphics.beginFill(0x000000, 0);
nextBox.graphics.drawRect(0,0,50,30);
nextBox.graphics.endFill();
nextBox.x = box.x + 600;
nextBox.y = box.y + 115;
nextText.defaultTextFormat = textFormat;
nextText.text = "Next";
nextText.textColor = 0xffffff;
nextText.autoSize = "left";
nextText.selectable = false;
nextText.mouseEnabled = false;
nextText.x = nextBox.x + 2
nextText.y = nextBox.y + 5
nextBox.buttonMode = true;
//nextBox.mouseEnabled = true;
nextBox.addEventListener(MouseEvent.MOUSE_DOWN, clickNext);
nextBox.addEventListener(MouseEvent.MOUSE_OVER, moveOver);
nextBox.addEventListener(MouseEvent.MOUSE_OUT, moveOut);
}
function onLoaded(e:Event):void {
trace(e.target.data);
textBox.text = e.target.data;
}
function mouseDownScroll(event:MouseEvent):void
{
textBox.scrollV+=4;
textBox.addEventListener(MouseEvent.MOUSE_UP,mouseup);
}
function mouseup(event:MouseEvent):void
{
if(textBox.scrollV == textBox.maxScrollV)
{
addChild(nextBox);
addChild(nextText);
}
}
function clickNext(event:MouseEvent):void
{
trace("click");
clickedNext = true;
_speechBoxCheck.stop();
(parent as Main).onTransition.start();
textBox.scrollV = 0;
textLoader.removeEventListener(Event.COMPLETE, onLoaded);
this.parent.removeChild(this);
}
function moveOver(event:MouseEvent):void
{
nextText.textColor = 0xffcc00;
}
function moveOut(event:MouseEvent):void
{
nextText.textColor = 0xffffff;
}
///////////////////////////////////////////////////////////////
function speechBoxCheck(event:TimerEvent)
{
if ((parent as Main).introduction == true)
{
textLoader.load(new URLRequest("Texts/LV1introduction.txt"));
trace("beginning");
(parent as Main).onTransition.stop();
}
if ((parent as Main).levelNum == 1)
{
textLoader.load(new URLRequest("Texts/LV1complete.txt"));
trace("go to lv 2")
(parent as Main).onTransition.stop();
}
if ((parent as Main).levelNum == 2)
{
textLoader.load(new URLRequest("Texts/LV2complete.txt"));
trace("go to lv 3")
(parent as Main).onTransition.stop();
}
}
}
}
EDIT: When the game starts, the LV1 introduction text starts. Once the scrollV equals maxScrollV, a next buttons appears. Click that, it will delete itself and the game starts. Once you beat stage one, levelNum automatically equals 2 and I add this class again from my main document class. However, it will show the same text over and over, regardless of what level.
So does the urlLoader always stay the same? If so, how can I change it?
URLLoader can be reused to load another data with new URLRequest instance. It is completely OK to reuse same URLLoader instance to load another file. Your problem is not in URLLoader, but in logics or somewhere else. You'd better try debuggers to make sure variable level has correct value of 2.
Why are you loading text file EVERY second? It would be ok to load them only level is changed.
does this textLoader instance have event listeners attached?
:::::::::EDITED:::::::::
You are removing event Listeners from textLoader in clickNext() call. textLoader will load file, but will not run onLoaded() to update textBox.text
Your speechBoxCheck() method is doing it wrong. 1. You must make only 1 load() call in speechBox() method. Your conditionals in the method are not exclusive, and it may cause trouble when multiple load() calls are made (previous loading operation will be canceled). consider "else if" chain.
it is not recommended to do something like loading files in this fashion. Unnecessary I/O operations, especially in runtime, should be avoided. Only load files when it is needed; In this case, it is when level changes.

Error #2025: The supplied DisplayObject must be a child of the caller - Not sure how to fix

So I get an error saying that the supplied DisplayObject must be a child of the caller. What happens is my game works first time around in that clicking the 'Play' button calls the startGame function and removes the menu so that the game is shown, but then at the end of the game when the playAgainBtn is clicked, instead of simply playing the game again / restarting the game, I get this error:
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
It specifically points to this line:
menuLayer.removeChild(mainMenu);
Here is the code:
package {
import flash.display.MovieClip;
import flash.display.LoaderInfo;
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.display.Stage;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.ui.Mouse;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.text.TextFormat;
import flash.text.TextField;
import flash.text.AntiAliasType;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.system.LoaderContext;
import flash.display.Sprite;
import flash.net.Socket;
import caurina.transitions.Tweener;
import flash.text.Font;
public class Main extends MovieClip {
public static var backgroundLayer:Sprite = new Sprite;
public static var gameLayer:Sprite = new Sprite;
public static var interfaceLayer:Sprite = new Sprite;
public static var endGameLayer:Sprite = new Sprite;
public static var menuLayer:Sprite = new Sprite;
public static var gameOverLayer:Sprite = new Sprite;
public static var howToLayer:Sprite = new Sprite;
public static var scoresLayer:Sprite = new Sprite;
public static var aboutLayer:Sprite = new Sprite;
public var mainMenu:menuMain = new menuMain;
public var gameEnd:endGame = new endGame;
public var howtoPlay:howToPlay = new howToPlay;
public var gameAbout:aboutGame = new aboutGame;
public var intro:IntroSound = new IntroSound();
public var soundControl:SoundChannel = new SoundChannel();
public var gameTime:int;
public var levelDuration:int;
public var crosshair:crosshair_mc;
static var score:Number;
var enemyShipTimer:Timer;
var enemyShipTimerMed:Timer;
var enemyShipTimerSmall:Timer;
static var scoreHeader:TextField = new TextField();
static var scoreText:TextField = new TextField();
static var timeHeader:TextField = new TextField();
static var timeText:TextField = new TextField();
static var scoreFormat = new TextFormat("Arial Rounded MT Bold", 20, 0xFFFFFF);
public var gameOverscoreFormat = new TextFormat("Arial Rounded MT Bold", 32, 0xFFFFFF);
public function Main()
{
addChild(gameLayer);
addChild(backgroundLayer);
addChild(interfaceLayer);
addChild(menuLayer);
menuLayer.addChild(mainMenu);
interfaceLayer.addChild(howtoPlay);
interfaceLayer.addChild(gameEnd);
interfaceLayer.addChild(gameAbout);
soundControl = intro.play(0, 100);
addMenuListeners();
}
public function menuReturn(e:Event)
{
addChild(gameLayer);
addChild(backgroundLayer);
addChild(interfaceLayer);
addChild(menuLayer);
menuLayer.addChild(mainMenu);
interfaceLayer.addChild(howtoPlay);
interfaceLayer.addChild(gameEnd);
interfaceLayer.addChild(gameAbout);
}
public function showAbout(e:Event)
{
menuLayer.removeChild(mainMenu);
interfaceLayer.addChild(gameAbout);
}
public function startGame(e:Event)
{
removeMenuListeners();
soundControl.stop();
interfaceLayer.removeChild(howtoPlay);
interfaceLayer.removeChild(gameAbout);
interfaceLayer.removeChild(gameEnd);
menuLayer.removeChild(mainMenu);
levelDuration = 30;
gameTime = levelDuration;
var gameTimer:Timer = new Timer(1000,levelDuration);
gameTimer.addEventListener(TimerEvent.TIMER, updateTime);
gameTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timeExpired)
gameTimer.start();
scoreHeader = new TextField();
scoreHeader.text = String("Score: ");
interfaceLayer.addChild(scoreHeader);
scoreHeader.x = 5;
scoreHeader.selectable = false;
scoreHeader.embedFonts = true;
scoreHeader.antiAliasType = AntiAliasType.ADVANCED;
scoreText = new TextField();
scoreText.text = String("0");
interfaceLayer.addChild(scoreText);
scoreText.x = 75;
scoreText.y = 0;
scoreText.selectable = false;
scoreText.embedFonts = true;
scoreText.antiAliasType = AntiAliasType.ADVANCED;
timeHeader = new TextField();
timeHeader.text = String("Time: ");
interfaceLayer.addChild(timeHeader);
timeHeader.x = 500;
timeHeader.y = 0;
timeHeader.selectable = false;
timeHeader.embedFonts = true;
timeHeader.antiAliasType = AntiAliasType.ADVANCED;
timeText = new TextField();
timeText.text = gameTime.toString();
interfaceLayer.addChild(timeText);
timeText.x = 558;
timeText.y = 0;
timeText.selectable = false;
timeText.embedFonts = true;
timeText.antiAliasType = AntiAliasType.ADVANCED;
scoreHeader.setTextFormat(scoreFormat);
scoreText.setTextFormat(scoreFormat);
timeHeader.setTextFormat(scoreFormat);
timeText.setTextFormat(scoreFormat);
var timeScorebg:Sprite = new Sprite();
backgroundLayer.addChild(timeScorebg);
timeScorebg.graphics.beginFill(0x333333);
timeScorebg.graphics.drawRect(0,0,600,30);
timeScorebg.graphics.endFill();
timeScorebg.y = 0;
enemyShipTimer = new Timer(2000);
enemyShipTimer.addEventListener("timer", sendEnemy);
enemyShipTimer.start();
enemyShipTimerMed = new Timer(2500);
enemyShipTimerMed.addEventListener("timer", sendEnemyMed);
enemyShipTimerMed.start();
enemyShipTimerSmall = new Timer(2750);
enemyShipTimerSmall.addEventListener("timer", sendEnemySmall);
enemyShipTimerSmall.start();
crosshair = new crosshair_mc();
gameLayer.addChild(crosshair);
crosshair.mouseEnabled = crosshair.mouseChildren = false;
Mouse.hide();
gameLayer.addEventListener(Event.ENTER_FRAME, moveCursor);
resetScore();
}
function addMenuListeners():void
{
mainMenu.playBtn.addEventListener(MouseEvent.CLICK, startGame);
mainMenu.howToPlayBtn.addEventListener(MouseEvent.CLICK, showInstructions);
mainMenu.aboutBtn.addEventListener(MouseEvent.CLICK, showAbout);
howtoPlay.backBtn.addEventListener(MouseEvent.CLICK, menuReturn);
gameEnd.playagainBtn.addEventListener(MouseEvent.CLICK, startGame);
gameAbout.backBtn.addEventListener(MouseEvent.CLICK, menuReturn);
}
function removeMenuListeners():void
{
mainMenu.playBtn.removeEventListener(MouseEvent.CLICK, startGame);
mainMenu.howToPlayBtn.removeEventListener(MouseEvent.CLICK, showInstructions);
mainMenu.aboutBtn.removeEventListener(MouseEvent.CLICK, showAbout);
howtoPlay.backBtn.removeEventListener(MouseEvent.CLICK, menuReturn);
gameEnd.playagainBtn.removeEventListener(MouseEvent.CLICK, startGame);
gameAbout.backBtn.removeEventListener(MouseEvent.CLICK, menuReturn);
}
public function showInstructions(e:Event)
{
menuLayer.removeChild(mainMenu);
interfaceLayer.addChild(howtoPlay);
}
function sendEnemy(e:Event)
{
var enemy = new EnemyShip();
gameLayer.addChild(enemy);
gameLayer.addChild(crosshair);
}
function sendEnemyMed(e:Event)
{
var enemymed = new EnemyShipMed();
gameLayer.addChild(enemymed);
gameLayer.addChild(crosshair);
}
function sendEnemySmall(e:Event)
{
var enemysmall = new EnemyShipSmall();
gameLayer.addChild(enemysmall);
gameLayer.addChild(crosshair);
}
static function updateScore(points)
{
score += points;
scoreText.text = String(score);
scoreHeader.setTextFormat(scoreFormat);
scoreText.setTextFormat(scoreFormat);
}
static function resetScore()
{
score = 0;
scoreText.text = String(score);
scoreText.setTextFormat(scoreFormat);
}
function updateTime(e:TimerEvent):void
{
gameTime--;
timeText.defaultTextFormat = scoreFormat;
timeText.text = String(gameTime);
}
function timeExpired(e:TimerEvent):void
{
var gameTimer:Timer = e.target as Timer;
gameTimer.removeEventListener(TimerEvent.TIMER, updateTime)
gameTimer.removeEventListener(TimerEvent.TIMER, timeExpired)
interfaceLayer.addChild(gameEnd);
var thisFont:Font = new myFont();
var myFormat:TextFormat = new TextFormat();
myFormat.font = thisFont.fontName;
scoreText = new TextField();
scoreText.defaultTextFormat = myFormat;
scoreText.text = String(score);
interfaceLayer.addChild(scoreText);
scoreText.x = 278;
scoreText.y = 180;
scoreText.selectable = false;
scoreText.embedFonts = true;
scoreText.antiAliasType = AntiAliasType.ADVANCED;
scoreText.setTextFormat(gameOverscoreFormat);
Mouse.show();
removeChild(gameLayer);
addMenuListeners();
}
function moveCursor(event:Event)
{
crosshair.x=mouseX;
crosshair.y=mouseY;
}
}
}
I'm not quite sure how to fix this, so any advice or solution will be welcome. I can't get it to work the way I intended without getting errors.
Thanks.
I believe the problem is calling menuLayer.removeChild(mainMenu); on the second play-through is throwing the error due to the fact that you'd already removed it once already. The quickest solution would be to do a check to ensure menuLayer contains mainMenu before you try and remove it:
if(menuLayer contains mainMenu)
menuLayer.removeChild(mainMenu);
(Note that I don't have access to the IDE right now, but I think this should work)
A more robust solution would be to call a different method when the play button is clicked from the main menu that removes mainMenu from menuLayer, then calls startGame (where as playAgain calls startGame directly).
EDIT
Ok I see what you mean. Perhaps something like this instead:
mainMenu.playBtn.addEventListener(MouseEvent.CLICK, playGame);
gameEnd.playagainBtn.addEventListener(MouseEvent.CLICK, playGameAgain);
...
public function playGame(e:Event)
{
menuLayer.removeChild(mainMenu);
startGame();
}
...
public function playGameAgain(e:Event)
{
startGame();
}
...
public function startGame()
I have no idea why your code is not working, but there is no need to fret, try:
MovieClip(menuLayer.parent).removeChild(menuLayer);
You remove mainMenu in two different locations. My guess is it is being removed once and then again moments later.
if ( mainMenu.parent == menuLayer ) {
menuLayer.removeChild( mainMenu );
}
This will verify that mainMenu is actually a child of menuLayer before removing it. You cannot remove a child from a parent that isn't actually its parent. Imagine the state taking a child away and taking custody of them from a kidnapper. It's not the prettiest comparison, but it gives the right idea.
I cannot verify this without seeing how the game over is handled, but I think potentially the problem is that you are not removing your event listeners each time the game is played. Therefore when you go back to the main menu and add them again, you now have TWO listeners for playAgainBtn.
So when you end a game and click on the playAgainBtn, startGame gets called TWICE. So the first time it removes things just fine, and the second time - there's nothing to remove. This issue will potentially exist with all of your event listeners given your current design.
If this is the case you simply need to remove your event listeners when the menu is removed.
I suggest that whenever you make the menu active you add the listeners, and then remove them whenever you hide it. Maybe have two methods, addMenuListeners and removeMenuListeners
You could create these two functions and use them where appropriate :
function addMenuListeners():void
{
mainMenu.playBtn.addEventListener(MouseEvent.CLICK, startGame);
mainMenu.howToPlayBtn.addEventListener(MouseEvent.CLICK, showInstructions);
mainMenu.aboutBtn.addEventListener(MouseEvent.CLICK, showAbout);
howtoPlay.backBtn.addEventListener(MouseEvent.CLICK, menuReturn);
gameEnd.playagainBtn.addEventListener(MouseEvent.CLICK, startGame);
gameAbout.backBtn.addEventListener(MouseEvent.CLICK, menuReturn);
}
function removeMenuListeners():void
{
mainMenu.playBtn.removeEventListener(MouseEvent.CLICK, startGame);
mainMenu.howToPlayBtn.removeEventListener(MouseEvent.CLICK, showInstructions);
mainMenu.aboutBtn.removeEventListener(MouseEvent.CLICK, showAbout);
howtoPlay.backBtn.removeEventListener(MouseEvent.CLICK, menuReturn);
gameEnd.playagainBtn.removeEventListener(MouseEvent.CLICK, startGame);
gameAbout.backBtn.removeEventListener(MouseEvent.CLICK, menuReturn);
}
If you follow the rule of always removing the event listeners when not in use, you can avoid this issue.
if( mainMenu.parent ){ mainmenu.parent.removeChild( mainMenu );} Or perhaps its already removed / not added at all?
Change this line
menuLayer.removeChild(mainMenu);
to this one..
if (mainMenu.parent != null && mainMenu.parent == menuLayer)
{
menuLayer.removeChild(mainMenu);
}
Hope it will solve.

Change format of any selected textfield in AS3?

I create several textfields when the click event is fired. Now I want to change the text format of any selected textfield. But the format is just applied to the last created textfield. I tried the following:
function _txtbtn(e:*):void
{
myText = new TextField();
mc3 = new MovieClip();
myText.text = "text...";
myFormat.font = "Arial";
myFormat.color = txt_color()
myText.setTextFormat(myFormat);
mc3.addChild(myText);
addChild(mc3);
mc3.x = _can.x;
mc3.y = p;
p= mc3.y+mc3.height+10;
mc3.addEventListener(MouseEvent.MOUSE_DOWN,_select)
}
function _select(e:MouseEvent):void
{
tool_stage.combo.addEventListener(Event.CHANGE,_font)
}
function _font(e:Event):void
{
format.font = tool_stage.combo.selectedLabel;
myText.setTextFormat(format);
}
It is right, because the variable myText refers to the last Object.
Instead of this you can get the current TextField object from the Event.
Each event has currentTarget value, which refers to the Object that has fired the Event.
You then can cast the currentTarget to your type and do the action with it.
Unfortunately I don't have your whole code, that is why I have my own version.
Have a look at it, I think it can help you.
//Main.as
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFormat;
public class Main extends Sprite
{
private var button:Sprite;
private var p:int = 50;
private var x0:int = 20;
public function Main()
{
init();
}
private function init():void
{
button = new Sprite();
button.graphics.beginFill(0xFFCC00);
button.graphics.drawRect(0, 0, 80, 20);
button.graphics.endFill();
button.addEventListener(MouseEvent.CLICK, onBtnClick);
this.addChild(button);
}
private function onBtnClick(e:*):void
{
var myFormat:TextFormat = new TextFormat();
var myText:TextField = new TextField();
var mc3:MovieClip = new MovieClip();
myText.text = "text...";
myFormat.font = "Arial";
myFormat.color = 0x000000;
myText.setTextFormat(myFormat);
mc3.addChild(myText);
addChild(mc3);
mc3.x = x0;
mc3.y = p;
p= mc3.y+mc3.height+10;
myText.addEventListener(MouseEvent.CLICK, onTextClick)
}
private function onTextClick(evt:MouseEvent):void
{
var newFormat:TextFormat = new TextFormat();
newFormat.size = 30;
newFormat.font = "Verdana";
(evt.currentTarget as TextField).setTextFormat(newFormat);
}
}
}

How to change a type Number variable through a text field

I was working on a little practice project in AS3 and I ran into a problem. I'm making a MS Paint style drawing program and I want the user to be able to change the brush size with an input field. I have two issues. The first is that I don't know how to make an input field through code, and the second is I don't know how to pass the variable from the input field on the stage to the variable controlling the brush size.
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.events.KeyboardEvent;
public class DrawingApp extends Sprite
{
var square0:Sprite;
var textField: TextField;
var textField2: TextField;
var textField3: TextField;
var square1:Sprite;
var square2:Sprite;
var square3:Sprite;
var lineColor:uint = 0x000000;
var brushSize:Number = 1;
public function DrawingApp()
{
square0 = new Sprite();
addChild(square0);
square0.graphics.lineStyle(1,0x000000);
square0.graphics.beginFill(0x000000);
square0.graphics.drawRect(0,0,30,20);
square0.graphics.endFill();
square0.x = 500;
square0.y = 10;
square1 = new Sprite();
addChild(square1);
square1.graphics.lineStyle(1,0x000000);
square1.graphics.beginFill(0x0000FF);
square1.graphics.drawRect(0,0,30,20);
square1.graphics.endFill();
square1.x = 500;
square1.y = 40;
square2 = new Sprite();
addChild(square2);
square2.graphics.lineStyle(1,0x000000);
square2.graphics.beginFill(0xff0000);
square2.graphics.drawRect(0,0,30,20);
square2.graphics.endFill();
square2.x = 500;
square2.y = 70;
textField = new TextField;
addChild(textField);
textField.x = 500;
textField.y = 100;
textField.width = 30;
textField.height = 20;
textField.text = "Eraser";
textField.selectable = false;
textField.border = true;
textField2 = new TextField;
addChild(textField2);
textField2.x = 500;
textField2.y = 130;
textField2.width = 30;
textField2.height = 20;
textField2.text = "Clear";
textField2.selectable = false;
textField2.border = true;
textField3 = new TextField;
addChild(textField3);
textField3.x = 500;
textField3.y = 160;
textField3.width = 30;
textField3.height = 20;
textField3.text = brushSize;
textField3.selectable = true;
textField3.border = true;
init();
}
private function init():void
{
graphics.lineStyle(1, lineColor, 1);
square0.addEventListener(MouseEvent.CLICK, changetoDefault);
square1.addEventListener(MouseEvent.CLICK, changetoBlue);
square2.addEventListener(MouseEvent.CLICK, changetoRed);
textField.addEventListener(MouseEvent.CLICK, changetoEraser);
textField2.addEventListener(MouseEvent.CLICK, clearAll);
textField3.addEventListener(KeyboardEvent.KEY_DOWN, adjustSize);
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseIsDown);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseIsUp);
}
private function changetoEraser(event: MouseEvent):void
{
lineColor = 0xffffff;
graphics.lineStyle(brushSize, lineColor, 1);
}
private function adjustSize(event: KeyboardEvent)
{
brushSize = textField3.text;
graphics.lineStyle(brushSize, lineColor, 1);
}
private function clearAll(event:MouseEvent):void
{
graphics.clear();
graphics.lineStyle(brushSize, lineColor, 1);
}
private function changetoDefault(event: MouseEvent):void
{
lineColor = 0x000000;
graphics.lineStyle(brushSize, lineColor, 1);
}
private function changetoBlue(event: MouseEvent):void
{
lineColor = 0x0000ff;
graphics.lineStyle(brushSize, lineColor, 1);
}
private function changetoRed(event: MouseEvent):void
{
lineColor = 0xff0000;
graphics.lineStyle(brushSize, lineColor, 1);
}
private function mouseIsDown(event: MouseEvent):void
{
graphics.moveTo(mouseX, mouseY);
stage.addEventListener(MouseEvent.MOUSE_MOVE, moveMyMouse);
}
private function mouseIsUp(event: MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_MOVE, moveMyMouse);
}
private function moveMyMouse(event:MouseEvent):void
{
graphics.lineTo(mouseX, mouseY);
}
}
}
I realized that setting brushSize to textField3.text wouldn't work because it's converting string to number. I have no clue how I can make it so that way this works. Thanks to anyone who can shed some light on this for me.
You can make an input field from code in Flash by making a TextField and setting its type to TextFieldType.INPUT.
In order to convert a string to a number you will have to use parseFloat() or parseInt() (I don't know whether you need an integer or a float by heart).
Though minimal, I do think this should be enough to help you get you going again.