I didn't really know what exactly to ask in the question. So I am going to explain everything here:
I am working on a Desktop AIR Database Application I have a Class named "Database Screen" which is linked to a movie clip:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.InteractiveObject;
import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.filesystem.FileMode;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.text.TextField;
public class DatabaseScreen extends MovieClip {
private var allButtons:Array;
private var codeSelected:Boolean;
private var nameSelected:Boolean;
private var xmlDatabase:XML;
private var dbFile:File;
public var xmlList:XMLList;
private var totalProducts:uint;
private var totalItems:uint = 0;
private var productExists:Boolean;
private var productId:Number;
private var XMLReader:xmlReader;
public function DatabaseScreen() {
allButtons = [searchPanel.search_btn, addNewPanel.addNew_btn, dbStatsPanel.xls_btn, searchPanel.code_radio, searchPanel.name_radio];
init();
}
private function init():void
{
XMLReader = new xmlReader();
//adding event listeners..
for(var i:int = 0; i<allButtons.length; i++)
{
allButtons[i].addEventListener(MouseEvent.MOUSE_OVER, onOver, false, 0, true);
allButtons[i].addEventListener(MouseEvent.MOUSE_OUT, onOut, false, 0, true);
allButtons[i].addEventListener(MouseEvent.MOUSE_DOWN, onDown, false, 0, true);
allButtons[i].addEventListener(MouseEvent.MOUSE_UP, onUp, false, 0, true);
allButtons[i].addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
allButtons[i].buttonMode = true;
}
//creating a new file for the database
dbFile = File.documentsDirectory.resolvePath("BlackCat/Database.xml");
xmlDatabase = new XML();
getXML();
saveXML();
getTotalItems();
dbStatsPanel.items.text = String(totalItems);
}
private function getXML():void
{
if(dbFile.exists)
{
var stream:FileStream = new FileStream();
stream.open(dbFile, FileMode.READ);
xmlDatabase = new XML(stream.readUTFBytes(stream.bytesAvailable));
stream.close();
xmlList = xmlDatabase.Product;
dbStatsPanel.products.text = xmlList.length();
XMLReader.xmlData = xmlList;
XMLReader.updateXMLList(xmlList);
}
else
{
xmlDatabase = <Products></Products>
}
}
public function getXMlList():XMLList
{
return xmlList;
}
private function getTotalItems():void
{
for(var i:int = 0; i < xmlList.length(); i++)
{
totalItems += uint(xmlList[i].#Qty);
}
}
private function saveXML():void
{
var stream:FileStream = new FileStream();
stream.open(dbFile, FileMode.WRITE);
stream.writeUTFBytes(xmlDatabase.toXMLString());
}
private function onDown(evt:MouseEvent):void
{
evt.target.scaleX = evt.target.scaleY = .8;
}
private function onUp(evt:MouseEvent):void
{
evt.target.scaleX = evt.target.scaleY = 1;
}
private function onOver(evt:MouseEvent):void
{
evt.target.alpha = .5;
}
private function onOut(evt:MouseEvent):void
{
evt.target.alpha = 1;
evt.target.scaleX = evt.target.scaleY = 1;
}
private function onClick(evt:MouseEvent):void
{
switch(evt.target.name)
{
case "code_radio":
codeSelected = true;
nameSelected = false;
searchPanel.code_radio.gotoAndStop(1);
searchPanel.name_radio.gotoAndStop(2);
break;
case "name_radio":
nameSelected = true;
codeSelected = false;
searchPanel.code_radio.gotoAndStop(2);
searchPanel.name_radio.gotoAndStop(1);
break;
case "addNew_btn":
//Checking if the product already exists..
for(var i:int = 0; i < xmlList.length(); i++)
{
if(xmlList[i].#code == addNewPanel.add_code_txt.text)
{
productExists = true;
productId = i;
}
}
if(productExists)
{
var PQty:uint = uint(xmlList[productId].#Qty);
var PQtoAdd:uint = uint(addNewPanel.add_qty_txt.text);
PQty += PQtoAdd;
xmlList[productId].#Qty = String(PQty);
productExists = false;
}
else
{
xmlDatabase.appendChild(<Product code={addNewPanel.add_code_txt.text}
name={addNewPanel.add_name_txt.text} Price={addNewPanel.add_price_txt.text}
Qty={addNewPanel.add_qty_txt.text}></Product>);
}
totalItems += uint(addNewPanel.add_qty_txt.text);
xmlList = xmlDatabase.Product;
dbStatsPanel.products.text = xmlList.length();
dbStatsPanel.items.text = String(totalItems);
XMLReader.updateXMLList(xmlList);
saveXML();
trace(xmlDatabase);
break;
}
}
public function setVisiblity(visibility:Boolean):void
{
switch(visibility)
{
case true:
this.visible = true;
break;
case false:
this.visible = false;
break;
}
}
public function getXMLList():XMLList
{
return xmlList;
}
}
}
And I have another class named "NewOrder", in this class I am trying to access the xmlList from the "DatabaseScreen" class but I am unable to do so.
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import com.greensock.TweenMax;
import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.filesystem.FileMode;
public class NewOrder extends MovieClip {
private var allButtons:Array;
private var shoppingCart:Array;
private var scroller:FlickScroll;
private var db:DatabaseScreen;
private var XMLReader:xmlReader;
public function NewOrder() {
this.visible = false;
init(db);
}
private function init(dbase:DatabaseScreen):void
{
XMLReader = new xmlReader();
trace(XMLReader.xmlData);
scroller = new FlickScroll(masker, container, 84.05, -500);
addChild(scroller);
allButtons = [scan_btn, print_invoice];
shoppingCart = [];
for(var i:int = 0; i < allButtons.length; i++)
{
allButtons[i].addEventListener(MouseEvent.MOUSE_OVER, onOver, false, 0, true);
allButtons[i].addEventListener(MouseEvent.MOUSE_OUT, onOut, false, 0, true);
allButtons[i].addEventListener(MouseEvent.MOUSE_DOWN, onDown, false, 0, true);
allButtons[i].addEventListener(MouseEvent.MOUSE_UP, onUp, false, 0, true);
allButtons[i].mouseChildren = false;
allButtons[i].buttonMode = true;
}
}
private function onOver(evt:MouseEvent):void
{
evt.target.alpha = .5;
}
private function onOut(evt:MouseEvent):void
{
evt.target.alpha = 1;
evt.target.scaleX = evt.target.scaleY = 1;
}
private function onDown(evt:MouseEvent):void
{
evt.target.scaleX = evt.target.scaleY = .8;
}
private function onUp(evt:MouseEvent):void
{
evt.target.scaleX = evt.target.scaleY = 1;
if(evt.target.name == "scan_btn")
{
var cartElement:CartElement = new CartElement();
container.addChild(cartElement);
cartElement.x = 0;
cartElement.alpha = 0;
TweenMax.to(cartElement, .4, {alpha:1});
shoppingCart.push(cartElement);
cartElement.id_txt.text = String(shoppingCart.length) + " - ";
if(shoppingCart.length < 2)
{
cartElement.y = container.height - 30;
}
else
{
cartElement.y = container.height + 5;
}
}
}
}
}
And there is a Main class in which I handle all the screens , e.g DatabaseScreen, NewOrder.. Which means I have added these to the display list in the Main class. To access the xmlList from the DatabaseScreen , I tried creating a new instance in the NewOrder class, but it creates to DatabaseScreen(s). I also tried creating another class named "xmlReader":
package {
public class xmlReader {
public var xmlData:XMLList;
public function xmlReader() {
}
public function updateXMLList(updatedList:XMLList):void
{
xmlData = updatedList;
}
}
}
In the databaseScreen class, as soon as I populate the xmlList , I set the xmlData of the xmlReader class equal to the xmlList from the databaseScreen class. And when I trace the XMLReader.xmlData in the databaseScreen , it works fine . But when I do the same thing in the NewOrder class, I get "null" in the output window.
How do I solve this problem. Any help is greatly appreciated.
You will need to pass a reference into the Order class to have access to the DatabaseScreen class. Something like this.
var ds = new DatabaseScreen();
var or = new NewOrder(ds)
Inside the NewOrder you can save the ref.
public class NewOrder {
private var screens:DatabaseScreens;
public function NewOrder(ds:DatabaseScreens) {
screens = ds;
// Now you can call screens.xmlList
}
}
Related
i'm just getting started programming and wanted to know how to make the cards i made in actions script a random color with a MouseEvent. I have to do this for a a school project in Animate (adobe). (This is also the first time using this website). This is my code:
This is the card.as:
package {
import flash.display.MovieClip;
import flash.geom.ColorTransform;
import flash.text.TextField;
public class card extends MovieClip {
//praperties
public var cardNumber:int;
public var cardColor:ColorTransform;
public var cardType:String;
public var minNum:Number;
public var maxNum:Number;
public var textBox:TextField;
//constructor
public function card() {
cardType = randomCardType();
cardNumber = 5;
cardColor = randomcardColor();
trace(cardColor);
trace(cardType);
transform.colorTransform = cardColor;
textBox = new TextField();
addChild(textBox);
textBox.text = String(cardType + "\n" + cardNumber);
textBox.width = 100;
textBox.height = 100;
textBox.border = true;
}
//methods
public function printinfo() :void {
trace("cardNumber: '" + cardNumber + "'");
}
public function randomcardColor():ColorTransform {
var kleur:ColorTransform = new ColorTransform();
kleur.color = (Math.random() * 0xFFFFFF);
return kleur;
}
public function randomCardType(){
var Name:Array = ["Knight","Archer","Wizard","Priest"];
var randomNum:int = Math.floor(Math.random()* Name.length);
return Name[randomNum];
}
function randomRange(minNum:Number, maxNum:Number):Number {
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
public function checkcardColor (otherColor) {
if (cardColor == otherColor) {
return true;
}
else {
return false;
}
}
}
}
and this is the cardgame.as:
package {
import flash.display.MovieClip;
import fl.motion.Color;
public class cardgame extends MovieClip {
//proparties
public var cardA:card;
public var cardB:card;
public var cardC:card;
public var cardD:card;
// constructor code
public function cardgame() {
cardA = new card();
cardA.x = 100;
cardA.y = 100;
cardA.width = 100;
cardA.height = 100;
this.addChild(cardA);
cardB = new card();
cardB.x = 450;
cardB.y = 100;
cardB.width = 100;
cardB.height = 100;
this.addChild(cardB);
cardC = new card();
cardC.x = 450;
cardC.y = 300;
cardC.width = 100;
cardC.height = 100;
this.addChild(cardC);
cardD = new card();
cardD.x = 100;
cardD.y = 300;
cardD.width = 100;
cardD.height = 100;
this.addChild(cardD);
showMeTheWorld();
}
//methods
public function showMeTheWorld() {
cardA.printinfo();
cardB.printinfo();
cardC.printinfo();
cardD.printinfo();
}
}
}
put following, inside constructor (public function card() {/*Here*/})
this.addEventListener(MouseEvent.CLICK, cardClicked);
also you had done the random color function
so put it in your card class
public function cardClicked(e:MouseEvent):void {
MovieClip(e.target).colorTransform = randomcardColor();
}
don't forget importing MouseEvent
read more about EventListener
i make a class like this:
package
{
import flash.display.Sprite;
import flash.text.TextField;
public class Hint extends Sprite
{
public static var _instance:Hint = null;
public function Hint()
{
_instance = this;
}
public function DrawHintText():void
{
Const._scoreText = new TextField();
Const._scoreTextHolder = new TextField();
Const._highScoreText = new TextField();
Const._highScoreTextHolder = new TextField();
Const._timeLeft = new TextField();
Const._timeLeftHolder = new TextField();
Const._scoreTextHolder.textColor = 0xFFFFFF;
Const._scoreTextHolder.x = stage.stageWidth - 350;
Const._scoreTextHolder.y = 100;
Const._scoreTextHolder.text = "Score: ";
Const._scoreTextHolder.selectable = false;
Const._scoreText.textColor = 0xFFFFFF;
Const._scoreText.x = stage.stageWidth - 250;
Const._scoreText.y = 100;
Const._scoreText.text = "--";
Const._scoreText.selectable = false;
Const._highScoreTextHolder.textColor = 0xFFFFFF;
Const._highScoreTextHolder.x = stage.stageWidth - 350;
Const._highScoreTextHolder.y = 150;
Const._highScoreTextHolder.text = "High Score: ";
Const._highScoreTextHolder.selectable = false;
Const._highScoreText.textColor = 0xFFFFFF;
Const._highScoreText.x = stage.stageWidth - 250;
Const._highScoreText.y = 150;
Const._highScoreText.text = "--";
Const._highScoreText.selectable = false;
Const._timeLeftHolder.textColor = 0xFF0000;
Const._timeLeftHolder.x = stage.stageWidth - 350;
Const._timeLeftHolder.y = 200;
Const._timeLeftHolder.text = "Time Left: ";
Const._timeLeftHolder.selectable = false;
Const._timeLeft.textColor = 0xFF0000;
Const._timeLeft.x = stage.stageWidth - 275;
Const._timeLeft.y = 200;
Const._timeLeft.text = "00:00";
Const._timeLeft.selectable = false;
addChild(Const._scoreText);
addChild(Const._scoreTextHolder);
addChild(Const._highScoreText);
addChild(Const._highScoreTextHolder);
addChild(Const._timeLeft);
addChild(Const._timeLeftHolder);
}
}
}
and i called on the GameManager:
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.text.TextField;
[SWF(width='1366',height='768',backgroundColor='#000000',frameRate='30')]
public class GameManager extends Sprite
{
public function GameManager():void
{
DrawHintText();
GenerateField();
ShowField();
GenerateGems();
}
private function GenerateField():void
{
Const._gridField = new Array();
for (var i:uint = 0; i < Const._gridSizeY; i++)
{
Const._gridField[i] = new Array();
for (var j:uint = 0; j < Const._gridSizeX; j++)
{
Const._gridField[i][j] = 0;
}
}
}
private function ShowField():void
{
Const._fieldSprite = new Sprite();
addChild(Const._fieldSprite);
Const._fieldSprite.graphics.lineStyle(1, 0xFFFFFF);
for (var i:uint = 0; i < Const._gridSizeY; i++)
{
for (var j:uint = 0; j < Const._gridSizeX; j++)
{
Const._fieldSprite.graphics.beginFill(0x666666);
Const._fieldSprite.graphics.drawRect(25 + 65 * j, 80 + 60 * i, 65, 60);
Const._fieldSprite.graphics.endFill();
}
}
}
private function DrawHintText():void
{
Hint._instance.DrawHintText();
}
private function GenerateGems():void
{
}
}
}
and here is the Const:
package
{
import flash.display.Sprite;
import flash.text.TextField;
public class Const
{
public static var _gridField:Array;
public static var _fieldSprite:Sprite;
public static var _scoreText:TextField;
public static var _scoreTextHolder:TextField;
public static var _highScoreText:TextField;
public static var _highScoreTextHolder:TextField;
public static var _timeLeft:TextField;
public static var _timeLeftHolder:TextField;
public static const _gridSizeX:Number = 10;
public static const _gridSizeY:Number = 10;
public function Const()
{
}
}
}
when i run the code, i got the error:
Where do i miss some code?
Invoking function DrawHintText() in Hint._instance.DrawHintText(); doesn't create instance of class Hint.
Try to substite your public variable with public getter.
private static var __instance:Hint = null;
public static function get _instance():Hint {
if (!__instance) {
__instance = new Hint();
}
return __instance;
}
And drop constructor, because getter makes it unnecessary.
Might be a silly question, but are you actually creating instance of Hint somewhere?
Because as long as you don't do new Hint() that Hint._instance will be null.
Try something like:
public class Hint extends Sprite
{
private static var _instance:Hint;
public function Hint()
{
if (_instance) throw new Error("Hint... use getInstance()");
_instance = this;
}
public static function getInstance():Hint
{
if (!_instance) new Hint();
return _instance;
}
//DrawHintText >> rename to drawHintText
public function drawHintText():void
{
//your code here
}
}
And to use:
Hint.getInstance().drawHintText();
Use Flash Builder, which costs some money, or Flash Develop. which is free. Both will show you compile time errors, with line numbers and location file.
Also at runtime will show you line number and the .as file where you have the problem.
Also autocomplete cuts your coding time by at least half time.
I am getting the error in the title when trying to access a method in another class. I have the main class, ZombieBots, which is linked to a movie clip of the same name. I then have 3 more movie clips which all get added to the ZombieBots clip during runtime, and each of these have their own classes.
When I attempt to access a method within the ZombieBots class from one of the other 3 classes, I get error 1006.
The function I am attempting to access in the ZombieBots class, that cannot be accessed:
package {
import flash.events.*;
import flash.display.MovieClip;
import flash.geom.Rectangle;
public class ZombieBots extends MovieClip{
private var pLives:int;
private var pScore:int;
private var pSkill:int;
private var pItems:int;
private var characterMC:Character;
private var cGameObjs:Array;
public function ZombieBots() {
/*cGameObjs = new Array();
addCharacter();
addItems();
addBots();
pLives = 5 - pSkill;
pScore = 0;
pItems = pSkill + 5;*/
resetGame();
}
private function addCharacter():void{
trace("Adding the character");
if (!characterMC){
var myBorder:Rectangle = new Rectangle(35,35,600,480);
var myXY:Array = [38, 400];
var myChar:int = Math.ceil(Math.random()*3);
var myKeys:Array = [37,39,38,40];
var myDistance:int = myChar * 3;
characterMC = new Character(myBorder, myXY, myKeys, myChar, myDistance);
addChild(characterMC);
}
else{
characterMC.x = 38;
characterMC.y = 510;
characterMC.gotoAndStop(pSkill);
}
}
private function addItems():void{
trace("yeah boi");
var mySkill:int = Math.ceil(Math.random() *3);
var myMaxItems:int = mySkill + 5;
trace(mySkill);
trace(myMaxItems);
trace(this);
for (var i:int = 0; i < myMaxItems; i++){
var thisItem:Item = new Item(this, characterMC, mySkill);
thisItem.name = "item" + i;
cGameObjs.push(thisItem);
addChild(thisItem);
}
pSkill = mySkill;
updateScores();
}
private function addBots():void{
trace("adding the bots bra");
var myBorder:Rectangle = new Rectangle(100,100,400,350);
var mySkill:int = Math.ceil(Math.random()*3);
var myMaxBots:int = mySkill +10;
for (var i:int = 0; i < myMaxBots; i++){
var thisBot:Bot = new Bot(myBorder, characterMC, mySkill);
thisBot.name = "bot" + i;
cGameObjs.push(thisBot);
addChild(thisBot);
}
}
private function updateScores():void{
scoreDisplay.text = String(pScore);
itemsDisplay.text = String(pItems);
livesDisplay.text = String(pLives);
msgDisplay.text = "Orc Invasion";
}
public function updateLives(myBot:MovieClip):void{
trace("update lives");
pLives--;
pScore -= myBot.getPts();
var myIndex:int = cGameObjs.indexOf(myBot);
cGameObjs.splice(myIndex, 1);
if (pLives > 0){
updateScores();
}
else{
gameOver(false);
}
}
public function updateItems(myItem:MovieClip):void{
trace("update items");
pItems--;
pScore += myItem.getPts();
var myIndex:int = cGameObjs.indexOf(myItem);
cGameObjs.splice(myIndex, 1);
if (pItems > 0){
updateScores();
}
else{
gameOver(true);
}
}
private function gameOver(bool:Boolean):void{
trace("Game over dawg");
updateScores();
if(bool){
msgDisplay.text = "Good job buddy";
}
else{
msgDisplay.text = "You suck dawg";
}
removeLeftovers();
}
private function resetGame():void{
playAgainBtn.visible = false;
playAgainBtn.removeEventListener(MouseEvent.CLICK,playAgain);
cGameObjs = new Array();
addCharacter();
addItems();
addBots();
pLives = 5 - pSkill;
pScore = 0;
pItems = pSkill + 5;
updateScores();
}
private function playAgain(evt:MouseEvent):void{
resetGame();
}
private function removeLeftovers():void{
trace("Removing leftover items and bots");
for each(var myObj in cGameObjs){
myObj.hasHitMe();
myObj = null;
}
playAgainBtn.visible = true;
playAgainBtn.addEventListener(MouseEvent.CLICK, playAgain);
}
}
}
and this is the class where I am attempting to access this function within one of the other 3 classes:
package {
import flash.display.MovieClip;
import flash.events.*;
import ZombieBots;
public class Item extends MovieClip{
private var cNumItem:int;
private var cNumPts:int;
private var characterMC:MovieClip;
private var ZombieBot:ZombieBots;
public function Item(myZB:ZombieBots, myChar:MovieClip, mySkill:int=1) {
ZombieBot = myZB;
cNumItem = Math.ceil(Math.random() * (mySkill * 3 + 1));
characterMC = myChar;
this.addEventListener(Event.ADDED_TO_STAGE,initItem);
addEventListener(Event.ENTER_FRAME, checkCollision);
}
private function initItem(evt:Event):void{
this.gotoAndStop(cNumItem);
cNumPts = cNumItem * 25;
setPosition();
this.removeEventListener(Event.ADDED_TO_STAGE,initItem);
}
private function setPosition():void{
this.x = (Math.ceil(Math.random() * 10)*50);
this.y = (Math.ceil(Math.random()*10)*35);
}
private function checkCollision(evt:Event){
if (characterMC.hitTestObject(this)){
ZombieBot.updateItems(this);
hasHitMe();
}
}
public function hasHitMe():void{
trace("remove");
removeEventListener(Event.ENTER_FRAME, checkCollision);
this.parent.removeChild(this);
}
public function getPts():int{
return cNumPts;
}
}
}
can anyone help?
updateItems is not a MovieClip method. It's a method of your ZombieBots class.
Casting your ZombieBots instance (which I am assuming is root) as a MovieClip, will only allow you to use it's class methods or methods it has inherited.
Try this :
var zombieBotsInstance:ZombieBots = root as ZombieBots;
zombieBotsInstance.updateItems(this);
I'm trying to place a dynamic generated text on a bezier curve - the text can be up to 12 charcters long, so it will need to adjust to the center.
I can't find any attempt to do this on google.
my only guess is reading a bezier curves xy, then placing the textfield on that, but how would i get the Textfield to fit to the curve?
Thanks!
Marcus
If your curve is an arc or a circle I have just the right thing for you :p
I made two classes some time ago to handle this here they come:
package com.display{
import flash.display.Sprite;
import utils.Utils;
public class PathText extends Sprite
{
private var _text:String;
private var _chars:Array;
private var _startAngle:Number;
private var _stopAngle:Number;
private var _radius:Number;
public function PathText(__text:String, __radius:Number)
{
super();
this.mouseChildren = false;
this.mouseEnabled = false;
_text = __text;
_startAngle = 0;
_radius = __radius;
_chars = new Array();
init();
}
private function init():void
{
for(var i:int = 0; i < _text.length; i++)
{
var char:Char = new Char(_text.charAt(i));
_chars.push(char);
}
drawArc(_radius);
}
public function drawArc(rad:Number):void
{
var lastAngle:Number = 0;
for(var i:int = 0; i < _chars.length; i++)
{
var angle:Number = 2 * Math.sin((_chars[i].width/2)/rad);
_chars[i].rotation = radiansToDegrees(lastAngle) + 90;
_chars[i].x = rad * Math.cos(lastAngle);
_chars[i].y = rad * Math.sin(lastAngle);
lastAngle += angle;
addChild(_chars[i]);
}
_stopAngle = radiansToDegrees(lastAngle);
}
public function destroy():void
{
for(var i:int = _chars.length; i >= 0; i--)
{
removeChild(_chars[i]);
_chars.pop().destroy();
}
}
public function get startAngle():Number
{
return _startAngle;
}
public function set startAngle(value:Number):void
{
_startAngle = value;
}
public function get stopAngle():Number
{
return _stopAngle;
}
public function set stopAngle(value:Number):void
{
_stopAngle = value;
}
private function radiansToDegrees(radians:Number):Number
{
return radians * 180 / Math.PI;
}
}
}
and the Char class:
package com.display
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
public class Char extends Sprite
{
private var _str:String;
public function Char(__str:String)
{
super();
_str = __str;
this.mouseChildren = false;
this.mouseEnabled = false;
init();
}
private function init():void
{
var _tf:TextField = new TextField();
_tf.defaultTextFormat = new TextFormat("Some Font here", 15, 0xffffff);
_tf.embedFonts = true;
_tf.mouseEnabled = false;
_tf.selectable = false;
_tf.text = _str;
_tf.autoSize = TextFieldAutoSize.LEFT;
_tf.width = _tf.textWidth;
addChild(_tf);
}
public function destroy():void
{
this.removeChildAt(0);
}
public function get str():String
{
return _str;
}
public function set str(value:String):void
{
_str = value;
}
}
}
Tell me if it works for you...
cheers!
I have a problem with my game.
When i played level 1 and i return to my main menu, the button new game doesn't work anymore.
Does anyone know what could be the problem?
this is what i have in my main menu as:
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import HomeTitel;
import InstBtn;
import NieuwBtn;
public class Hoofdmenu extends MovieClip
{
private var homeTitel:HomeTitel;
private var instBtn:InstBtn;
private var nieuwBtn:NieuwBtn;
private var inst:Instructions;
private var level1:Level1;
public function Hoofdmenu():void
{
placeHomeTitel();
placeInstructionsBtn();
placeNieuwBtn();
}
private function placeHomeTitel():void
{
homeTitel = new HomeTitel();
addChild(homeTitel);
homeTitel.x = 275;
homeTitel.y = 20;
}
private function placeInstBtn():void
{
instBtn = new InstBtn();
addChild(instBtn);
instBtn.x = 275;
instBtn.y = 225;
instBtn.addEventListener(MouseEvent.CLICK, gotoInstructions);
}
private function gotoInstructions(event:MouseEvent)
{
inst = new Instructoins();
addChild(inst);
}
private function placeNewBtn():void
{
newBtn = new NewBtn();
addChild(newBtn);
newBtn.x = 275;
newBtn.y = 175;
newBtn.addEventListener(MouseEvent.CLICK, gotoLevel1);
}
private function gotoLevel1(event:MouseEvent):void
{
level1 = new Level1();
addChild(level1);
}
}
}
this is what i have in my level1 as:
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import L1Achtergrond;
import L1Titel;
import MenuBtn;
import Sun;
import Min;
import GameOver;
import WellDone;
import VolgLevel;
import HoofdmenuBtn;
import Opnieuw;
public class Level1 extends MovieClip
{
private var back:L1Achtergrond;
private var titel:L1Titel;
private var menu:MenuBtn;
private var sun:Sun;
private var aantalSun:int = 5;
private var counter:int;
private var sunArray:Array = new Array();
private var timer:Timer;
private var min:Min;
private var gameover:GameOver;
private var welldone:WellDone;
private var volglevel:VolgLevel;
private var opn:Opnieuw;
private var hoofdBtn:HoofdmenuBtn;
private var level1:Level1;
private var level2:Level2;
private var hoofdmenu:Hoofdmenu;
public function Level1():void
{
back = new L1Achtergrond();
addChild(back);
placeTitel();
timer = new Timer(3000,1);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, startLevel1);
timer.start();
}
private function placeTitel():void
{
titel = new L1Titel();
addChild(titel);
titel.x = 275;
titel.y = 150;
}
private function startLevel1(event:TimerEvent):void
{
for (counter = 0; counter < aantalSun; counter++)
{
sun = new Sun();
sunArray.push(sun);
addChild(sun);
sun.addEventListener(MouseEvent.CLICK, checkSun);
}
min = new Min();
addChild(min);
min.x = 275;
min.y = 30;
min.play();
min.width = 40;
min.height = 20;
timer = new Timer(20000,1);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, gameOver);
timer.start();
menu = new MenuBtn();
addChild(menu);
menu.x = 510;
menu.y = 380;
menu.addEventListener(MouseEvent.CLICK, gotoHoofdmenu);
}
private function checkSun(event:MouseEvent):void
{
aantalSun--;
if (aantalSun == 0)
{
wellDone();
timer.stop();
}
}
public function wellDone():void
{
removeChild(menu);
removeChild(min);
welldone = new WellDone();
addChild(welldone);
welldone.x = 275;
welldone.y = 150;
volglevel = new VolgLevel();
addChild(volglevel);
volglevel.x = 300;
volglevel.y = 250;
volglevel.addEventListener(MouseEvent.CLICK, gotoLevel2);
hoofdBtn = new HoofdmenuBtn();
addChild(hoofdBtn);
hoofdBtn.x = 95;
hoofdBtn.y = 250;
hoofdBtn.addEventListener(MouseEvent.CLICK, gotoHoofdmenuW);
}
private function gameOver(event:TimerEvent):void
{
//timer.stop();
removeChild(min);
removeChild(menu);
for (counter = 0; counter < sunArray.length; counter++)
{
removeChild(sunArray[counter]);
}
gameover = new GameOver();
addChild(gameover);
gameover.x = 275;
gameover.y = 150;
opn = new Opnieuw();
addChild(opn);
opn.x = 300;
opn.y = 250;
opn.addEventListener(MouseEvent.CLICK, level1Opn);
hoofdBtn = new HoofdmenuBtn();
addChild(hoofdBtn);
hoofdBtn.x = 95;
hoofdBtn.y = 250;
hoofdBtn.addEventListener(MouseEvent.CLICK, gotoHoofdmenuG);
}
private function level1Opn(event:MouseEvent):void
{
removeChild(gameover);
removeChild(opn);
removeChild(hoofdBtn);
removeChild(back);
level1 = new Level1();
addChild(level1);
}
private function gotoHoofdmenu(event:MouseEvent):void
{
timer.stop();
removeChild(min);
removeChild(menu);
removeChild(back);
for (counter = 0; counter < sunArray.length; counter++)
{
removeChild(sunArray[counter]);
}
}
private function gotoHoofdmenuW(event:MouseEvent):void
{
removeChild(back);
removeChild(welldone);
removeChild(hoofdBtn);
removeChild(volglevel);
}
private function gotoHoofdmenuG(event:MouseEvent):void
{
removeChild(back);
removeChild(gameover);
removeChild(hoofdBtn);
removeChild(opn);
}
private function gotoLevel2(event:MouseEvent):void
{
removeChild(back);
removeChild(volglevel);
removeChild(hoofdBtn);
removeChild(welldone);
level2 = new Level2();
addChild(level2);
}
}
}
I think you should rebuild/redesign the structure of your game.
Now, your code does few strange things:
in your Main class: everytime you call function gotoLevel1 you create a new instance of Level1
in your Level1 class in the function level1Opn you create another instance of 'Level1' and you add it inside Level1 - quite a mess.
This isn't just small code tweak - you should rebuild it quite significantly.
Seems like you never remove level1 from your menu. Even though you remove all children from Level 1, the movieclip will still exist and be on top of your menu.
I would recommend reading though this tutorial, as it will teach you some basic skills about structuring your code, and specific game development features (sound, preloading, saving things in cookies): http://gamedev.michaeljameswilliams.com/2008/09/17/avoider-game-tutorial-1/