Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    Flash




[Flash 8] Referencing Class Variables From OnEnterFrame Created Within Class



Hi,
It's been a while since my last post here, but I was hoping someone could help me with a problem I'm having. I want to reference and change a class variable from within an onEnterframe function defined within a class. I can actually do this right now, but I want to do it in a different way. Here's a code sample of what I am talking about:


Test.fla file:

Code:
var t:tester = new tester()

Working tester.as file:


Code:
class tester{
private var num:Number = 100;

function tester(){
var classObj:tester = this;
var mc:MovieClip = _root.createEmptyMovieClip("test",1);
mc.onEnterFrame = function(){
trace(classObj.num); //This traces 100 (CORRECT!!!)
}
}
}
This traces 100 to the output window, just like it should

Here is the way that I would like to do it, because I want to reuse my onEnterFrame Stuff:

Code:
class tester{
private var num:Number = 100;

function tester(){
var classObj:tester = this;
var mc:MovieClip = _root.createEmptyMovieClip("test",1);
mc.onEnterFrame = this.mcOnEnterFrame;
}

private function mcOnEnterFrame(){
trace(num) //this traces undefined (BAD!!!)
}
}

As you can see, the work around to reading the class variable in the onEnterFrame function is to create a reference to the class object, before defining that function, then using the reference you created to access the class variables.

I have tried various iterations to get the second example working, but have had no luck. Does anyone know a way to get the second method working, or am I stuck using the first method.



FlashKit > Flash Help > Flash ActionScript
Posted on: 01-03-2007, 06:40 PM


View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread

Referencing An Mc Created In One Class From Another Class
Hello everybuddy,

Cracking site, I normally don't post but have read and learned much from here thanks to all the posters!

I'm struggling with AS3 at the moment, forcing myself to take an OO approach and slowly getting there... However I'm now stuck...

My project is a dynamically generated web page, getting pics and data from xml files.

I have a button class that creates buttons based on an xml file, this is in its own class file(buttons.as) which is called from my document class.

The document class also creates a bunch of thumbnails using (screen.as), the thumbnails are placed in an MC called thumbs (which created by the document class).

What I need now is a way of linking my button class to the thumbs MC, so that when I click a button my thumbs MC is tweened using my dotween function.

when I run my project i get an errror from my buttons.as --> 1120: Access of undefined property thumbs.

I guess what i'm asking is how to reference an MC created in one class, from another seperate class. I thought that by setting it to public this would be possible but its not working...

Here is my code:




Code:
//Document.as
package {
import flash.display.MovieClip;
public class Document extends MovieClip {
public var thumbs = new MovieClip;
public var butArr = new Array;
public var screen1:screen;
public var thumbArr = new Array;
public function Document() {
//add buttons
for (var i:uint = 0; i < 10; i++) {
button[i] = new buttons(i);
addChild(button[i]);
}

//add thumb container
this.addChild(thumbs);
//addthumbs
for (var i:uint = 0; i < 10; i++) {
var thumbleft:uint=140+i*320;
thumbArr[i] = new screen(thumbleft,275,i,320,240,"thumb");
thumbs.addChild(thumbArr[i]);
}

screen1 = new screen(140,35,1,640,240,"home");
addChild(screen1);
}
}
}

Code:
//buttons.as
package {
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.events.Event;
import flash.display.MovieClip;
import flash.display.SimpleButton;
import flash.events.MouseEvent;
import flash.text.*;
import flash.filters.GlowFilter;

import fl.transitions.Tween;
import fl.transitions.TweenEvent;
import fl.transitions.easing.*;
public class buttons extends MovieClip {
public var num:uint=1;
public var myXML:XML;
public var thisText =thisText;
public var thisID:uint = thisID;
public function buttons(thisID) {
this.num=thisID;
getXML();
}
public function getXML() {
var urXML:URLRequest;
var ulXML:URLLoader;
urXML=new URLRequest("buttons.xml");
ulXML = new URLLoader(urXML);
ulXML.addEventListener(Event.COMPLETE, xmlLoaded);
ulXML.load(urXML);
}
public function xmlLoaded(event:Event) {

myXML = XML(event.target.data);

var xmlID=thisID-1;
thisText=myXML.butTitle[this.num];

makeButton(thisText);
}
public function makeButton(thisText) {
var myTextField:TextField=new TextField;

// Here we add the new textfield instance to the stage with addchild()
addChild(myTextField);

// Here we define some properties for our text field, starting with giving it some text to contain.
// A width, x and y coordinates.
myTextField.text=thisText;
myTextField.width=120;
//myTextField.height=50;

myTextField.multiline = true;
myTextField.wordWrap = true;
myTextField.x=15;
myTextField.y=this.num*50+50;

// Here are some great properties to define, first one is to make sure the text is not selectable, then adding a border.
myTextField.selectable=false;
//myTextField.border=true;

// This last property for our textfield is to make it autosize with the text, aligning to the left.
//myTextField.autoSize=TextFieldAutoSize.LEFT;

//This is the section for our text styling, first we create a TextFormat instance naming it myFormat
var myFormat:TextFormat=new TextFormat;

// Giving the format a hex decimal color code
myFormat.color=0xFFFFFF;

// Adding some bigger text size
myFormat.size=16;
myFormat.font="SkandiaDisplay";

// Last text style is to make it italic.
//myFormat.italic=true;

// Now the most important thing for the textformat, we need to add it to the myTextField with setTextFormat.
myTextField.setTextFormat(myFormat);
this.addEventListener(MouseEvent.CLICK,changePage);
this.addEventListener(MouseEvent.MOUSE_OVER,mouseover);
this.addEventListener(MouseEvent.MOUSE_OUT,mouseout);
}
function mouseover(evt:MouseEvent):void {
var glow:GlowFilter = new GlowFilter(0xFFFFFF,0.5,5,5);
this.filters=[glow];
}
function mouseout(evt:MouseEvent):void {
this.filters=[];
}
function changePage(evt:MouseEvent):void {
var newPage:Number=evt.currentTarget.num;
trace(newPage);


//not working
//1120: Access of undefined property thumbs.
thumbs.dotween("x",700,460);
}

public function dotween(command,startVal, endVal) {
var myTween:Tween = new Tween(this,command, None.easeOut, 0, 1, 1, true);
}
}
}
Any help would be greatly appreciated!!!

Thanks in advance!

Referencing Dynamically Created Instances Of Class
I've looked up several links but can't figure out why I can't access my dynamically created instances of class in as3... my code is...


Code:
var textPara:textPara1 = new textPara1();

content.addChild(textPara)
textPara.name = "bab"


var maxIndex:Number = content.numChildren - 1;
content.setChildIndex(content.bab as MovieClip, maxIndex);
content.bab.y = 50;
content.bab.x = 500
;


It adds an instance of the "textPara1" class (which I've put in the variable placeholder "textPara") to the display list of the "content" movieclip...

but despite assigning the new instance the name "bab", I can't seem to be able to access it (i.e. when i want to set the x and y position).

I thought it might have something to do with using array [i.e. square brackets] syntax, but already tried that to no avail.

My other thought was maybe I have to write in some sort of code that makes sure the instance has loaded to the stage/display list first and then write and function which references only after that has happened... but I could be talking nonsense!

Please please help. Any thoughts/links very very appreciated.
Cheers.

Referencing Timeline Variables From A Class
Yet another question..How do I referece, within a class function, variables residing in the timeline that is invoking the class? (Very beginner here!)

So far I've had to send the timeline variables from the timeline to the class's function as parameters, which works, but there's so many. And I know I can just make these variables reside in _root and reference them this way, but that is not smart.

Does it have to do with _parent at all? Tried using it but failed..

Thanks.

Movieclip In Library Referencing Variables In Main Document Class
I have a main.fla and a main document class (main.as)

Within the main.fla file I have a movieclip in the library with the linkage id of "myMC" and it is exported within the first frame.

Within that movieclip I have two images that I would like to attach ToolTips to, however, the key is to reference the text for the tooltips from XML as I have done previously through the main.as class.

I keep getting this error Access of undefined property toolTip and XML_mc

Here is the code within myMC in the library

ActionScript Code:

_button1.addEventListener(MouseEvent.ROLL_OVER, launchToolTip);
function launchToolTip(event:MouseEvent):void {
toolTip.addTip(XML_mc.preferences.imageAltText);
}




Note: In main.as I have toolTip and XML_mc both referenced as public variables within the package.

Any ideas?

[F8] Referencing A Static Class Inside Another Class's Instance
I've got a movie loading into a framework.

This framework has 1 instance of the class main called main.

Inside this class, another class is used, but it is used directly, not as an instance. E.g.:
code:
import com.StaticClass;
class main {
private function UseStaticClass():void {
StaticClass.init();
}
}


From my movie, I can reference the main instance as _root.main. Can I reference StaticClass at all if there's no explicit instance created or it's not assigned to a public variable?

I can't modify main to include getter/setter methods, that's why I ask.

Thanks.

Static Class Variable Referencing Class Instance
I was given the task of writing a class that would send serial requests for xml data, the idea being that the requests could be added while previous requests were still in progress, but the class would queue them and wait for the reply of one request to come back before sending the next.

The way I did this was to create a class instance for each request, and the request itself would be stored in an instance variable, waiting to be sent. A static variable called queue (accessible to all instances) was then given a reference to the instance, and when this reference got to the top of the queue, queue would call the sendRequest() method on that instance.

The reason why I am using one instance per request is so that the replies can be retrieved via the instance, so keeping each request entirely discreet.

Everything works very nicely, but the problem is my IT manager looked at the code and told me that you cannot put a reference to a class instance in a class static variable... and for this reason he has informed my line manager that he has serious reservations about the code, and recommends that it is not incorporated it into the project. However, the code works very well on my local machine and on the testsite, and no-one has experienced any problems with it.

Can someone reassure me here... I can see absolutely nothing wrong with having a class static array hold references to each of the instantiated class instances. And the proof is in the pudding.. it works. Can anyone else see a problem here?

Button Created Within Class Cannot Access Class Properties
Hi,
I'm using the following code within a class:
code:
_head_mc.attachMovie("headButton", "head_btn", this.getNextHighestDepth());

_head_mc.head_btn.onRelease = function () {
containingClip_mc._parent._parent.clickedHead(_per sonName);
}


The button gets attached (line 1). This works because I can see the mouse changing to a finger.

The onRelease function is declared and works. I know because if I put a trace in there, it works.

The function it calls (containingClip_mc._parent._parent.clickedHead also works, becuase I can see traces from within it.

But the _personName variable is passed as undefined.

I know that this variable has a value, because I can trace it outside the function, but it seems that this onRelease function is not able to see the variable. It's declared as private, but setting it to public doesn't fix anything.

I imagine there's something I don't understand about the scoping of variables. I've tried _parent references, but that doesn't appear to help either. Is there a better way to do this or a workaround?

Barrette

Added by edit
Okay, I've pretty much determined this is a scoping issue. From the onRelease function, I'm unable to access ANY of the functions within my class. I still would like advice on how to do so..

Barrette

Calling SetTimeout Within Custom Class And Cannot Access The Class' Variables
Hi All,

I'm creating an user interface with Flash 8, I'm new to Flash, my background is Java therefore I decided to use ActionScript to create a custom component that is reference within an external file.

My problem I believe is scope related. I have a status bar (label component), once I update the status bar I want to call the
"setTimeout" function to wait a couple of seconds before clearing my status bar. The "setTimeout" function is executing, but for some reason my status bar is not being cleared (accessed).

Below is a snippet of my code. Any help appreciated. Thanks.


/*
External File
*/
import mx.controls.Button;
import mx.controls.Label;

class MyApp
{
//private properties
private var mc_container:MovieClip;
private var btn:Button;
private var lbl_status:Label;
private var str:String = "do see me";

//constructor
public function MyApp(target:MovieClip)
{
trace("-- MyApp --");
mc_container = target.createEmptyMovieClip("mc_container", 100);
}
//public methods
public function init(width:Number, height: Number, xPos:Number, yPos:Number):Void
{
var my_app:MyApp = this;

btn = mc_container.createClassObject(Button, "btn", 1, {label:"click me"});
btn.setSize(100, 25);
btn.move(10, 10);
btn.clickHandler = function():Void
{
trace("btn clicked");
setTimeout(my_app.clearStatus, 2400);
//correct if I call directly
//my_app.clearStatus();
trace(str);
}

lbl_status = mc_container.createClassObject(Label, "lbl_status", 2, {text:"status bar message"});
lbl_status.setSize(200, 25);
lbl_status.move(0, 50);
}
public function clearStatus():Void
{
trace("calling clearStatus");
lbl_status.text = "";
}
}


/*
Called for Flash IDE
*/
var app:MyApp = new MyApp(this);
app.init(200, 200, 0, 0);

AS3 - Referencing Dynamically Created Variables.
Here I have a number of 'TweenField' instances created in a for loop. The problem is that each time the loop increments, the 'myTweenField' variable has the same name, so I don't know how they can be referenced individually from elsewhere in the script. How can I rewrite it so that each instance has a unique name, and how would I then reference it from outside the loop?


Code:
package
{
import flash.display.Sprite;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.events.Event;
import com.TweenField;

public class LoadItems extends Sprite{
private var yy:Number=1.5
private var externalXML:XML;
private var someXML:XMLList

public function LoadItems() {
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("xmlFile.xml");
loader.load(request);
loader.addEventListener(Event.COMPLETE, onComplete);
}

public function onComplete(event:Event):void {
var loader:URLLoader = URLLoader(event.target);
externalXML = new XML(loader.data);
someXML = new XMLList(externalXML.children().attribute("label"));
var bool:Boolean = true;
for(var xx:Number = 0; xx < someXML.length();xx++) {
if (bool) {
var myTweenField:TweenField = new TweenField(xx, someXML[xx], xx*30, 600, yy*30, 0, 20, .1, 200, yy*20, 1, 0, 1);
bool=false;
} else {
var myTweenField:TweenField = new TweenField(xx, someXML[xx], xx*30, -300, yy*30, 0, -20, .1, 200, yy*20, 1, 0, 1);
bool=true;
}
addChild(myTweenField);
yy++;
trace(bool);
}
}

private function saySomething(e:Event):void {
trace("changed");
}
}
}
Fingers

AS3 - How To Access Symbol(movie Clip) That Created Manually In Flash FROM Class ?
How to access symbol (movie clip) that created manually in flash FROM class ?
p.s : and that class is NOT a document class.

thanks.

btw I already try getChildByName(instanceName) to no avail.

Probelms Referencing A Class
Basically I have a class which extends EventDispatcher (DropDownMenu) and creates instances of another class(MenuButton) dynamically the first class is a menu the second the menu buttons for that menu.


It was all working fine until I make and instance of the dropdown menu which then makes instances of buttons and although the classpath is correct it will not make an instance of the button

this["menuMC"+i] = new MenuButton(dropMenu_mc, p_obj.eventName, 1, 1, p_obj.txt, "VP-100-256-639", "icon_mc", p_obj.iconType, 10, yPos);

unless I first declare this["menuMC"+0] = new MenuButton(); explictily in DropDownMenu constructor which defeats the dynamicnesss of it as I dont want to predeclare the vars because I dont know how many buttons there are going to be.

Has anyone experienced anything like this - its like the class has no scope in the parent class unless it is first declared in constructor - any help would be appreciated.

AS2 Class Object Referencing
Okay, so I have an object which is derived from mty DrawGrid3d class which works lovely. The draw3d class extends the movie clip class and has a constructor methos which believe it or not builds a 3d grid. Now I cant seem to be able to refer to the objects properties in any way. for example the code below traces out 'undefined'.
Any ideas?
Cheers


Code:
my_grid3d=new DrawGrid3D(_root,130,100,16,16,12,18,176,5.9,0xC5D7FE,0xFFFFFF)


trace("GRID IS:"+my_grid3d._x)

Referencing Stage From Class
Hello,
I am trying to make my first as3 class based game and so i was wondering if i could get some help. although the game wont have fancy graphics, i just would like to understand the way it works...currently, i am at a point where im getting :

1067: Implicit coercion of a value of type flash.display:Stage to an unrelated type Stage.
in my main file robot.fla, im using

var robo:robot=new robot(stage);
//var starenemy:enemy1=new enemy1(this.stage);
addChild(robo);

inside that robot.as
....
public class robot extends Sprite {
import flash.display.Stage;
private var _stage:Stage;
....
public function robot(stageRef:Stage):void {
_stage = stageRef;
...
}
amongst other things and i cant reference anything from the stage.

I think im going nuts trying to figure out how to correctly reference things to the stage. so can you take a look and guide me and tell me how i can proceed?
Attached is the zip file

Referencing Class Methods.
Hi,

I am have a class which I am instantiating in the first frame of a movie.
The class has a method called statecheck which I would like to access from a movie clip symbol.
I can reference the method easily from the first frame. what is the correct way of referencing it from the movieclip?

import Tpanel

var public panel:Tpanel = new Tpanel;

panel.statecheck(this); // works

the same line of code in the movieclip symbol does not.

also

_root.panel.statecheck(this); // does not work in as3

Cheers


Matt

Help Referencing A Visual MC From Another Class
I have a fla file with visual content onstage. This Fla also has a document class assigned called Home(extends Movieclip.) One of the visual assets onstage is a movieclip called mcHome that the Home class controls successfully.

I’ve got another class, Photos(extends Sprite) that I have imported(from another package) and it also successfully does what it’s suppose to. However, when I add code to Photos to refer to mcHome, the onstage movieclip, I get an


1120 access of undefined property mcHome error

What is necessary to make Photos understand what mcHome is?
Thanks

OnEnterFrame Within Class?
im writing a class-file, actually, my own tween-class.
and so i need to use the onOnterFrame-handle.
but how would i do that?

ok, i know i can create a mc on the _root or something like that, and use its onEnterFrame. but i was wonder if theres a better way..
creating/deleting mc's does that time, and putting one in the _root might cause depth-issues and such. and i dont like having to specify a mc to be used for onEnterFrame when calling the tween-class..

so is there a better way?

any answer apreciated.
thanks

OnEnterFrame In Class
helle all

i try to use onEnterFram

Code:
class i_clip extends MovieClip {
// ---- Init EventDispatcher
private static var initDispatcher = EventDispatcher.initialize (i_clip.prototype) ;

// --- private methodes
public var mcRef:MovieClip;
public var tEtat:TextField;
public var mc_Texte:MovieClip;
private var _intResize:Number;
private var _intLoad:Number;
private var propriete:Object = new Object();


// ---- public Properties
public var addEventListener:Function ;
public var removeEventListener:Function ;
public var dispatchEvent:Function ;


//---- Constructor
public function i_clip (ref:MovieClip,_idname:String,depth:Number)
{
mcRef = ref.createEmptyMovieClip(_idname,depth);
}
//---- Public Méthodes
(...)
/**
* Charge une image ou SWF
*/
public function _LoadImage (url:String):Void
{
mcRef.loadMovie(url);
onEnterFrame();
}

public function onEnterFrame(Void):Void
{
var chargement:Number = mcRef.getBytesLoaded();
var total:Number = mcRef.getBytesTotal();
var totalOctet:Number = Math.floor(total / 1024);
var loadOctect:Number = Math.floor(chargement / 1024);
var percent:Number = Math.floor (chargement /total *100) ;
/************************************************** ******/
if (isNaN (percent)!=0)
{
propriete.percent =percent;
propriete.totalOctet=totalOctet;
propriete.loadOctect=loadOctect
}
/************************************************** ********/
dispatchEvent ({type : "_onLoadProgress", target : this, propriete : propriete})
if (chargement == total)
{
clearInterval (_intLoad);
trace(chargement +""+ total);
dispatchEvent ({type : "_onLoadComplete", target : this, cible:mcRef})
}
trace("ok");
}

}
but when i called _loadImage my onEnterFrame was calling one time

for what ?

thanks

OnEnterFrame In A Class
Dear All,

I am studying “classes” in order to develop one that allows me to drive a car. After some tries a doubt came out: where to put the controls to drive the car? I mean, where to put the OnEnterFrame handler to refresh the position of the car? In the class or in the main fla?

I tried this and worked, but I am not sure if this is the best way:



Code:

//Main .fla
stop();
var Car:car= new car ();
var onEnterFrame:Function = Update;
function Update(){
Car.Run();
}
Is it possible to have the handler in the class?

Thanks in advance for your help

OnEnterFrame In Class
helle all

i try to use onEnterFram

Code:
class i_clip extends MovieClip {
// ---- Init EventDispatcher
private static var initDispatcher = EventDispatcher.initialize (i_clip.prototype) ;

// --- private methodes
public var mcRef:MovieClip;
public var tEtat:TextField;
public var mc_Texte:MovieClip;
private var _intResize:Number;
private var _intLoad:Number;
private var propriete:Object = new Object();


// ---- public Properties
public var addEventListener:Function ;
public var removeEventListener:Function ;
public var dispatchEvent:Function ;


//---- Constructor
public function i_clip (ref:MovieClip,_idname:String,depth:Number)
{
mcRef = ref.createEmptyMovieClip(_idname,depth);
}
//---- Public Méthodes
(...)
/**
* Charge une image ou SWF
*/
public function _LoadImage (url:String):Void
{
mcRef.loadMovie(url);
onEnterFrame();
}

public function onEnterFrame(Void):Void
{
var chargement:Number = mcRef.getBytesLoaded();
var total:Number = mcRef.getBytesTotal();
var totalOctet:Number = Math.floor(total / 1024);
var loadOctect:Number = Math.floor(chargement / 1024);
var percent:Number = Math.floor (chargement /total *100) ;
/************************************************** ******/
if (isNaN (percent)!=0)
{
propriete.percent =percent;
propriete.totalOctet=totalOctet;
propriete.loadOctect=loadOctect
}
/************************************************** ********/
dispatchEvent ({type : "_onLoadProgress", target : this, propriete : propriete})
if (chargement == total)
{
clearInterval (_intLoad);
trace(chargement +""+ total);
dispatchEvent ({type : "_onLoadComplete", target : this, cible:mcRef})
}
trace("ok");
}

}
but when i called _loadImage my onEnterFrame was calling one time

for what ?

thanks

Referencing A Subclip From Within A Class File
Say I have the following movieClip Structure

myMovieClip
myMovieClip.subMovieClip

I want to make a Class file for myMovieClip

I would like this Class to reference and adjust the subMovieClip._y using commands from the class file.

I keep getting errors when trying to do this. Is this a matter of syntax or is there no way to reference another movieClip from a class file?

Thanks

Referencing Class Variable From Inside Self
I have a class in an external .as called CustomGroup, and it will take in and process a number of objects which I want to name.

Code:
var myGroup:CustomGroup = new CustomGroup();
var otherGroup:CustomGroup = new CustomGroup();

myGroup.storeMarkers(someArray);
otherGroup.storeMarkers(otherArray);
I would like for each marker in someArray to be indexed with the instance name of the class object (i.e. "myGroup001", "myGroup002", "myGroup003") and ("otherGroup001", "otherGroup002", "otherGroup003")... but I cannot figure out how to target the class variable name from inside itself.

Help?

Dynamic Class Referencing Question
Quick question, I'm sure this is a stupid syntax problem...


Code:
fighter1_mc.aiPattern="SwoopDown";
fighterPattern = new classes.ai_routines[fighter1_mc.aiPattern](this, 20, 1, 5, 5);
fighterPattern = new classes.ai_routines.SwoopDown(this, 20, 1, 5, 5);
The second one creates the object as it is supposed to, but the first one does not. What is the correct way to dynamically reference the object?


Thanks in Advance

Problems Referencing Parent Class
I would like to have a child access the properties of the parent class and I've read _parent allows you to reference a parent object. However, I can't seem to get it to work. Here's an example.


Code:
class test{
public var name:String;
public var Test:test2;
function test(){
name = "testSring";
Test = new test2();
}
}

class test2{
function test2(){
var This:Object = this;
trace(This._parent.name);
}

}
//in the .fla
var Test:test = new test();
If I run it, I will get "undefined".

Referencing Stage.stageWidth From A Class
I created a custom class in a .as file. I then linked this custom class with a symbol from the library in my .fla file. However, I can't reference stage.stageWidth in my custom class file. I get a null object error.

I think this happens because the custom class file is associated with a symbol on the stage and not the stage itself. For example, if I set the fla file's Document Class to the name of my custom class I can reference stage.stageWidth in the custom class. But I don't do this because I am creating multiple instances of the symbol on the stage. In order to do that properly i found I have to set the class in the properties panel of the symbol to the underlying class which then defines how each symbol behaves.

Under this type of linkage, is there a way to reference the stage width from the class?

I've tried root.stage.stageWidth and parent.stage.stageWidth to no avail. I also made sure to import flash.display.* in my custom class.

Below is the code for my .fla file and my .as file. In the .as file you'll see the line "x = Math.random() * stage.stageWidth;". This is the line giving me problems. I could hard code it, as I do for the y variable on the next line, but I'd prefer not to in order to keep the code flexible.

I also attached the files in a zip.

Any help would be appreciated.


ActionScript Code:
//.fla code

var i:int;

for(i=0; i < 100; i++){
    var myBall:flaBall = new flaBall();
    addChild(myBall);
}


//.as code

package {
   
    import flash.display.*;
    import flash.events.Event;
   
   
    public class Ball extends MovieClip{
       
        var dx:Number;
        var dy:Number;
       
        public function Ball(){
            addEventListener(Event.ENTER_FRAME, onEnterFrame2);
            reset();
        }
       
        private function reset(){
            x = Math.random() * stage.stageWidth;
            y = Math.random() * 400;
            dx = Math.random() * 20 - 10;
            dy = Math.random() * 20 - 10;
        }
       
        private function onEnterFrame2(event:Event):void{
            move();
            checkBounds();
        }
       
        private function move(){
            x += dx;
            y += dy;
        }
       
        private function checkBounds(){
            if (x > 550 || x < 0){
                dx *= -1;
            }
            if (y > 400 || y < 0){
                dy *= -1;
            }
        }
    }
}

Referencing A Instance Inside A Class
Hi --

I am working on converting a movie clip to a Class so that I can more easily
reuse it in later projects.

I have pretty succesfully converted my AS code from my include file to a
Class file. However, I have two objects on the stage, topBG and botBG and
whenever I reference these items inside my code, such as botBG._y I get an
error at compile time saying "There is no property with the name 'botBG'"
How can I set it so these assets can be referred to inside my code?

The code worked fine when it was just a movie.. Also, this is ActionScript
2.0.

Thanks

Rich

Referencing Stage From External Class
I have an external class file that extends the MovieClip class and is linked to a movieClip on the main stage. I need it to be able to access properties of other movieclips on the main stage. How could I do this. Here is what my base movieclip class that I want to access the stage with looks like. Remember, it is linked to a movieclip on the stage, if that matters...
Obviously there is more code in the class, but I removed it for the sake of simplicity.







Attach Code

package{
import flash.display.MovieClip;
import flash.display.DisplayObject;
import Math;

public class Test extends MovieClip{

public function Test(){ //Constructor

}
}
}

Referencing Stage.stageWidth From A Class
I created a custom class in a .as file. I then linked this custom class with an symbol from the library in my .fla file. However, I can't reference stage.stageWidth in my custom class file. I get a null object error.

I think this happens because the custom class file is associated with a symbol on the stage and not the stage itself. For example, if I set the fla file's Document Class to the name of my custom class I can reference stage.stageWidth in the custom class. But I don't do this because I am creating multiple instances of the symbol on the stage. In order to do that properly i found I have to set the class in the properties panel of the symbol to the underlying class which then defines how each symbol behaves.

Under this type of linkage, is there a way to reference the stage width from the class?

I've tried root.stage.stageWidth and parent.stage.stageWidth to no avail. I also made sure to import flash.display.* in my custom class.

Any help would be appreciated.

Referencing An Object Inside A Class
and I'm trying to add an event listener and a function to the class, but I keep getting errors of undefined,
I tried just about everthing to be able to refference obj0 can anyone please help?

objGroup.obj0.addEventListener(MouseEvent.CLICK, onClick)
private function onClick (event:MouseEvent):void{

trace ("Click");

}

any help or advice will be greatly appreciated sincerely newwave
---------------this is my complete code - above code-------------feel free to use as you wish----------------------







Attach Code

package {
import flash.display.SimpleButton;
import flash.events.MouseEvent;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import org.papervision3d.core.proto.MaterialObject3D;
import org.papervision3d.lights.PointLight3D;
import org.papervision3d.materials.shadematerials.FlatShadeMaterial;
import org.papervision3d.objects.DisplayObject3D;
import org.papervision3d.objects.primitives.Sphere;
import org.papervision3d.view.BasicView;

public class pv3dMyRotation2 extends BasicView {

private static const ORBITAL_RADIUS:Number = 300;
private var angle:Number = 0;
private var obj0:Sphere;
private var obj1:Sphere;
private var obj2:Sphere;
private var obj3:Sphere;
private var obj4:Sphere;
private var obj5:Sphere;
private var obj6:Sphere;
private var obj7:Sphere;
private var objGroup:DisplayObject3D;

public function pv3dMyRotation2() {
super(0, 0, true, false);
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
init3D();
createScene();
startRendering();
}

private function init3D():void {

camera.x = -200;
camera.y = 0;
camera.z = 0;
}

private function createScene():void {

var light:PointLight3D = new PointLight3D(true);
light.x = 400;
light.y = 1000;
light.z = -400;

var M1:MaterialObject3D = new FlatShadeMaterial(light, 0xFF0000, 0xFFCC99);

for(var i=0; i<8; i++) {
this['obj'+i] = new Sphere(M1, 50, 10, 10);
this['obj'+i].x = ORBITAL_RADIUS * Math.cos(angle);
this['obj'+i].z = ORBITAL_RADIUS * Math.sin(angle);
angle += (360 / 8) * Math.PI / 180;
}

objGroup = new DisplayObject3D();
objGroup.addChild(obj0);
objGroup.addChild(obj1);
objGroup.addChild(obj2);
objGroup.addChild(obj3);
objGroup.addChild(obj4);
objGroup.addChild(obj5);
objGroup.addChild(obj6);
objGroup.addChild(obj7);

scene.addChild(objGroup);
scene.addChild(light);

}

override protected function onRenderTick(event:Event=null):void {
objGroup.yaw(1);
super.onRenderTick(event);
}
}
}

























Edited: 02/01/2009 at 08:58:22 PM by newwaveboats

Can't Get OnEnterFrame Running On MC In Class
Can anyone tell me why the onEnterFrame is not executing in the startRewind() method?


Code:
class mp3Player extends MovieClip
{
//properties

public var titlePlaying:String;
public var artistPlaying:String;
public var albumPlaying:String;
public var pathToPlaying:String;
public var songList:Array;
public var progressFraction:Number;
private var listXML_xml:XML;
private var songToPlay:Number;
private var thisSound:Sound;
private var _playing:Boolean;
private var currentPos:Number;
private var rewinder_mc:MovieClip;

//constructor
public function mp3Player(path:String)
{
// make a reference for method's use
var _this:Object = this;

// create new Sound to hold song playing
thisSound = new Sound();

// instantiate _playing
_playing = false;

// create MC to anchor rewind onEnterFrame events to
rewinder_mc = this.createEmptyMovieClip("rewinder_mc",this.getNextHighestDepth());


// set listXML_xml property to new XML() and call method to get
// XML list of songs, titles, etc and set to songList array property
listXML_xml = new XML();
listXML_xml.ignoreWhite = true;
listXML_xml.load(path);
listXML_xml.onLoad = function(success:Boolean)
{
if(success == true)
{
//trace("about to fire setSongListProp()");
_this.setSongListProp();
}
else
{
trace("no success on XML load");
}
}
}

//methods


// method to get XML list of songs, titles, etc and set to songList array property
private function setSongListProp():Boolean
{
//trace("setSongListProp() triggered");
var i:Number;
this.songList = new Array();
for (i=0; i<listXML_xml.firstChild.childNodes.length; i++)
{
var songTitle:String = listXML_xml.firstChild.childNodes[i].firstChild.firstChild.nodeValue;
var songArtist:String = listXML_xml.firstChild.childNodes[i].childNodes[1].firstChild.nodeValue;
var songAlbum:String = listXML_xml.firstChild.childNodes[i].childNodes[2].firstChild.nodeValue;
var songPath:String = listXML_xml.firstChild.childNodes[i].childNodes[3].firstChild.nodeValue;

var songArray:Array = new Array(songTitle, songArtist, songAlbum, songPath);
//trace("songArray for "+i+" is "+songArray[0]+", "+songArray[1]+", "+songArray[2]+", "+songArray[3]);
this.songList.push(songArray);
}
//trace("second title and artist is "+this.songList[1][0]+" "+this.songList[1][1]);
return true;
}

// method to load song into Sound made in constructor
public function loadSong(songCount:Number)
{
trace("sound loading");
thisSound.loadSound(this.songList[songCount][3], true);
thisSound.onLoad = function()
{
this.stop();
trace("song loaded");
}
}

// method to play the song
public function playSong()
{
trace("sound should start playing now");
thisSound.start();
this._playing = true;
}

// methods to rewind song
public function startRewind()
{
// make a reference for method's use
var _this:Object = this;
// and for sound's use
var _thisSound:Object = thisSound;
trace("rewind now");
trace("playing ? ="+this._playing);
this.currentPos = thisSound.position;
this.rewinder_mc.onEnterFrame = function()
{
trace("running onEnterFrame code");
_thisSound.start(_this.currentPos - 1);
_this.currentPos--;
}
}
public function stopRewind()
{
var _thisSound:Object = thisSound;
trace("stop rewind onEnterFrame now");
delete this.rewinder_mc.onEnterFrame;
if (this._playing != true)
{
thisSound.stop();
}
}



}



Much thanks!

[F8] Removing OnEnterFrame From AS 2 Class
Anyone know if there's a way? I lose a lot of efficiency when I onEnterFrames running on multiple clips. With the timeline I always do

PHP Code:




myClip.onEnterFrame = function()
{
if (condition to stop)
{
delete this.onEnterFrame;
}
}







But I don't have this feature with AS 2 classes...


PHP Code:




class Ball extends MovieClip{
function Ball()
{
}
function onEnterFrame()
{
// This'll keep running forever :-(. I don't want to use booleans to check if I should run the code in here since it'll still slow down...
}
}







Anyone know of any way to disable onEnterFrame from running on a particular class object?

Thanks,
-Danny

OnEnterFrame Only Running Once In Class?
Hi,

Can someone explain to me that if you define a function to be used as a onEnterFrame inside a constructor of a class it only runs once? and not every cycle?

So if you have

class whatever {


vars
vars

function whatever(root){
mc:MovieClip = root.attachMovie("mc", "mc1", 1);
mc.onEnterFrame = mainLoop;

}
function mainLoop(){
//only runs once, why??

}}

the only way I've been able to get my code to run properly inside a onEnterFrame is to stick it on the main timeline of the .fla, not inside a Class, any ideas?

Specify OnEnterFrame Function Within A Class
I saw a thread about onEnterFrameBeacon, but all I want to be able to do is specify onEnterFrame function within a class, very tidy no ?

But no It just wont work, despite my having seen many examples of this online?

I wonder if it is my Flash ide?- but doubtfull.

i want to do
-------------inside class---------------------
private function onEnterFrame(){
trace("it worked");
}

Delete OnEnterFrame In A Class?
i have a class that extends a movieClip...and in it, i defined an onEnterFrame.

Code:
class Me extends MovieClip {
//constructor

//onEnterFrame loop
function onEnterFrame() {
//do stuff
}

function die() {
delete this.onEnterFrame;
//or delete this.onEnterFrame();
}
}
the function die() would get called, but deleting the onEnterFrame doesn't work... obviously this is wrong?

thanks.

Delete OnEnterFrame In Class
Hi,
I am wondering how I can delete the onEnterFrame function in this class:


Code:
class MoveBall extends MovieClip {
private var _nSpeed:Number;
private var tText;
public function set speed (nSpeed) {
_nSpeed = nSpeed;
}
public function move ():Void {
this._x += _nSpeed;
updateAfterEvent ();
if (this._x >= 200) {
this._x = 200;
trace(this._name);
this.tText.text=this._name;
delete onEnterFrame;//not working
}
}
public function onEnterFrame () {
move ();
}
}
thanks,

Jerryj.

Onenterframe In Class Constructor
Hey all,
Im completely messed up about this maybe you guys can help. How on earth do you get onEnterFrame working properly within a as2.0 class. Im trying to simply set an MCs _y based on another MCs _y, onEnterframe. I have a feeling im caught into some sort of variable scope issue. Heres my code.....


PHP Code:



//buld main nav - button_holder
var button_holder:Object = _root.createEmptyMovieClip("button_holder", 6);
var button_holder_mc:Object = button_holder.attachMovie ("button_holder", "button_holder", 0);
button_holder_mc._x = 0;
                    
    button_holder.onEnterFrame = function(){
    trace(_root.div.div_bg._y);
    button_holder._y = _root.div.div_bg._y;
    } 




The trace in the onenterframe comes back undefined, so thats most likely the issue...but _root.div.div_bg._y is an absolute path Im ot understanding why it wouldnt work..if this is a varibble scope issue can someone explain what a scope issue is or point me to a good explanation of what they are and how to fix them?

Thanks.

OnEnterFrame Inside A Class
I don't have a problem as much as just a lack of understanding:

Question: Will I run into any problems using onEnterFrame inside a class? I know that onEnterFrame events can overwrite each other if they are written dynamically, but I'm not sure how this effects classes...

Also, onEnterFrame is an event of the movie clip class right? ...does that even matter...? What happens if I declare an onEnterFrame event inside a method inside my class: will it even work? will it effect the movie clip from which the class.method is being called?

Sigh... Hopefully you get the idea of what I'm having trouble grasping. Please explain any concepts you think I appear to be missing. I'm new to classes - thanks for your help.

OnEnterFrame = Function Within A Class
Hi all

I've created a class that has a method that receives an XML node. Currently, it uses a for loop to go throught the XML, like this:

for(var i=0; i<=(myXML.childNodes.length-1);i++){
// Internal Actions
}

Now this would work fine if the XML node received by this method has 10 nodes, 20 nodes, and so on. But I'll need this to handle anywhere from 1000 to 2000 nodes.

If I were writing this code on the timeline, I would use an onEnterFrame action to drill through a 2000 node XML, like this:

var i=0;
this.onEnterFrame = function(){
if(i<=(myXML.childNodes.length-1)){
// Internal Actions
i++;
}else{
this.onEnterFrame = null;
}
}

But I want to do something like this within a class. But every attempt to use the above onEnterFrame in a class hasn't worked. Nothing within the onEnterFrame ever gets called.

I'm still a bit fuzzy how to write classes so any help is appreciated.

Thanks
Chris

OnEnterFrame Vs Tween Class
Hi there,
I came across this code for a set of navigation _mcs:

Code:
// create an array of all nav buttons in group
var groupinfo:Array = [clip1, clip2, clip3];
// create a variable to track the currently selected button
var activebtn:MovieClip;
starty = 100;
targety = 180;
speed = 12;
// define handler function for rollovers
function grow() {
if (this._yscale < 180) {
this._yscale += (targety - starty)/speed;
}
}
// define handler function for rollouts
function shrink() {
if (this._yscale > 100) {
this._yscale -= (targety - starty)/speed;
}
}
// doRollOver: start the rollover action or process,
// unless the button is currently selected
function doRollOver() {
if (this != activebtn) {
this.onEnterFrame = grow;
}
}
// doRollOut: start the rollout action or process,
// unless the button is currently selected
function doRollOut() {
if (this != activebtn) {
this.onEnterFrame = shrink;
}
}
// doClick: 1) return previously selected button to normal, 2) show visual
// indication of selected button, 3) update activebtn
function doClick() {
activebtn.onEnterFrame = shrink; // return previously selected to normal

delete this.onEnterFrame; // stop activity on selected mc
this._yscale = 200; // change appearance of selected mc

activebtn = this; // update pointer to current selection
}
// assign functions to each event for each button in the group
function init() {
for (var mc in groupinfo) {
groupinfo[mc].onRollOver = doRollOver;
groupinfo[mc].onRollOut = doRollOut;
groupinfo[mc].onRelease = doClick;
}
}
init();
And decided to do the same but instead use only the Tween Class. My newbie brain generated this code:

Code:
import mx.transitions.Tween;
import mx.transitions.easing.*;

var activemc:MovieClip;
myall = function(mc){
mc.onRollOver = function(){
var upy = new Tween(mc,"_yscale",Strong.easeOut,mc._yscale,200,20,false);
}
mc.onRollOut = function(){
var downy = new Tween(mc,"_yscale",Strong.easeOut,mc._yscale,100,20,false);
}
mc.onRelease = function(){
if(this != activemc){
new Tween(activemc,"_yscale",Strong.easeOut,this._yscale,100,20,false);
activemc = this;
this._yscale = 200;
delete mc.onRollOut;
}
}
}
myall(green1);
myall(green2);
myall(green3);
myall(green4);
when I click each _mc one by one it works flawlessly but roll over them all at the same time and they all refuse to tween down to 100% scale. Please find attached fla.
Any pointers much apprerciated.
Geminian1

Tween Class With OnEnterFrame
I put a movieclip I created (located in the library) on the stage with AS, then dynamically drew a white box on top of it. The tween is meant to fade the the white box to 0, but..nothing! Anybody see some syntax errors I'm missing?

ActionScript Code:
stop();

import mx.transitions.Tween;
import mx.transitions.easing.*;

//White box (for use in transitions)
this.createEmptyMovieClip("transBox",2);
transBox.moveTo(0, 0);
transBox.beginFill(0xFFFFFF,100);
transBox.lineTo(1280, 0);
transBox.lineTo(1280, 800);
transBox.lineTo(0, 800);
transBox.lineTo(0, 0);
transBox.endFill;

this.attachMovie("gradient", "colorGrad", 1);

this.onEnterFrame = function() {
var transTween:Tween = new Tween(transBox, "_alpha", Strong.easeOut, 100, 0, 1, true);
transTween.onMotionFinished = function() {
delete this.onEnterFrame();
}
}

Referencing A Movie Clip From A Class .as File
Okay, so I'm making a game. I've made various class files for various elements on the screen and used linkage to make the movie clips on screen members of my custom classes (by right clicking on the movie clip in the library and selecting linkage, etc). But I'm having an issue...
I can't reference child movie clips. So say I have a movie clip called "sea", and within it I have one called "fish" (instance name, of course). I use linkage to make "sea" a member of my custom "SeaClass" class. However if I try to do something like this.fish.gotoAndStop(5); I get an error saying that there is no property "fish". I understand that it's looking for a "fish" function instead of the "fish" subclip, but is there any way to make it reference the subclip?
This is a big issue because I'm having to use a lot of onClipEvent(enterFrame) variable checks for my subclips and whatnot to make them execute something instead of being able to put the command straight in a function and its really bogging down code.
I hope this makes sense... thanks in advance for the help!

Referencing The Root Timeline Within Using _root In A Class
I have a class that I wrote and I need to reference the root timline but I can't use _root to do that because my movie will be loaded into another movie. Is there another way to reference root?... maybe a _global variable? If so, how would I set up that global variable on the root timline and then use it in the class?

Thanks.

Referencing A Parent Method From A SimpleButton Class
I'm new to AS3 (know AS2 fairly well), and am having trouble wrapping my head around OOP methods of doing things. I know it will keep things organized and more modular, so I'm trying to learn, but am having trouble...

Specifically, I've defined a method called showScreen within the document class (Main). I've also defined a NavButton class that's attached to a hand full of simple buttons objects. The only problem is that, when one of the buttons is clicked, I receive an error that the parent class's method (showScreen) isn't defined.

1061: Call to a possibly undefined method showScreen through a reference with static type flash.display:DisplayObjectContainer.

(It's worth noting that I'm still learning to read those fancy new errors, and that making things public / private / static have only confused me further as to their relevance to my problem.)


PHP Code:



// Main.as... abridged to save you time
package com.as3Adventures
{
    public class Main extends MovieClip
    {
        function Main()
        {
            // sets up the elements on the stage, etc
        }
        public function showScreen(which:String):void
        {
            // animates the old screen out and displays
            // another, based on the variable passed
            
            // this is the method I want to call
        }
    }
}




And


PHP Code:



// NavButton.as... also abridged
package com.as3Adventures
{
    public class NavButton extends SimpleButton
    {
        function NavButton()
        {
            // sets up the button...
            addEventListener (MouseEvent.CLICK, clickHandler);

        }
        function clickHandler (e:MouseEvent):void
        {
            // does a little magic with the button, animating, etc... then...

            trace(parent);  // returns "[object Main]"
            parent.showScreen(this.name);  // <------------ Causes headaches
        }
    }
}




I suspect that making NavButton extend MovieClip rather than SimpleButton would fix this (am I wrong? I have no idea), but doing so breaks the functionality for the button that's already been written. And besides, this seems like a fairly common thing to do - calling a method from a button.

What am I doing wrong? Any help would be much appreciated.

Referencing Buttons From Class That Extends Movieclip
I'm attaching actionscript classes to my movie clips by extending the MovieClip class and specifying the AS 2.0 class in the linkage properties in the library – with the intention of having basically no code in the FLA.

This works fine and I can respond to events and reference objects contained within that movie clip by declaring a variable with the same name as the object's instance name in the class.

PROBLEM is that the object has to be present on the first frame of the MC, or the class just doesn't know about its existence. I have a short animation on the timeline, and then the btnOK button appears for the first time a few frames later. Problem is that I can't setup any sort of event handler or listener, because when the class is initialised on the first frame it doesn't seem to know about the button.

So in the below code... if the btnOK is on the first frame of the timeline, it traces, otherwise btnOK is undefined.


Code:
class myMC extends MovieClip {

var btnOK:Button;

function myMC() {
btnOK.onPress = function() { trace("clicked") };
}
}
Yeah sure I could place the button on the first frame and show/hide it as needed but that wouldn't be ideal and would make me want to vomit.

By the way, I'm talking about normal everyday button symbols, not the Button component.

Any ideas?

Cheers.

Referencing A Parent Method From A SimpleButton Class
I'm new to AS3 (know AS2 fairly well), and am having trouble wrapping my head around OOP methods of doing things. I know it will keep things organized and more modular, so I'm trying to learn, but am having trouble...

I've defined a method called showScreen within the document class (Main). I've also defined a NavButton class that's attached to a hand full of simplebutton objects. The only problem is that, when one of the buttons is clicked, I receive an error that the document class's method (showScreen) isn't defined. I suspect I'm just not referencing it correctly.

1061: Call to a possibly undefined method showScreen through a reference with static type flash.display:DisplayObjectContainer.

(It's worth noting that I'm still learning to read those fancy new errors, and that making things public / private / static have only confused me further as to their relevance to my problem.)


ActionScript Code:
Main.as... abridged to save you time
package com.as3Adventures
{
    public class Main extends MovieClip
    {
        function Main()
        {
            // sets up the elements on the stage, etc
        }
        public function showScreen(which:String):void
        {
            // animates the old screen out and displays
            // another, based on the variable passed
           
            // this is the method I want to call
        }
    }
}


ActionScript Code:
// NavButton.as... also abridged
package com.as3Adventures
{
    public class NavButton extends SimpleButton
    {
        function NavButton()
        {
            // sets up the button...
            addEventListener (MouseEvent.CLICK, clickHandler);

        }
        function clickHandler (e:MouseEvent):void
        {
            // does a little magic with the button, animating, etc... then...

            trace(parent);  // returns "[object Main]"
            trace(parent.parent);  // returns "[object Stage]"
            parent.showScreen(this.name);  // <------------ Causes headaches
        }
    }
}

I suspect that making NavButton extend MovieClip rather than SimpleButton would fix this (am I wrong? I have no idea), but doing so breaks the functionality for the button that's already been written. And besides, this seems like a fairly common thing to do - calling a method from a button. I also suspect that using parent may be attempting to run a method for a DisplayObject rather than the Class itself, but I'm not sure.

What am I doing wrong? Any help would be much appreciated.

Referencing Main Document Class From A Loaded Swf
Hi,
I'm loading a game swf into what is essentially a shell swf, I'd like game.swf to call a function (myFunction) in the document class of shell.swf.

At the moment I am trying to use the stage within game.swf property as a reference for shell.swf (which extends from movieclip) and then calling stage.myFunction but because the property I want to call is a custom property, it throws an error at compile time saying that the method does not exist.

Any ideas? Is it possible to do this without including the definition for the shell document class in my game.swf? Is it possible to do this without storing a reference to the shell.swf document class - i.e. being able to create the reference from within the game.swf at any desired point.

Cheers
JMC
www.funsneaks.com

Referencing Other Object Classes In A Class Definition
Here's want I want to do.
I have a ball class and paddle class. I want to put a hitTestObject statement in the ball class that references the paddle class. I need the ball class to perform the same function whenever it hits an instance of the paddle class.
Can I achieve this affect with just these two classes, or do I need to write a third class to handle collisions between the two classes?

Why doesn't this work?
ball class:

ActionScript Code:
package
{
  import paddle
  import flash.display.MovieClip
  import flash.events.Event
  public class ball extends MovieClip
  {
    public var xmov:Number = 5
    public var ymov:Number = 5
    public function ball():void
    {
      stage.addEventListener(Event.ENTER_FRAME, enterframe)
    }
    public function enterframe(event:Event):void
    {
      if(this.hitTestObject(paddle))
      {
        ymov *= -1
      }
    }
  }
}

Referencing Text Field Within Custom Class
I have set up two classes, one is the DocumentClass and it imports a custom class i have made called XMLLoader. The problem is I want to change the value of a dynamic text field on the stage with the instance name xml_txt from within the XMLLoader class...


Code:
package classes
{
import flash.display.MovieClip;
import classes.XMLLoader;

public class DocumentClass extends MovieClip
{
public function DocumentClass():void
{
var xml:XMLLoader = new XMLLoader();
}
}
}

Code:
package classes
{
import flash.events.*;
import flash.net.URLLoader;
import flash.net.URLRequest;

public class XMLLoader
{
var req:URLRequest = new URLRequest("myXML.xml");
var loader:URLLoader = new URLLoader();

public function XMLLoader():void
{
loader.addEventListener(ProgressEvent.PROGRESS, loadProgress);
loader.addEventListener(Event.COMPLETE, loadComplete);
loader.load(req);
}

private function loadProgress(event:ProgressEvent):void
{
var percent:Number = ( 100 / event.bytesTotal ) * event.bytesLoaded;
trace(Math.round(percent));
}

private function loadComplete(event:Event):void
{
var newLoader:URLLoader = URLLoader(event.target);
trace(newLoader.data);
}
}
}

Packaging And Cyclic Class Referencing Problems
Anyone know of a good source that shows a good solution to these errors:?

"The class <classname> could not be loaded...",
"The class <classname> conflicts with the previously loaded class <classname>..."

I'm having a heck of a time trying to implement some design patterns, like Observer and MVC, inside packages...these patterns include some cyclic class referencing.

Thanks ahead of time,
Mike
Frustrated Flash Developer

Referencing A Class Intance At Root Level
I created a class to do different unit conversions and Its called

Convert.as

Now I have a main movie that is loading different SWF's into the stage depending on what section im in. Is there any way to create one instance of the class in the _root level and be able to access it from ALL the loaded SWF's? Ive experimented but I cannot get it to work. It seems like I have to instantiate the class in each FLA file. I don't like this because Ive got about 10 external SWF files that are using this class and if I change it I have to re publish all of those files. If I can somehow reference the class in the _root level then I would only have to publish it once. Please help...

And I have tried this...

var _root.myClass:Convert = new Convert();

but it wont work. Ive even tried this...
var myClass:Convert = new Convert();
_root.myClass2 = myClass

hoping that I could reference it but it wont work. So im at a loss...

I guess what im looking for is a Global Class that I can access ANYWHERE

Copyright © 2005-08 www.BigResource.com, All rights reserved