Using variable from another class as3 - actionscript-3

i separated one big file into multiple file to have it cleaned and i got a problem now.
I have my main.as, character.as, camera.as.
What i'm trying to do is access a variable from another class which i set later on that class. Ill show you what i mean.
From my main.as im loading each class and add them as child so it get displayed on screen.
public function buildGame()
{
var loadMap:Sprite = new nf_MapBuilder();
var xChar:Sprite = new nf_Character();
var xCam:Sprite = new nf_Camera();
var UserControl:nf_UserControl = new nf_UserControl();
addChild(loadMap);
addChild(xChar);
addChild(xCam);
addChild(UserControl);
}
Everything show on screen like it needed. Then it goes to my character.as:
package as3
{
import flash.display.Sprite;
import flash.events.Event;
public class nf_Character extends Sprite
{
public var character_pos:Array = new Array();
public var character_is_moving:Boolean = false;
public var character_x_dir:int = 0;
public var character_y_dir:int = 0;
public var character:hero = new hero();
public function nf_Character()
{
addEventListener(Event.ADDED_TO_STAGE,xCharLoad);
}
public function xCharLoad(e:Event)
{
character_pos = [2,2];
character.x=64*(character_pos[1]);
character.y=64*(character_pos[0]);
addChild(character);
}
}
}
There is the problem. I need to use those variable i set there in my character.as to use it in my camera.as:
package as3
{
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Rectangle;
import flash.display.StageScaleMode;
import as3.nf_Character;
public class nf_Camera extends Sprite
{
private var xChar:nf_Character = new nf_Character();
//Camera variables
var stageW2:Number;
var stageH2:Number;
var view:Rectangle;
public function nf_Camera()
{
addEventListener(Event.ADDED_TO_STAGE,xCamGo);
}
public function xCamGo(e:Event):void
{
trace("Camera pos - " + xChar.x + " " + xChar.character.y);
view = new Rectangle(0,0,stage.stageWidth,stage.stageHeight)
stageW2 = stage.stageWidth / 2 - 32;
stageH2 = stage.stageHeight / 2 - 32;
addEventListener(Event.ENTER_FRAME,CamView);
}
public function CamView(e:Event):void
{
view.x = xChar.character.x - stageW2;
view.y = xChar.character.y - stageH2;
scrollRect = view;
}
}
}
When it was all in one big file it was ok i just had to set the variable in the class and acessing it trough every function but now im kinda confused. Anyone see how i could do this?

In short, I think you should subscribe to an event from your character in your main class which is fired whenever the character moves. In the handler for that event you could call a method on the camera to set it's position according to the current position of the character.
main.as
private var xChar:Sprite = new nf_Character();
private var xCam:Sprite = new nf_Camera();
public function buildGame()
{
var loadMap:Sprite = new nf_MapBuilder();
var UserControl:nf_UserControl = new nf_UserControl();
// listen for when the character has moved
xChar.addEventListener(MoveEvent.MOVED, characterMovedHandler);
addChild(loadMap);
addChild(xChar);
addChild(xCam);
addChild(UserControl);
}
private function characterMovedHandler(event:MoveEvent):void
{
xCam.setPosition(xChar.x, xChar.y);
}
nf_Character.as
public class nf_Character extends Sprite
{
public var character_pos:Array = new Array();
public var character_is_moving:Boolean = false;
public var character_x_dir:int = 0;
public var character_y_dir:int = 0;
public var character:hero = new hero();
public function nf_Character()
{
addEventListener(Event.ADDED_TO_STAGE,xCharLoad);
}
public function xCharLoad(e:Event)
{
character_pos = [2,2];
character.x=64*(character_pos[1]);
character.y=64*(character_pos[0]);
addChild(character);
}
public function xCharMoved()
{
// Dispatch a custom event when the character moves
dispatchEvent(new MovedEvent(MovedEvent.MOVED));
}
}
nf_Camera.as
public class nf_Camera extends Sprite
{
private var xChar:nf_Character = new nf_Character();
//Camera variables
var stageW2:Number;
var stageH2:Number;
var view:Rectangle;
public function nf_Camera()
{
addEventListener(Event.ADDED_TO_STAGE,xCamGo);
}
public function xCamGo(e:Event):void
{
trace("Camera pos - " + xChar.x + " " + xChar.character.y);
view = new Rectangle(0,0,stage.stageWidth,stage.stageHeight)
stageW2 = stage.stageWidth / 2 - 32;
stageH2 = stage.stageHeight / 2 - 32;
// Probably only need one enterframe either in your character class or main
//addEventListener(Event.ENTER_FRAME,CamView);
}
public function setPosition(x:Number, y:Number):void
{
view.x = xChar.character.x - stageW2;
view.y = xChar.character.y - stageH2;
scrollRect = view;
}
}
Out of interest, how are you moving the character?

You can pass your character class instance to your camera class instance as an argument of the constructor. You will then have a reference to the character inside the camera class and you can access it's variables
// Inside buildGame() in main.
var xChar:nf_Character = new nf_Character();
var xCam:nf_Camera = new nf_Camera(xChar);
// Inside nf_Camera
public function nf_Camera(char:nf_Character) {
xChar = char;
}

Related

Error 1119 in Actionscript 3 (as3) Access of possibly undefined property text through a reference with static type money_txt

This is in the main class
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.display.Sprite;
import flash.events.Event;
public class main extends MovieClip {
public var scene = 0;
public var _money = 0;
public var gain = 1;
public var clicks = 0;
public function main() {
addEventListener(Event.ENTER_FRAME, loop);
mainbtn.addEventListener(MouseEvent.CLICK, handler);
playbtn.addEventListener(MouseEvent.CLICK, playHandler);
}
var mainbtn:button = new button();
var playbtn:playbutton = new playbutton();
var playtxt:playtext = new playtext();
var cash:money_txt = new money_txt();
var scene0:MovieClip = new MovieClip();
var scene1:MovieClip = new MovieClip();
public function loop(e:Event):void {
if(scene == 0) {
addChild(scene0)
scene0.addChild(playbtn);
playbtn.x = 300;
playbtn.y = 200;
scene0.addChild(playtxt);
playtxt.x = 300;
playtxt.y = 100;
} else {
scene0.removeChild(playbtn);
scene0.removeChild(playtxt);
}
if(scene == 1) {
addChild(scene1);
scene1.addChild(mainbtn);
mainbtn.x = 300;
mainbtn.y = 200;
scene1.addChild(cash);
cash.text = 'Money: ' + _money.toString();
} else {
scene1.removeChild(mainbtn);
}
}
public function playclickHandler(e:MovieClip) {
scene = 1;
}
public function handler(e:MouseEvent):void {
_money += gain;
clicks++;
trace('yep');
}
public function playHandler(e:MouseEvent):void {
scene = 1;
}
}
}
And This is where the error would be
C:\Users\Slime\Desktop\Art-ish\game\main.as, Line 47, Column 10 1119: Access of possibly undefined property text through a reference with static type money_txt.
Thanks for helping if you can!
these should be defined as public
public var mainbtn:button = new button();
public var playbtn:playbutton = new playbutton();
public var playtxt:playtext = new playtext();
public var cash:money_txt = new money_txt();
public var scene0:MovieClip = new MovieClip();
public var scene1:MovieClip = new MovieClip();
also it is hard to tell if money_txt, playtext, playbutton and button are classes or MovieClip instances. Convention dictates that Classes should start with a capital letter and instances with lower.
update
The issue is that if button and playbutton are buttons and playtext and money_txt are MovieClips, you should instantiate them as such.
for example if you have
public var mainbtn:button = new button();
but there is no class with name of button, mainbtn will be null. What you may need to do is
public var mainbtn:Button;
public var cash:MovieClip;
and as a part of your main or some other function, assign the instances
mainbtn = this['button'];
cash = this['money_txt'];
you can check if this worked by checking trace(cash);, which will return null if the assignment did not work.
I should stress again though, it is hard to to know what exactly is going wrong without knowing what your setup is. I'm assuming money_txt and the other classes you are defining are not actually classes with their own linkage IDs, but buttons and movieclips inside the MovieClip or stage you are putting this code in.

AS3 Scrolling Movieclip

I have a problem with my code whereby I have a spawned vertical movieclip where there are button instances in it which makes it look like a list.
The problem is that I am trying to recreate a iOS-style drag scrolling. When I hold and drag my movieclip, it works fine, scrolling up and down. But when I release my left mouse button, It registers a click on one of my buttons.
I tried to remove the event listeners on the buttons but the scrolling only works once, after I released my left mouse button, the whole scrolling does not work the second time.
Is it possible to have maybe like a mouse drag (up or down) ignoring the button click listeners however when the user want to click the button instead, the scrolling won't kick in?
My buttons' class
public function PlaceOneButtons()
{
for (var a=0; a<buttons.length; a++)
{
stationsone1[a].addEventListener(clicked,StationSelectOne);
stationsone2[a].addEventListener(clicked,StationSelectOne);
stationsone3[a].addEventListener(clicked,StationSelectOne);
stationsone4[a].addEventListener(clicked,StationSelectOne);
stationsone5[a].addEventListener(clicked,StationSelectOne);
}
}
My Main (spawner) class
package
{
import flash.display.MovieClip;
import flash.display.*;
import flash.text.*;
import flash.events.*;
import flash.ui.*;
import flash.utils.*;
import flash.media.*;
import IconSpawn;
import Scrolling;
public class MainClass extends MovieClip
{
private var iconspawn:IconSpawn = new IconSpawn();
private var touchay:int = new int;
private var touchPoint:int = new int;
private var touchPoint2:int = new int;
private var touchString:int = new int;
private var AYint:int = new int;
private var touchTimer:Timer = new Timer(150,1);
private var endTime:Timer = new Timer(1,1);
private var speed:int = new int;
public static var scrollDiff:int = new int;
public static var doubleDiff:int = new int;
public static var dragging:Boolean = new Boolean
//private var scrolling:Scrolling = new Scrolling();
//public static var Ystore:Point;
public function MainClass()
{
// constructor code
AYint = IconSpawn.A_Y.y;
}
public function startApp()
{
addChild(iconspawn);
iconspawn.MenuSpawn();
dragging = false;
}
public function directionsApp()
{
addChild(iconspawn);
iconspawn.KeyboardOne();
}
public function placeOneApp()
{
addChild(iconspawn);
iconspawn.PlaceOneSpawn();
Evtlistener();
}
private function Evtlistener()
{
addEventListener(Event.ENTER_FRAME,update);
addEventListener(MouseEvent.MOUSE_DOWN,spawnTouch);
addEventListener(MouseEvent.MOUSE_UP,endScroll);
}
public function directionsApp2()
{
addChild(iconspawn);
iconspawn.KeyboardTwo();
}
public function update(evt:Event)
{
//trace(touchTimer);
//trace(touchString);
touchPoint2 = mouseY;
scrollDiff = touchPoint2 - touchPoint;
doubleDiff = scrollDiff - scrollDiff;
trace(dragging);
if(dragging == true)
{
//iconspawn.PlaceOneButtons();
}
}
public function spawnTouch(evt:MouseEvent)
{
touchPoint = mouseY;
touchTimer.addEventListener(TimerEvent.TIMER,timerTouch);
endTime.addEventListener(TimerEvent.TIMER,endTimer);
touchTimer.start();
dragging = true;
touchay = IconSpawn.A_Y.y;
}
public function timerTouch(evt:TimerEvent):void
{
if(dragging == true)
{
addEventListener(Event.ENTER_FRAME,startScroll);
}
}
public function startScroll(evt:Event)
{
if(mouseY > 540 && mouseY < 1510)
{
IconSpawn.A_Y.y = touchay + (touchPoint2 - touchPoint);
}
}
public function endScroll(evt:MouseEvent)
{
removeEventListener(MouseEvent.MOUSE_DOWN,spawnTouch);
removeEventListener(Event.ENTER_FRAME,startScroll);
touchTimer.reset();
endTime.start();
}
private function endTimer(evt:TimerEvent):void
{
dragging = false;
Evtlistener();
}
}
}
Help will be appreciated! Have been stuck at this problem for days now.
UPDATE: Added new updated code
Hi guys, now my problem is that after I scroll my movieclip, the code will listen out for scrollDiff if its = 0.
When scrollDiff is 0, the buttons of the movieclip is clickable but if its more or less than that, the buttons are not clickable. Now my new problem is that after I release my left click, the code does not update the scrollDiff to 0, so user have to double click to select the button. Help!
package
{
import flash.display.MovieClip;
import flash.display.*;
import flash.text.*;
import flash.events.*;
import flash.ui.*;
import flash.utils.*;
import flash.media.*;
import IconSpawn;
import Scrolling;
public class MainClass extends MovieClip
{
private var iconspawn:IconSpawn = new IconSpawn();
private var touchPoint:int = new int;
private var touchPoint2:int = new int;
private var AYint:int = new int;
private var touchTimer:Timer = new Timer(150,1);
private var endTimer:Timer = new Timer(150,1);
private var IconSpwnY:int = new int;
private var touchbool:Boolean = new Boolean
public static var scrollDiff:int = new int;
//private var scrolling:Scrolling = new Scrolling();
//public static var Ystore:Point;
public function MainClass()
{
// constructor code
}
public function startApp()
{
addChild(iconspawn);
iconspawn.MenuSpawn();
}
public function directionsApp()
{
addChild(iconspawn);
iconspawn.KeyboardOne();
}
public function placeOneApp()
{
AYint = IconSpawn.A_Y.y;
addChild(iconspawn);
iconspawn.PlaceOneSpawn();
addEventListener(Event.ENTER_FRAME,update);
addEventListener(MouseEvent.MOUSE_DOWN,spawnTouch);
addEventListener(MouseEvent.MOUSE_UP,endScroll);
touchbool = false;
//IconSpawn.container.mouseChildren = true;
}
public function directionsApp2()
{
addChild(iconspawn);
iconspawn.KeyboardTwo();
}
public function update(evt:Event)
{
touchPoint2 = mouseY;
scrollDiff = touchPoint2 - touchPoint;
trace(scrollDiff);
}
public function spawnTouch(evt:MouseEvent)
{
touchPoint = mouseY;
touchTimer.addEventListener(TimerEvent.TIMER,timerTouch);
touchTimer.start();
IconSpwnY = IconSpawn.A_Y.y;
if(scrollDiff == 0)
{
IconSpawn.container.mouseChildren = true; //Important <-
}
else
{
IconSpawn.container.mouseChildren = false; //Important <-
}
}
public function timerTouch(evt:TimerEvent):void
{
addEventListener(Event.ENTER_FRAME,startScroll);
touchbool = true
}
public function startScroll(evt:Event)
{
if(mouseY > 0 && mouseY < 1510)
{
IconSpawn.A_Y.y = IconSpwnY + (touchPoint2 - touchPoint);
}
}
public function endScroll(evt:MouseEvent)
{
removeEventListener(MouseEvent.MOUSE_DOWN,spawnTouch);
removeEventListener(Event.ENTER_FRAME,startScroll);
endTimer.addEventListener(TimerEvent.TIMER,endTiming);
endTimer.start();
trace("CALLL")
scrollDiff = touchPoint2 - touchPoint;
//touchTimer.reset();
}
private function endTiming(evt:TimerEvent)
{
IconSpawn.container.mouseChildren = true;
addEventListener(MouseEvent.MOUSE_DOWN,spawnTouch);
//addEventListener(Event.ENTER_FRAME,startScroll);
scrollDiff = 0;
}
}
}
While you're moving set <container_mc>.mouseChildren = false. When the container clip stops moving, set the mouseChildren property to 'true'.
Adding to Craig's answer (which I definitely recommend implementing, to make life easier!), here is the list of the event listeners you should have hooked up for this to work as planned. This is theory, so you may have to play around with it a bit.
container.addEventListener(MouseEvent.MOUSE_DOWN, response);: You'll want to raise some sort of flag that the mouse is down, and wait for the next mouse event, which determines the action.
container.addEventListener(MouseEvent.MOUSE_MOVE, response);: If the mouse is down, disable child clicking (Craig's answer) and initiate dragging. You'll also want to raise a dragging flag.
container.addEventListener(MouseEvent.MOUSE_UP, response);: If the dragging flag is raised, stop drag and enable child clicking. If it isn't raised, do nothing, so the item can take over from there.
item.addEventListener(MouseEvent.MOUSE_UP, itemResponse);: Your click action.
Theoretically, this should work fine with your nested MovieClips, as long as you use MouseEvent.MOUSE_UP as the listener on them (as shown above). Using MouseEvent.MOUSE_DOWN or MouseEvent.CLICK may mess your timing up. However, I'd experiment a bit to find the right combination, as I could be wrong on that last point.

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.0 I'm trying to figure out how to access properties of event target

I'm trying to figure out how to reference the class of a target. Here is some of the code:
xmlDoc = new XML(xmlLoader.data);
//trace(xmlDoc.Video[1].Desc);
for (var i:int = 0; i < xmlDoc.Video.length(); i++)
{
xmlObj = new FilmVideo(xmlDoc.Video[i].Name, xmlDoc.Video[i].title, xmlDoc.Video[i].Thumb, xmlDoc.Video[i].URL, xmlDoc.Video[i].APILoader);
XMLItem[i] = xmlObj;
//trace(XMLItem);
MovieClip(root).main_mc.thumb_mc.addChild(XMLItem[i]);
if (i <= 0) {
XMLItem[i].x = 20;
XMLItem[i].y = 0;
} else if (i > 0){
XMLItem[i].x = XMLItem[i-1].x + XMLItem[i-1].width + 120;
XMLItem[i].y = 0;
}
XMLItem[i].addEventListener(MouseEvent.CLICK, makeThumbClick);
XMLItem[i].addEventListener(MouseEvent.MOUSE_OVER, makeThumbRollOver);
XMLItem[i].addEventListener(MouseEvent.ROLL_OUT, makeThumbRollOut);
}
}
function makeThumbClick(e:MouseEvent)
{
//var myFilmVideo:FilmVideo = FilmVideo(e.target);
MovieClip(root).main_mc.play();
trace(FilmVideo(e.target));
/MovieClip(root).main_mc.theater_mc.videoLoader(FilmVideo(e.target)._APILoad, FilmVideo(e.target)._videoURL);
}
The XMLItem is an array that's storing a class object I custom made (the class name is FilmVideo based off movieclip). The _thumbToMC is a method within my custom class that returns a movieclip. The class has info stored within its properties I would like to pass through a function called in the makeThumbClick function. However, I have no idea how. e.target reference the _thumbToMC movieclip rather than the class. I do I reference the class? Thank you in advance :)
Here is the class:
package filmvideo
{
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.net.URLRequest;
public class FilmVideo extends MovieClip
{
public var _nameXML:String = "";
public var _title:String = "";
public var _thumbURL:URLRequest;
public var _videoURL:URLRequest;
public var _APILoad:String = "";
public var loader:Loader = new Loader();
public function FilmVideo(name:String, title:String, thumbURL:String, videoURL:String, APILoad:String)
{
_nameXML = name;
_title = title;
_thumbURL = new URLRequest(thumbURL);
_videoURL = new URLRequest(videoURL);
_APILoad = APILoad;
//trace(_name);
//trace(_title);
//trace(thumbURL);
//trace(videoURL);
//trace(_APILoad);
this.addChild(loader);
loader.load(_thumbURL);
}
}
}
You could simplify your class to:
package filmvideo
{
import flash.display.Loader;
import flash.display.MovieClip;
import flash.net.URLRequest;
public class FilmVideo extends MovieClip
{
public var _nameXML:String = "";
public var _title:String = "";
public var _thumbURL:URLRequest;
public var _videoURL:URLRequest;
public var _APILoad:String = "";
public var loader:Loader = new Loader();
public function FilmVideo(name:String, title:String, thumbURL:String, videoURL:String, APILoad:String)
{
_nameXML = name;
_title = title;
_thumbURL = new URLRequest(thumbURL);
_videoURL = new URLRequest(videoURL);
_APILoad = APILoad;
//trace(_name);
//trace(_title);
//trace(thumbURL);
//trace(videoURL);
//trace(_APILoad);
this.addChild(loader);
loader.load(_thumbURL);
}
}
}
Then you can use FilmVideo as a MovieClip (since it extends the MovieClip class).
And use 'currentTarget' instead of 'target', because it always points to the listened object, while 'target' points to the object which fired the event. more info here
xmlDoc = new XML(xmlLoader.data);
//trace(xmlDoc.Video[1].Desc);
for (var i:int = 0; i < xmlDoc.Video.length(); i++)
{
xmlObj = new FilmVideo(xmlDoc.Video[i].Name, xmlDoc.Video[i].title, xmlDoc.Video[i].Thumb, xmlDoc.Video[i].URL, xmlDoc.Video[i].APILoader);
XMLItem[i] = xmlObj;
//trace(XMLItem);
Object(root).main_mc.thumb_mc.addChild(XMLItem[i]);
if (i <= 0) {
XMLItem[i].x = 20;
XMLItem[i].y = 0;
} else if (i > 0){
XMLItem[i].x = XMLItem[i-1].x + XMLItem[i-1].width + 120;
trace(XMLItem[i].width);
XMLItem[i].y = 0;
}
XMLItem[i].addEventListener(MouseEvent.CLICK, makeThumbClick);
XMLItem[i].addEventListener(MouseEvent.MOUSE_OVER, makeThumbRollOver);
XMLItem[i].addEventListener(MouseEvent.ROLL_OUT, makeThumbRollOut);
}
function makeThumbClick(e:MouseEvent)
{
//var myFilmVideo:FilmVideo = FilmVideo(e.target);
MovieClip(root).main_mc.play();
trace(myFilmVideo._APILoad);
MovieClip(root).main_mc.theater_mc.videoLoader(FilmVideo(e.currentTarget)._APILoad, FilmVideo(e.currentTarget)._videoURL);
}
If you don't want to do this way
Add a reference (inside the class) to the _thumbToMC back to it's FilmVideo object.
_thumbMC._filmVideo = this;
Then:
function makeThumbClick(e:MouseEvent)
{
//var myFilmVideo:FilmVideo = FilmVideo(e.target);
MovieClip(root).main_mc.play();
MovieClip(root).main_mc.theater_mc.videoLoader(MovieClip(e.currentTarget)._filmVideo._APILoad, MovieClip(e.currentTarget)._filmVideo._videoURL);
}
I'm not 100% sure I understand the question, but assuming you want to retrieve the properties of the FilmVideo instance (which it appears the user is clicking on) then maybe this is what you are looking for;
function makeThumbClick(e:MouseEvent){
var myFilmVideo:FilmVideo = FilmVideo(e.target);
// access properties of _thumbToMC
myFilmVideo.randomproperty = 123;
}

Use MouseEvent for getting Object`s public variables

I have a simple problem which is not easy at the moment. this is a text field class which add a text field to a movieclip (passed from root class) and also save(buffer) some data (like xml file name) in it`s public variables:
package src {
import flash.display.Shape;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
public class menuitem00 extends Shape {
public var activateFlag:Boolean = false;
public var name00:String = "";
public var xml00:String = "";
public var txt00:TextField = new TextField();
private var OM:MovieClip;
private var id00:Number = 0;
public function menuitem00(n:int ,OE:MovieClip ,xmlf:String):void {
trace (" Text Field Object with buffer ");
OM = OE; id00 = n; xml00 = xmlf;
}
public function init():void{
// textfield
txt00.selectable = false;
txt00.autoSize = TextFieldAutoSize.LEFT;
txt00.defaultTextFormat = new TextFormat("Impact", 36,0x66AAFF);
txt00.text = name00;
txt00.border = true;
txt00.borderColor = 0x00FF00;
txt00.sharpness = 100;
txt00.x = 0;
txt00.y = (id00 * txt00.height) + 1;
txt00.z = 0;
OM.addChild(txt00);
}
}
}
.. now I use a for loop to add instance of that class to a movie clip on stage:
for (var i:int = 0; i<Bunker[0]["trans0size"]; i++) {
menuData[i] = new menuitem00(i, menu_mc, Bunker[0]["transfile0" + i]);// pass i , a movieclip named menu_mc and an xml file name
menuData[i].name00 = Bunker[0]["transtitle0" + i]; // pass text
menuData[i].activateFlag = true; // set actveFlag to true
menuData[i].init(); // run init() inside the instance. it adds textfield to the menu_mc and also set name00 as Text for the textField
}
also I add mouse event for clicking on the stage,
stage.addEventListener(MouseEvent.CLICK, clk, false, 0, true);
public function clk(evt:MouseEvent):void{ //// mouse
trace (" Name: " + evt.target.text);
//trace (evt.target.xml00);
}
HERE IS MY PROBLEM --> I want to get "xml00" var from that instance on the stage by mouse click but, trace (evt.target.xml00); is not working .. also trace (evt.target.name00); is not working. I can get everything like .alpha or .text from txt00 but not other variables in my object. Any idea ?
don't add the click-listener to the STAGE but to you object.
menuData[i].addEventListener(MouseEvent.CLICK, clk, ...);
and add the following line to your menuitem00 class:
this.mouseChildren = false;
so you can be sure that the evt.target is an object of this class and not a child (like the textfield or something else).
edit
if you want to keep the stage-listener, try this:
stage.addEventListener(MouseEvent.CLICK, clk, ...);
private function clk (evt:MouseEvent):void
{
if (evt.currentTarget is menuitem00)
{
var item:menuitem00 = evt.currentTarget as menuitem00;
trace(item.xml00); // or any other public variable
}
}
but still add the mouseChildren = false; to your class.
edit2
make the menuitem00 class a sprite (and rename it pls):
public class MenuItem extends Sprite {
private var _activateFlag:Boolean;
private var _xml:String;
private var _txt:TextField;
private var _id:Number;
public function MenuItem (n:int, xmlf:String) {
trace (" Text Field Object with buffer ");
_id = n;
_xml = xmlf;
_activeFlag = true;
this.mouseChildren = false;
// create txt
_txt = new TextField();
// do the formating here ...
this.addChild(_txt);
}
public function getXml():String {
return _xml;
}
}
in the for loop you would do sth like this:
for (var i:int = 0; i<Bunker[0]["trans0size"]; i++) {
var item:MenuItem = new MenuItem(i, Bunker[0]["transfile0" + i]);
item.addEventListener(MouseEvent.CLICK, clk, false, 0, true);
menu_mc.addChild(item);
menuData[i] = item;
}
private function clk (evt:MouseEvent):void {
var item:MenuItem = evt.target as MenuItem;
if (item != null) {
trace(item.getXml()); // use a getter and don't access the variable directly
}
}
and pls re-read your actionscript (or programming) books, you're doing some really bad things i your code that you shouldn't.