Creating obstacles in AS3 - actionscript-3

I'm having troubles with creating obstacles in Flash. I managed somehow to create obstacles but are only visible if there is no background. When adding one they simply disappear...
Here's the code for the main.as file:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.filters.BitmapFilterQuality;
import flash.filters.BlurFilter;
import flash.utils.setInterval;
import flash.utils.clearInterval;
public class Main extends MovieClip {
private var obstacleArray:Array;
private var obstacleInterval:uint;
private var rural2:Rural2;
private var rural3:Rural2;
private var cityFront2:CityFront2;
private var cityFront3:CityFront2;
private var cityBack2:CityBack2;
private var cityBack3:CityBack2;
private var skyline:Skyline;
private var skyline2:Skyline;
public var ship:Ship;
public function Main() {
// constructor code
obstacleArray = new Array();
obstacleInterval = setInterval(createObstacle, 1000);
addSkylineToStage();
addCityBack2ToStage();
addCityFront2ToStage();
addRural2ToStage();
createShip();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function addSkylineToStage() {
skyline = new Skyline();
/*var myBlurFilter:BlurFilter = new BlurFilter(8,8);
skyline.filters = [myBlurFilter];*/
stage.addChild(skyline);
skyline2 = new Skyline();
skyline2.x = skyline.width;
stage.addChild(skyline2);
}
private function addCityBack2ToStage() {
cityBack2 = new CityBack2();
cityBack2.y = 310;
cityBack2.x = 20;
var myBlurFilter:BlurFilter = new BlurFilter(3.7,3.7);
cityBack2.filters = [myBlurFilter];
stage.addChild(cityBack2);
cityBack3 = new CityBack2();
cityBack3.y = 310;
cityBack3.x = cityBack2.width-20;
cityBack3.filters = [myBlurFilter];
stage.addChild(cityBack3);
}
private function addCityFront2ToStage() {
cityFront2 = new CityFront2();
cityFront2.y = 310;
var myBlurFilter:BlurFilter = new BlurFilter(2.3,2.3);
cityFront2.filters = [myBlurFilter];
stage.addChild(cityFront2);
cityFront3 = new CityFront2();
cityFront3.y = 310;
cityFront3.x = cityFront2.width-8;
cityFront3.filters = [myBlurFilter];
stage.addChild(cityFront3);
}
private function addRural2ToStage() {
rural2 = new Rural2();
rural2.y = 410;
stage.addChild(rural2);
rural3 = new Rural2();
rural3.y = 410;
rural3.x = rural2.width-2;
stage.addChild(rural3);
}
var position:String = 'bottom';
private function createObstacle(){
if(position == 'bottom'){
position = 'top';
}else{
position = 'bottom';
}
var obstacle:Obstacle = new Obstacle(stage,position);
obstacleArray.push(obstacle);
obstacle.x = stage.stageWidth;
addChild(obstacle);
}
private function stopObstacles(){
for(var i:int = 0; i<obstacleArray.length;i++){
var obstacle:Obstacle = obstacleArray[i];
obstacle.removeEvents();
}
clearInterval(obstacleInterval);
}
private function onEnterFrame(evt:Event) {
rural2.x -= 2;
rural3.x -= 2;
if(rural2.x <= -rural2.width){
rural2.x = rural3.width-4;
}
if(rural3.x <= -rural3.width){
rural3.x = rural2.width-4;
}
cityFront2.x -= 1;
cityFront3.x -= 1;
if(cityFront2.x <= -cityFront2.width){
cityFront2.x = cityFront3.width-15;
}
if(cityFront3.x <= -cityFront3.width){
cityFront3.x = cityFront2.width-15;
}
cityBack2.x -= 0.5;
cityBack3.x -= 0.5;
if(cityBack2.x <= -cityBack2.width){
cityBack2.x = cityBack3.width-50;
}
if(cityBack3.x <= -cityBack3.width){
cityBack3.x = cityBack2.width-50;
}
skyline.x -= 0.25;
skyline2.x -= 0.25;
if(skyline.x <= -skyline.width){
skyline.x = skyline2.width-2;
}
if(skyline2.x <= -skyline2.width){
skyline2.x = skyline.width-2;
}
for(var i:int = 0; i<obstacleArray.length; i++){
var obstacle:Obstacle = obstacleArray[i];
if(obstacle.hitTestObject(ship)){
stage.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
stopObstacles();
}
}
}
public function createShip() {
ship = new Ship(stage);
stage.addChild(ship);
ship.x = 20;
ship.y = 180;
}
}
}
And the code for obstacles.as file:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;
public class Obstacle extends MovieClip {
private var speed:Number = 3;
private var mPosition:String;
private var mStage:Stage;
public function Obstacle(stage:Stage, position:String = 'bottom') {
// constructor code
mPosition = position;
mStage = stage;
addEvents();
setPosition();
}
private function setPosition(){
var factor:Number = Math.random()+0.3;
this.scaleY = factor;
if(mPosition == 'bottom'){
this.y = mStage.stageHeight - this.height;
}else{
this.y = 0;
}
}
private function addEvents(){
addEventListener(Event.ENTER_FRAME, onFrame);
}
public function removeEvents(){
removeEventListener(Event.ENTER_FRAME, onFrame);
}
private function onFrame(evt:Event){
this.x -= speed;
}
}
}
How can I tweak the code, so both the parallax background and obstacles will be seen on the stage?
Thank you!

Oh, initially I missed the "setInterval" in your code which should indeed add your obstacles over the other elements. Maybe try setting their index to the top when they get added? So:
addChildAt(obstacle,stage.numChildren-1)
For testing layering issues, you can try setting all your elements alpha to 0.5 so you can see if something is on the stage but behind other elements or just not getting added to the stage.
Also, http://www.monsterdebugger.com is really helpful for debugging display list issues because you can select elements in the debugger and see their location on the screen.

Related

Passing an object reference between classes AS3

Making a map creation program. Field.as instantiates _player. Player.as addsChild _editorPanel to parent. EditorPanel.as instantiates a movieclip called tilepalette when I click a button in the editor panel. Tilepalette holds all of my tilesets that I want to be able to choose a tile from by clicking the tile that I want.
Field.as:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.display.FrameLabel;
import flash.display.DisplayObjectContainer;
import flash.geom.Rectangle;
public class Field extends MovieClip{
private var player:Player;
private var sampleTile:Tile = new Tile();
private var _tilePalette:TilePalette;
private var _paletteArray:Array = [];
public function Field()
{
player = new Player();
player.x = 0;
player.y = 0;
addChild(player);
GetSampleTiles();
}
private function GetSampleTiles()
{
for (var i:int = 1; i <= sampleTile.totalFrames; i++)
{
var tileObj:Object = new Object();
sampleTile.gotoAndStop(i);
var graphicData:BitmapData = new BitmapData(32,32);
graphicData.draw(sampleTile);
tileObj.Name = sampleTile.currentFrameLabel;
tileObj.Graphic = graphicData;
tileObj.Frame = sampleTile.currentFrame;
Engine._tilesData.push(tileObj);
}
}
}
}
Player.as:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.display.BitmapData;
import flash.display.Bitmap;
public class Player extends MovieClip
{
private var _inp:Input = new Input();
private var _playerXindex:int = 0;
private var _playerYindex:int = 0;
private var _heldTile:Object;
private var _editorPanel:EditorPanel;
public function Player()
{
addChild(_inp);
addEventListener(Event.ENTER_FRAME, HandleKeys);
_heldTile = new Object();
}
private function HandleKeys(e:Event)
{
_playerXindex = x/32;
_playerYindex = y/32;
if(_inp.keyUp)
{
y -= 32;
}
if(_inp.keyDown)
{
y += 32;
}
if(_inp.keyLeft)
{
x -= 32;
}
if(_inp.keyRight)
{
x += 32;
}
if(_inp.keySpace)
{
try{DrawATile(_heldTile);}
catch(err:Error){trace("Bad or no graphic. Using this instead.");}
finally{DrawATile(Engine._tilesData[0]);}
}
if(_inp.keyA)
{
trace(Engine.tileObjIndex[_playerYindex][_playerXindex].Name);
}
if(_inp.keyB)
{
BuildStarterIndex();
SetHeldTile(Engine._tilesData[0]);
}
}
private function DrawATile(tileToDraw:Object)
{
if (Engine.tileObjIndex[_playerYindex][_playerXindex].Name.indexOf("Placeholder") >= 0)
{
trace("set");
var graphicData:BitmapData = new BitmapData(32,32);
graphicData.draw(tileToDraw.Graphic);
Engine.tileObjIndex[_playerYindex][_playerXindex].Name = tileToDraw.Name;
Engine.tileObjIndex[_playerYindex][_playerXindex].Graphic = tileToDraw.Graphic;
var newTile:Bitmap = new Bitmap(tileToDraw.Graphic);
newTile.x = x;
newTile.y = y;
parent.addChild(newTile);
}
}
private function BuildStarterIndex()
{
_editorPanel = new EditorPanel();
_editorPanel.x = 1;
_editorPanel.y = 544;
parent.addChild(_editorPanel);
for (var i:int = 0; i < 20; i++)
{
Engine.tileObjIndex[i] = [];
for (var u:int = 0; u < 20; u++)
{
var tileObj:Object = new Object();
var graphicData:BitmapData = new BitmapData(32,32);
graphicData.draw(Engine._tilesData[0].Graphic);
tileObj.Name = "Placeholder" + "["+i+"]"+"["+u+"]";
tileObj.Graphic = graphicData;
tileObj.Frame = 0;
Engine.tileObjIndex[i].push(tileObj);
}
}
}
private function SetHeldTile(tiletoset:Object)
{
_heldTile.Name = tiletoset.Name;
_heldTile.Graphic = tiletoset.Graphic;
_heldTile.Frame = tiletoset.Frame;
_editorPanel.tileName.text = _heldTile.Name;
_editorPanel.tileFrame.text = _heldTile.Frame;
var heldTile:Bitmap = new Bitmap(_heldTile.Graphic);
heldTile.x = 30;
heldTile.y = 31;
_editorPanel.addChild(heldTile);
}
}
}
EditorPanel.as:
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.display.Bitmap;
import flash.events.Event;
public class EditorPanel extends MovieClip
{
public var _tilePalette:TilePalette;
private var _pArray:Array = [];
private var _mouseXi:int;
private var _mouseYi:int;
public var _tileGrabbed:Object;
public function EditorPanel()
{
btnpalette.addEventListener(MouseEvent.CLICK, BuildPalette);
}
private function UpdateMouse(e:Event)
{
_mouseXi = Math.floor(_tilePalette.mouseX/32);
_mouseYi = Math.floor(_tilePalette.mouseY/32);
}
private function BuildPalette(e:MouseEvent)
{
_tilePalette = new TilePalette();
_tilePalette.x = mouseX;
_tilePalette.y = mouseY-256;
addChild(_tilePalette);
var counter:int = 1;
for (var i:int = 0; i < 8; i++)
{
_pArray[i] = [];
for(var u:int = 0; u < 8; u++)
{
if(counter >= Engine._tilesData.length)
{
counter = 1;
}
var b:Bitmap = new Bitmap(Engine._tilesData[counter].Graphic);
b.x = 32 * u;
b.y = 32 * i;
_tilePalette.addChild(b);
_pArray[i].push(Engine._tilesData[counter]);
counter++;
}
}
_tilePalette.addEventListener(MouseEvent.MOUSE_MOVE, UpdateMouse);
_tilePalette.addEventListener(MouseEvent.CLICK, GrabATile);
}
private function GrabATile(e:MouseEvent)
{
return _pArray[_mouseXi][_mouseYi];
}
}
}
The problem is that when I do GrabATile, I don't know what to do with the returned Object reference. I want to use that Object in the Player function SetHeldTile.
So this will make it work, but I would suggest looking to refactor that code a bit. Adding children that add things to their parents is not the best design... There is also round robin stuff going on there where the editor selects the tile, but then the player sets things like tileName back on the editor after it is told about the new tile. This should occur in the editor where tile selection occurs etc.
That said, depending on your flow, here is how to make it work:
EditorPanel already has a property _tileGrabbed. so in your GrabATile() method just set
_tileGrabbed = _pArray[_mouseXi][_mouseYi];
Then in your setHeldTile() method... simply say
_heldTile = _editorPanel._tileGrabbed.
Now, if you need GrabATile() to TRIGGER setHeldTile(), the best way to handle that would be with an event.
// in EditorPanel
private function GrabATile(e:MouseEvent){
_tileGrabbed = _pArray[_mouseXi][_mouseYi];
dispatchEvent(new Event("tileChanged"));
}
// in Player
private function BuildStarterIndex(){
_editorPanel = new EditorPanel();
_editorPanel.addEventListener("tileChanged", setHeldTile);
// ... rest of code
}
private function SetHeldTile(event:Event){
_heldTile = _editorPanel._tileGrabbed;
// ... rest of code
}

Null object reference actionscript 3

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.

Error 1006: Not a function

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);

actionscript 3 new game btn in main menu not working

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/

Need to know which sprite was clicked

This is my level selector for a game. You can choose level 1-8, I need to know which one was clicked. e.target doesn't give me much besides the name of the object. I need to know either the place in the array or the name of the picture so I know which level to load up.
package
{
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
public class LevelSelector extends Sprite
{
private var posX:int = 50;
private var posY:int = 50;
[Embed(source="../lib/one.png")]
private var lvl1Class:Class;
private var lvl1:Bitmap = new lvl1Class();
[Embed(source="../lib/two.png")]
private var lvl2Class:Class;
private var lvl2:Bitmap = new lvl2Class();
[Embed(source="../lib/three.png")]
private var lvl3Class:Class;
private var lvl3:Bitmap = new lvl3Class();
[Embed(source="../lib/four.png")]
private var lvl4Class:Class;
private var lvl4:Bitmap = new lvl4Class();
[Embed(source="../lib/five.png")]
private var lvl5Class:Class;
private var lvl5:Bitmap = new lvl5Class();
[Embed(source="../lib/six.png")]
private var lvl6Class:Class;
private var lvl6:Bitmap = new lvl6Class();
[Embed(source="../lib/seven.png")]
private var lvl7Class:Class;
private var lvl7:Bitmap = new lvl7Class();
[Embed(source="../lib/eight.png")]
private var lvl8Class:Class;
private var lvl8:Bitmap = new lvl8Class();
private var myArrayBitmaps:Array = new Array;
private var myArraySprites:Array = new Array;
private var yCounter:int = 1;
public function LevelSelector():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
myArrayBitmaps.push(false, lvl1, lvl2, lvl3, lvl4, lvl5, lvl6, lvl7, lvl8);
for (var i:int = 1; i < 9; i++)
{
myArrayBitmaps[i].x = posX;
myArrayBitmaps[i].y = posY;
myArrayBitmaps[i].height = 50;
myArrayBitmaps[i].width = 100;
//myArrayBitmaps[i].name = "lvl_" + i + "";
myArraySprites[i] = new Sprite();
myArraySprites[i].addChild(myArrayBitmaps[i]);
myArraySprites[i].x = posX;
myArraySprites[i].y = posY;
//myArraySprites[i].name = "lvl_" + i + "";
stage.addChild(myArraySprites[i]);
myArraySprites[i].addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void {
removeThis(e, this);
});
posX += 100;
yCounter += 1;
if (yCounter == 5) {
posY += 100;
posX -= 400;
}
}
}
private function removeThis(e:MouseEvent, temp):void
{
//Need to know the number which was passed, 1-8
}
}
}
I would do something like this:
//...
private function init(e:Event = null):void
{
//...
for (var i:int = 1; i < 9; i++)
{
//...
myArraySprites[i] = new Sprite();
myArraySprites[i].addChild(myArrayBitmaps[i]);
//...
stage.addChild(myArraySprites[i]);
myArraySprites[i].addEventListener(MouseEvent.CLICK, removeThis);
}
}
}
private function removeThis(e:MouseEvent):void
{
var clickTarget:int = myArraySprites.indexOf(e.currentTarget);
trace("Clicked sprite (id): " + clickTarget);
}