Passing an object reference between classes AS3 - actionscript-3

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
}

Related

Generating Random text on Collision AS3

I would like to generate some random words when an object hits another one.
I've tried it but only one word comes up and never changes again.
Also would it be better if I make a new class for the random texts or is including it in the Main class good enough? Thanks!
Here's my current code:
package {
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.Event;
public class Main extends MovieClip {
public var cell:Cell;
public var group:Array;
public var gameTimer:Timer;
public var score:int = 0;
var array:Array = new Array ("Apples",
"Bananas",
"Grapes",
"Oranges",
"Pineapples"); //create an array of possible strings
var randomIndex:int = Math.random () * array.length;
//public var randomTxt:String;
public function Main() {
group = new Array();
gameTimer = new Timer (25);
gameTimer.addEventListener(TimerEvent.TIMER,moveCell);
gameTimer.start();
}
private function createCell(_x:Number = 0, _y:Number = 0):void {
var cell:Cell = new Cell(_x, _y);
group.push(cell);
addChild(cell);
}
function moveCell (timerEvent:TimerEvent):void {
if (Math.random() < 0.01) {
var randomX:Number = Math.random()*800;
var randomY:Number = Math.random()*600;
createCell(randomX, randomY);
}
for (var i:int = 0; i < group.length; i++)
{
var cell:Cell = Cell(group[i]);
if (cell.hitTestObject(island))
{
cell.parent.removeChild(cell);
group.splice(i,1);
score++;
txtWordDisplay.text = "Killed by" + array [randomIndex];
}
}
scoreOutPut.text = score.toString();
}
}
}
It's always the same word because you only set the randomIndex once at the beginning of your program.
A simple fix would be to update that value when the collision happens:
if (cell.hitTestObject(island))
{
...
randomIndex = Math.floor(Math.random () * array.length);
txtWordDisplay.text = "Killed by" + array [randomIndex];
}

Creating obstacles in AS3

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.

how to insert sound to this code?

hello how to put sounds to this code so when tower firing bullet sound will show up together with it...i'm just nubie so i really need a help
can you help me how to put sounds in this code
this is the code
package Game
{
import flash.display.MovieClip;
import flash.events.*;
import flash.geom.*;
import Gamess.BulletThree;
import Games.BulletTwo;
public class Tower_Fire extends MovieClip
{
private var isActive:Boolean;
private var range,cooldown,damage:Number;
public function Tower_Fire()
{
isActive = false;
range = C.TOWER_FIRE_RANGE;
cooldown = C.TOWER_FIRE_COOLDOWN;
damage = C.TOWER_FIRE_DAMAGE;
this.mouseEnabled = false;
}
public function setActive()
{
isActive = true;
}
public function update()
{
if (isActive)
{
var monsters = GameController(root).monsters;
if (cooldown <= 0)
{
for (var j = 0; j < monsters.length; j++)
{
var currMonster = monsters[j];
if ((Math.pow((currMonster.x - this.x),2)
+ Math.pow((currMonster.y - this.y),2)) < this.range)
{
//spawn new bullet
var bulletRotation = (180/Math.PI)*
Math.atan2((currMonster.y - this.y),
(currMonster.x - this.x));
var newBullet = new Bullet(currMonster.x,currMonster.y,
"fire",currMonster,this.damage,bulletRotation);
newBullet.x = this.x;
newBullet.y = this.y;
GameController(root).bullets.push(newBullet);
GameController(root).mcGameStage.addChild(newBullet);
this.cooldown = C.TOWER_FIRE_COOLDOWN;
break;
}
}
}
else
{
this.cooldown -= 1;
}
}
}
}
}
Firstly, you need to export sound for AS:
and then you can play sound from code:
var sound:Sound = new Track();
sound.play();
UPDATE:
if ((Math.pow((currMonster.x - this.x),2) + Math.pow((currMonster.y - this.y),2)) < this.range)
{
//spawn new bullet
var sound:Sound = new Track();
sound.play();
var bulletRotation = (180/Math.PI)*
Math.atan2((currMonster.y - this.y), (currMonster.x - this.x));
...

Actionscript 3: Error #1009: Cannot access a property or method of a null object reference. (parent)

This is a bit difficult to explain, but I will try.
In my Main() class, let's say I have the main movieclip (bg_image) being created, and also some lines that create an instance of another class. (look at the code below)
var route = Route(Airport.return_Route);
This route instance, is then purposed to dynamically add sprite-childs to the main background from the Main() class.
I have tried to to this with the following line:
new_flight = new Flight(coordinates)
Main.bg_image.addChild(new_flight);
This seem to work pretty fine. Let's switch focus to the new_flight instance. At the Flight class, this line trace(this.parent) would return "[object Image]".I would consider this successful so far since my intention is to add the new_flight as child to bg_image, which I guess is an "object image".
The problem, however, occurs when trying to delete the "new_flight"-instance. Obviously the ideal way of doing this would be through bg_image with removeChild.
But, when my script reaches this line: Main.bg_image.removeChild(this), my script stops and returns ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller., at that line. I have also tried replacing Main.bg_image.removeChild(this) with this.parent.removeChild(this), with no luck.
I think the solution may be to use some sort of "EventDispatching"-method. But I haven't fully understood this concept yet...
The code follows. Please help. I have no idea how to make this work...
Main class:
package
{
import flash.display.MovieClip;
import flash.utils.Dictionary;
import flash.events.MouseEvent;
import flash.display.Sprite;
import flash.text.TextField;
import fl.controls.Button;
import flash.display.DisplayObject;
import Airport;
public class Main extends Sprite
{
// ------------------------
// Buttons
public var create_new_route;
public var confirm_new_route;
// images
public static var bg_image:MovieClip;
public var airport:MovieClip;
//-------------------------------
public var routeArray:Array;
public static var airportDict:Dictionary = new Dictionary();
public static var collectedAirportArray:Array = new Array();
public function Main()
{
addEventListener(Event.ADDED_TO_STAGE, init);
create_new_route = new Button();
create_new_route.label = "Create new route";
create_new_route.x = 220;
create_new_route.y = 580;
this.addChild(create_new_route)
create_new_route.addEventListener(MouseEvent.CLICK, new_route)
confirm_new_route = new Button();
confirm_new_route.label = "Confirm route";
confirm_new_route.x = 220;
confirm_new_route.y = 610;
this.addChild(confirm_new_route)
confirm_new_route.addEventListener(MouseEvent.CLICK, confirm_route)
}
public function init(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
bg_image = new Image();
addChild(bg_image);
S_USA["x"] = 180.7;
S_USA["y"] = 149.9;
S_USA["bynavn"] = "New York";
S_Norway["x"] = 423.7;
S_Norway["y"] = 76.4;
S_Norway["bynavn"] = "Oslo";
S_South_Africa["x"] = -26;
S_South_Africa["y"] = 146;
S_South_Africa["bynavn"] = "Cape Town";
S_Brazil["x"] = 226;
S_Brazil["y"] = 431.95;
S_Brazil["bynavn"] = "Rio de Janeiro";
S_France["x"] = 459.1;
S_France["y"] = 403.9;
S_France["bynavn"] = "Paris";
S_China["x"] = 716.2;
S_China["y"] = 143.3;
S_China["bynavn"] = "Beijing";
S_Australia["x"] = 809.35;
S_Australia["y"] = 414.95;
S_Australia["bynavn"] = "Sydney";
// ----------------------------------------------------
airportDict["USA"] = S_USA;
airportDict["Norway"] = S_Norway;
airportDict["South Africa"] = S_South_Africa;
airportDict["Brazil"] = S_Brazil;
airportDict["France"] = S_France;
airportDict["China"] = S_China;
airportDict["Australia"] = S_Australia;
for (var k:Object in airportDict)
{
var value = airportDict[k];
var key = k;
startList.addItem({label:key, data:key});
sluttList.addItem({label:key, data:key});
var airport:Airport = new Airport(key,airportDict[key]["bynavn"]);
airport.koordinater(airportDict[key]["x"], airportDict[key]["y"]);
collectedAirportArray.push(airport);
airport.scaleY = minScale;
airport.scaleX = minScale;
bg_image.addChild(airport);
}
// --------------------------------------------
// --------------------------------------------
// -----------------------------------------------
}
private function new_route(evt:MouseEvent):void
{
Airport.ROUTING = true;
}
public function confirm_route(evt:MouseEvent):void
{
Airport.ROUTING = false;
trace(Airport.return_ROUTE);
var route = new Route(Airport.return_ROUTE); // ***
this.addChild(route); // **
Airport.return_ROUTE = new Array();
}
}
}
Airport class:
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.display.SimpleButton;
import flash.display.Stage;
import flash.text.TextField;
import flash.text.TextFormat;
import flashx.textLayout.formats.Float;
public class Airport extends MovieClip
{
public static var ROUTING = false;
public static var return_ROUTE:Array = new Array();
//-----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
protected var navn:String;
protected var bynavn:String;
// ----------------------------------------------------------------------------
public function Airport(navninput, bynavninput)
{
this.bynavn = bynavninput;
this.navn = navninput;
this.addEventListener(MouseEvent.CLICK, clickHandler);
this.addEventListener(MouseEvent.MOUSE_OVER, hoverHandler);
}
public function zoomHandler():void
{
trace("testing complete");
}
public function koordinater(xc, yc)
{
this.x = (xc);
this.y = (yc);
}
private function clickHandler(evt:MouseEvent):void
{
trace(ROUTING)
if (ROUTING == true)
{
return_ROUTE.push([this.x, this.y])
}
}
private function hoverHandler(evt:MouseEvent):void
{
if (ROUTING == true)
{
this.alpha = 60;
this.width = 2*this.width;
this.height = 2*this.height;
this.addEventListener(MouseEvent.MOUSE_OUT, awayHandler);
}
}
private function awayHandler(evt:MouseEvent):void
{
this.width = 13;
this.height = 13;
}
}
}
Route class
package
{
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.display.MovieClip;
import Main;
public class Route
{
public var income:Number;
public var routePoints:Array;
private var routeTimer:Timer;
private var new_flight:Flight;
public function Route(route_array:Array)
{
this.routePoints = route_array
routeTimer = new Timer(2000);// 2 second
routeTimer.addEventListener(TimerEvent.TIMER, route_function);
routeTimer.start();
}
private function route_function(event:TimerEvent):void
{
for (var counter:uint = 0; counter < routePoints.length - 1; counter ++)
{
trace("Coords: ", routePoints[counter][0],routePoints[counter][1],routePoints[counter + 1][0],routePoints[counter + 1][1]);
new_flight = new Flight(routePoints[counter][0],routePoints[counter][1],routePoints[counter + 1][0],routePoints[counter + 1][1]);
Main.bg_image.addChild(new_flight);
var checkTimer:Timer = new Timer(15);// 1 second
checkTimer.addEventListener(TimerEvent.TIMER, check_function);
checkTimer.start();
function check_function(event:TimerEvent):void
{
if (new_flight.finished = true)
{
checkTimer.stop();
}
}
}
}
}
}
Flight class
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.display.SimpleButton;
import flash.display.Stage;
import flash.events.TimerEvent;
import flash.utils.Timer;
import fl.controls.Button;
import flash.display.DisplayObject;
public class Flight extends MovieClip
{
public static var speed:uint = 1
public var finished:Boolean = false;
protected var absvector:Number;
protected var vector:Array;
protected var myTimer:Timer;
//protected var parentContainer:MovieClip;
protected var utgangspunkt_x;
protected var utgangspunkt_y;
protected var destinasjon_x;
protected var destinasjon_y;
protected var vector_x;
protected var vector_y;
public function Flight(utgangspunkt_x, utgangspunkt_y, destinasjon_x, destinasjon_y):void
{
addEventListener(Event.ADDED_TO_STAGE, init);
this.utgangspunkt_x = utgangspunkt_x;
this.utgangspunkt_y = utgangspunkt_y;
this.x = utgangspunkt_x;
this.y = utgangspunkt_y;
this.destinasjon_x = destinasjon_x + 10;
this.destinasjon_y = destinasjon_y + 10;
this.vector_x = Math.abs(this.destinasjon_x-this.utgangspunkt_x);
this.vector_y = Math.abs(this.destinasjon_y-this.utgangspunkt_y);
this.height = 20;
this.width = 20;
}
public function init(evt:Event):void
{
trace(this.parent)
if (utgangspunkt_x < destinasjon_x)
{
this.rotation = -(Math.atan((utgangspunkt_y-destinasjon_y)/(destinasjon_x-utgangspunkt_x)))/(Math.PI)*180;
}
else
{
this.rotation = 180-(Math.atan((utgangspunkt_y-destinasjon_y)/(destinasjon_x-utgangspunkt_x)))/(Math.PI)*180;
}
absvector = Math.sqrt(Math.pow((destinasjon_x - utgangspunkt_x),2) + Math.pow((utgangspunkt_y - destinasjon_y),2));
vector = [(destinasjon_x - utgangspunkt_x) / absvector,(utgangspunkt_y - destinasjon_y) / absvector];
stage.addEventListener(Event.ENTER_FRAME, movement)
}
private function movement(evt:Event):void
{
if (this.vector_x > this.vector_y)
{
if (destinasjon_x>utgangspunkt_x)
{
if (this.x < destinasjon_x)
{
this.x += speed*vector[0];
this.y -= speed*vector[1];
}
else
{
finished = true
Main.bg_image.removeChild(this)
}
}
else if (destinasjon_x<utgangspunkt_x)
{
if (this.x > destinasjon_x)
{
this.x += speed*vector[0];
this.y -= speed*vector[1];
}
else
{
finished = true
Main.bg_image.removeChild(this)
}
}
}
else
{
if (destinasjon_y>utgangspunkt_y)
{
if (this.y < destinasjon_y)
{
this.x += speed*vector[0];
this.y -= speed*vector[1];
}
else
{
finished = true
Main.bg_image.removeChild(this)
}
}
else if (destinasjon_y<utgangspunkt_y)
{
if (this.y > destinasjon_y)
{
this.x += speed*vector[0];
this.y -= speed*vector[1];
}
else
{
finished = true
Main.bg_image.removeChild(this)
}
}
}
}
}
}
I am confused what your asking and what your trying to do, but I will give it my best shot.
this.addchild(new_class2)
This line adds your object to the display list. Adding another object to the display is done the same way you added the first. Flash adds objects in the sequentially, so the objects you want in the back need to be declared and added first.
This is probably what you want:
var new_flight:Flight = new Flight();
this.addchild(new_flight);
Also you forgot your type declaration for Class2:
var new_class2:Class2 = new Class2();
Try replacing:
Main.bg_image.addChild(new_flight);
with
Main(this.parent).bg_image.addChild(new_flight);
... assuming the 'main' class you refer to is infact named 'Main' and it has a named instance called 'bg_image'
Please leave a comment if it works, I can explain in more detail what is actually happening here.
Why you are adding new_flight to bg_image?
Anyway, if you are adding new_flight to bg_image, then you have bg_image already declared as public static (which I do not recommend),
Try removing the flight in your Flight class it-self like so,
Main.bg_image.removeChild(this) // *
You can also use Event Dispatching instead of declaring bg_image as static.
If you want to remove flight then dispatch event from Flight class to Route class and there you again dispatch event to main class.
And, inside main class capture this event and access the MovieClip.

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/