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




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 Codepackage { 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



Adobe > ActionScript 3
Posted on: 02/01/2009 05:18:26 PM


View Complete Forum Thread with Replies

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

[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.

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?

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

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 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
      }
    }
  }
}

[CS3] Referencing A Movieclip Inside A Movieclip From A Class File
Hello All,

I'm trying to access a movieclip inside another movie clip from a class file that is not attached to either movieclip. For instance, I'm checking hitTests for the avatar the player uses on the game, there are two enemy movieclips. Inside each enemy movieclip is another movie clip that serves as a bounding box (specifically around the mouth of the enemy so it can eat the player). Here is what I have so far that isnt working:


Code:
if (_root['otter']['obbox'].hitTest(this) && touch == false) {
trace("Otter touched Urchin");
gotoAndPlay("hit");
_root['otter'].gotoAndPlay("eat");
touch = true;
}
The class file is for the avatar. On the stage is the otter mc and inside the otter mc is another mc called obbox which is what I'm trying to hitTest against. Needless to say, it doesn't hitTest or trace or play the animation. Is there a way to reference a nested mc? Thanks in advance.

Terror.

Why Won't My XML Object Work Inside Of A Class
I am writing a class to handle an XML document. The class definition is:

---------------------------------------
/**
* TemplateParser class
* author: Daniel Farrow
* -------------------------------------------------------------------------
*
* -------------------------------------------------------------------------
*/


class TemplateParser {

// private properties:
private var docXML:XML;
private var fileName:String;
private var parsedContent:String = "nothing";
private var xmlLoaded:Boolean = false;

// ================================================== ======================
// Constructor for TemplateParser
// ================================================== ======================
// Parameters:
// p_fileXML:String -> name of the XML file

public function TemplateParser(p_fileXML:String){

fileName = p_fileXML;
//var docXML = new XML();
docXML.onLoad = myOnLoad;
docXML.load(fileName);

}


// Public Methods
public function getContent():String {
return parsedContent;
}

// Private Methods
private function myOnLoad(status):Void {
trace("status = " + status);
if (status == true) {
publishContent(docXML.firstChild);
}
}

// ================================================== ======================
// Publish function
// ================================================== ======================
private function publishContent(HeadlineXMLNode:XMLNode):Void {
trace("publishContent() function called");

if (HeadlineXMLNode.nodeName.toUpperCase() == "BROADCAST") {
var myContent = "";
var story:XMLNode = HeadlineXMLNode.firstChild;
while (story != null) {
if (story.nodeName.toUpperCase() == "STORY") {
var lead:String = "";
var body:String = "";
var storyURL:String = "";
var element:XMLNode = story.firstChild;
while (element != null) {
if (element.nodeName.toUpperCase() == "LEAD") {
lead = element.firstChild.nodeValue;
}
if (element.nodeName.toUpperCase() == "BODY") {
body = element.firstChild.nodeValue;
}
if (element.nodeName.toUpperCase() == "URL") {
storyURL = element.firstChild.nodeValue;
}
element = element.nextSibling;
}
myContent += "<font size='+2' color='#3366cc'><a href='"+storyURL+"'>"+lead+"</a></font><br>"+body+"<br><br>";
trace("myContent = " + myContent);
}
story = story.nextSibling;
}
parsedContent = myContent;
}
}


}

----------------------------------------

The problem is, when the var docXML is declared as a property during object initialization, then the "onLoad" event will not get called. If I create the docXML object in the Constructor function of theclass, then the onLoad event works but I can't access the docXML object in other places in order to parse it. What am I doing wrong?

New Graphic Object From Inside A Class
Hi, I am newbie 3.0 :-) and this is my first show stopper:

The main Class (just the default created in Flex) creates a new Sprite. Then I call a Class that displays a text. The text has an event listener. It calls a function to create another Text, but it doesn't work. I think it is because I cant find the right scope for the new thing or because the Class approach is totally wrong.

Reading about the strict scope of AS3, if I can't reach stage or root from inside a class to elaborate a path, how can I create anything from inside a Class???? Shouldn't it be an easy thing?

If only I could pass the "container" reference as a parameter in the MouseEvent when calling the function…

Any help will be appreciated.

Regards:
Jeremy T.


ActionScript Code:
public class MyTest extends Sprite
    {
        public function MyTest ()
        {
            var container:Sprite=new Sprite;
            addChild (container);
            var $home:Page_home=new Page_home(container);         
        }
    }


ActionScript Code:
public class Page_home 
    {
        public function Page_home (container:Sprite)
        {
            var myText:TextField=new TextField;
            var $text:String = "The first";
           
            myText.text=$text;
            myText.addEventListener(MouseEvent.MOUSE_DOWN, clickOnText);
            container.addChild(myText);
        }
       
        private function clickOnText(evt:MouseEvent):void
        {
            var myText2:TextField=new TextField;
            var $text2:String = "The second";
           
            myText2.text=$text2;
            myText2.x=300;
           
            /* HERE IS THE SCOPE PROBLEM. I TRIED LINES LIKE THEESE WITH NO LUCK: */

            // addChild(myText2);  // no object to be attached
            // container.addChild(myText2);  // from inside here I can't find the object
            // stage.container.addChild(myText2);  // just fooling trial and error…
            // ...
        }
    }

Using A Sound Object Inside A Class
i'm attempting to use a class to store a sound object. when i call the init function of the class i want the sound object to load a file and set the sound_loaded property of the class to true. i can't seem to access the sound_loaded property of the class inside the onLoad event of the sound object. i've tried this.sound_loaded and this._parent.sound_loaded but neither works. any help would be greatly appreciated.

i'm using flash 8 pro


Code:


BeatBar.prototype.init = function (new_id, new_sound_location, new_num_beats) {
this.current_beat = 0;
this.is_cut = false;
this.is_muted = false;
this.id = new_id;
this.sound_loaded = false;
this.sound_location = new_sound_location;
this.sound = new Sound ();

// notify beatbar when sound has loaded
this.sound.onLoad = function (success:Boolean) {
if (success) {
trace (this.sound_loaded);
this.sound_loaded = true;
// also tried this._parent.sound_loaded = true;
} else {
// could not load requested sound
}
};

this.sound.loadSound (this.sound_location, false);
};



i know that the sound succeeds in loaded because the trace output appears. but for some reason the sound_loaded always appears as undefined even though i define it as false at the beginning of the init function.

--jeremy

XML Object Inside A Movie Clip Class
How do you instantiate the XML object ie:

myXMLObject = new XMLObject();

inside of a movie clip component??

Any help would be great!!

Sound Object Inside Class Onload...plz Help
i'm attempting to use a class to store a sound object. when i call the init function of the class i want the sound object to load a file and set the sound_loaded property of the class to true. i can't seem to access the sound_loaded property of the class inside the onLoad event of the sound object. i've tried this.sound_loaded and this._parent.sound_loaded but neither works. any help would be greatly appreciated.

i'm using flash 8 pro


Code:
BeatBar.prototype.init = function (new_id, new_sound_location, new_num_beats) {
this.current_beat = 0;
this.is_cut = false;
this.is_muted = false;
this.id = new_id;
this.sound_loaded = false;
this.sound_location = new_sound_location;
this.sound = new Sound ();

// notify beatbar when sound has loaded
this.sound.onLoad = function (success:Boolean) {
if (success) {
trace (this.sound_loaded);
this.sound_loaded = true;
// also tried this._parent.sound_loaded = true;
} else {
// could not load requested sound
}
};

this.sound.loadSound (this.sound_location, false);
};


i know that the sound succeeds in loaded because the trace output appears. but for some reason the sound_loaded always appears as undefined even though i define it as false at the beginning of the init function.

Dynamically Assigning Code To An Object Inside A Class. Which This Is This?
EDIT: Sorry, this is AS2, Flash8

Okay, I have a class named ship that I want to use to create some temporary movieclips and give them some onRelease code. I would like to pass to the movieclip onRelease code, the class object that created the code... but I am not sure if 'this' will be evaluated to be the movieclip that the onRelease code is assigned to, or the class object that assigned that code...

Does this make ANY sense? How about some pseudo code...

PHP Code:



class Ship extends MovieClip {
private var maxhandsize = 3
private var cardsinhand:String = ""  //comma deliminated listing of cards belonging to this player.

public function discard(){
   var inhandarray = cardsinhand.split(",");
   if (maxhandsize > inhandarray.length) {
      for (i in inhandarray) {
         this["tempcard" + i] = attachMovie(a card from the library)
         this["tempcard" + i].onRelease = function([b]this[/b]){
            //code for discarding cards that are clicked on.
            //code for removing all these cards once inhand array is under maxhandsize again
            //this code needs to know WHICH ship called it so it can call a method for this ship to continue onto the next steps.
         }
      }
   }
}





The this up above in the onRelease line.... will that mean the ship object or the tempcard+i instance of the card from the library?

What about addition references to 'this' inside the {} brackets of the onRelease funtion? Are THOSE this's the ship or the card movieclip?

Class To Manage Objects Inside A Shared Object
Something i needed for a recent project.
ActionScript Code:
//  Constructor_global.SO = function(name) {    this.name = name;};//  Method to create an object in your SOSO.prototype.createObject = function(obj) {    var so = SharedObject.getLocal(this.name);    so.data[obj] = new Object();    so.flush();};//  Method to delete an object in your SOSO.prototype.deleteObject = function(obj) {    var so = SharedObject.getLocal(this.name);    delete so.data[obj];};//  Method to display the objects in your SOSO.prototype.showObjects = function() {    var so = SharedObject.getLocal(this.name);    trace("Objects inside "+this.name+":");    for (var prop in so.data) {        trace(prop);    }};//  Method to set a property inside an object in your SOSO.prototype.setObjectProperty = function(obj, prop, content) {    var so = SharedObject.getLocal(this.name);    so.data[obj][prop] = content;    so.flush();};//  Method to get a property inside an object in your SOSO.prototype.getObjectProperty = function(obj, prop) {    var so = SharedObject.getLocal(this.name);    return so.data[obj][prop];};//  Method to display the properties inside an object in your SOSO.prototype.showObjectProperties = function(obj) {    var so = SharedObject.getLocal(this.name);    trace("Props inside "+obj+":");    for (var prop in so.data[obj]) {        trace(prop+" = "+so.data[obj][prop]);    }};//  Method to purge all objects inside an object in your SOSO.prototype.purgeObjects = function() {    var so = SharedObject.getLocal(this.name);    for (var prop in so.data) {        delete so.data[prop];    }    so.flush();};////  Usage: ////  First create an instance of your SO classso = new SO("Database");//  Create an object inside your SOso.createObject("user1");so.createObject("user2");//  You can create properties to anuy object inside your SOso.setObjectProperty("user1", "adress", "3th street");so.setObjectProperty("user1", "tel", "555-5555");so.setObjectProperty("user2", "adress", "5th street");so.setObjectProperty("user2", "tel", "123-4567");//  Print the objects inside your SOso.showObjects();//  Check the properties of any object inside your SOso.showObjectProperties("user1");so.showObjectProperties("user2");//  Purge all objects inside your SOso.purgeObjects();

Class To Manage Objects Inside A Shared Object
Something i needed for a recent project.
ActionScript Code:
_global.SO = function(name) {    this.name = name;};//  Method to create an object in your SOSO.prototype.createObject = function(obj) {    var so = SharedObject.getLocal(this.name);    so.data[obj] = new Object();    so.flush();};//  Method to delete an object in your SOSO.prototype.deleteObject = function(obj) {    var so = SharedObject.getLocal(this.name);    delete so.data[obj];};//  Method to display the objects in your SOSO.prototype.showObjects = function() {    var so = SharedObject.getLocal(this.name);    trace("Objects inside "+this.name+":");    for (var prop in so.data) {        trace(prop);    }};//  Method to set a property inside an object in your SOSO.prototype.setObjectProperty = function(obj, prop, value) {    var so = SharedObject.getLocal(this.name);    so.data[obj][prop] = value;    so.flush();};//  Method to get a property inside an object in your SOSO.prototype.getObjectProperty = function(obj, prop) {    var so = SharedObject.getLocal(this.name);    return so.data[obj][prop];};//  Method to display the properties inside an object in your SOSO.prototype.showObjectProperties = function(obj) {    var so = SharedObject.getLocal(this.name);    trace("Props inside "+obj+":");    for (var prop in so.data[obj]) {        trace(prop+" = "+so.data[obj][prop]);    }};//  Method to purge all objects inside an object in your SOSO.prototype.purgeObjects = function() {    var so = SharedObject.getLocal(this.name);    for (var prop in so.data) {        delete so.data[prop];    }};////  Usage: ////  First create an instance of your SO classso = new SO("Database");//  Create a new object inside your SOso.createObject("user1");//  You can set properties to any object inside your SOso.setObjectProperty("user1", "adress", "3th street");so.setObjectProperty("user1", "tel", "555-5555");//  You get properties for any object inside your SOtrace("user1 adress:"+so.getObjectProperty("user1", "adress"));//  Print the objects inside your SOso.showObjects();//  Check the properties of any object inside your SOso.showObjectProperties("user1");//  Purge all objects inside your SOso.purgeObjects();

Problems With DispatchEvent And With Accessing A NetStream Object Inside Custom Class
Hej Guys!

I currently work on a simple VideoObject class. This class extends Sprite. The constructor takes 3 parameters: the filename of a .flv, width and height of the video. The class does all the netConnect and netStream stuff to load the video and add it to its displayList.

My goal is that I can finally simply create a new VideoObject wherever I want, supply the 3 parameters and get the reference to a sprite containing a connected, streaming and paused video.
Then I could for example place the VideoObject somewhere on the stage and resume playing or seek or whatever.

I hope that's understandable so far.


Basically my class works. But I still encounter a bigger and a minor problem:

The bigger problem:
As you can see in the code below, I create a netStream inside my VideoObject class called ns as a public property.
But when I try to access the netStream Object through an instance of my VideoObject, I get an error telling me that I try to access a null object reference. Tracing myVideoObject.ns returns null as well.
Now what could be the problem? I mean, I should be able to access the netStream object from outside the class as well, right?

The smaller problem:
I try to dispatch a custom event when the video is ready and listen for the event from outside the class (see .fla code). The event gets dispatched but so far I have not been able to receive it.

Any ideas would be highly appreciated!


Here comes the class:

ActionScript Code:
package {
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.NetStatusEvent;
    import flash.events.SecurityErrorEvent;
    import flash.events.AsyncErrorEvent;
    import flash.media.Video;
    import flash.net.NetConnection;
    import flash.net.NetStream;

    public class VideoObject extends Sprite {
        public var videoURL:String;
        public var videoWidth:int;
        public var videoHeight:int;
        public var ns:NetStream;

        public var video:Video;
        private var nc:NetConnection;
        private var myEvent:Event;
       
        public function VideoObject(videoURL:String,videoWidth:int,videoHeight:int)
        {
            this.videoURL = videoURL;
            this.videoWidth = videoWidth;
            this.videoHeight = videoHeight;
            init();
        }
        //
        //initialize
        private function init():void
        {
            myEvent = new Event("video_loaded");
           
            nc = new NetConnection();
            nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
            nc.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
            nc.connect(null);
        }
        //
        //check network connection and proceed if successfull
        private function netStatusHandler(event:NetStatusEvent):void
        {
            switch (event.info.code) {
                case "NetConnection.Connect.Success":
                    connectStream();
                    break;
                case "NetStream.Play.StreamNotFound":
                    trace("Unable to locate video: " + videoURL);
                    break;
            }
        }
        //
        //begin video streaming
        private function connectStream():void
        {
            var ns:NetStream = new NetStream(nc);
            ns.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
            ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
            var video:Video = new Video();
            video.attachNetStream(ns);
            ns.play(videoURL);
            ns.pause();
           
            video.width = videoWidth;
            video.height = videoHeight;
            video.x = -videoWidth/2;
            video.y = -videoHeight/2;
            addChild(video);
           
            dispatchEvent(myEvent);
        }
        //
        //handle security errors
        private function securityErrorHandler(event:SecurityErrorEvent):void
        {
            trace("securityErrorHandler: " + event);
        }
        //
        //handle async error
        private function asyncErrorHandler(event:AsyncErrorEvent):void
        {
            // ignore AsyncErrorEvent events.
        }
    }
 }



and this is the fla where I create a VideoObject instance and listen for my event:

ActionScript Code:
var myVideo:VideoObject = new VideoObject("test.flv",720,405);
myVideo.x = stage.stageWidth/2;
myVideo.y = stage.stageHeight/2
addChild(myVideo);

trace(myVideo.ns);
myVideo.ns.resume();

myVideo.addEventListener("video_loaded", onVideoLoaded);


function onVideoLoaded(event)
{
    trace("video loaded");
}

Problems With DispatchEvent And With Accessing A NetStream Object Inside Custom Class
Hej Guys!

I currently work on a simple VideoObject class. This class extends Sprite. The constructor takes 3 parameters: the filename of a .flv, width and height of the video. The class does all the netConnect and netStream stuff to load the video and add it to its displayList.

My goal is that I can finally simply create a new VideoObject wherever I want, supply the 3 parameters and get the reference to a sprite containing a connected, streaming and paused video.
Then I could for example place the VideoObject somewhere on the stage and resume playing or seek or whatever.

I hope that's understandable so far.


Basically my class works. But I still encounter a bigger and a minor problem:

The bigger problem:
As you can see in the code below, I create a netStream inside my VideoObject class called ns as a public property.
But when I try to access the netStream Object through an instance of my VideoObject, I get an error telling me that I try to access a null object reference. Tracing myVideoObject.ns returns null as well.
Now what could be the problem? I mean, I should be able to access the netStream object from outside the class as well, right?

The smaller problem:
I try to dispatch a custom event when the video is ready and listen for the event from outside the class (see .fla code). The event gets dispatched but so far I have not been able to receive it.

Any ideas would be highly appreciated!


Here comes the class:

PHP Code:



 package {
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.NetStatusEvent;
    import flash.events.SecurityErrorEvent;
    import flash.events.AsyncErrorEvent;
    import flash.media.Video;
    import flash.net.NetConnection;
    import flash.net.NetStream;

    public class VideoObject extends Sprite {
        public var videoURL:String;
        public var videoWidth:int;
        public var videoHeight:int;
        public var ns:NetStream;

        public var video:Video;
        private var nc:NetConnection;
        private var myEvent:Event;
        
        public function VideoObject(videoURL:String,videoWidth:int,videoHeight:int)
        {
            this.videoURL = videoURL;
            this.videoWidth = videoWidth;
            this.videoHeight = videoHeight;
            init();
        }
        //
        //initialize
        private function init():void
        {
            myEvent = new Event("video_loaded");
            
            nc = new NetConnection();
            nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
            nc.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
            nc.connect(null);
        }
        //
        //check network connection and proceed if successfull
        private function netStatusHandler(event:NetStatusEvent):void
        {
            switch (event.info.code) {
                case "NetConnection.Connect.Success":
                    connectStream();
                    break;
                case "NetStream.Play.StreamNotFound":
                    trace("Unable to locate video: " + videoURL);
                    break;
            }
        }
        //
        //begin video streaming
        private function connectStream():void
        {
            var ns:NetStream = new NetStream(nc);
            ns.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
            ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
            var video:Video = new Video();
            video.attachNetStream(ns);
            ns.play(videoURL);
            ns.pause();
            
            video.width = videoWidth;
            video.height = videoHeight;
            video.x = -videoWidth/2;
            video.y = -videoHeight/2;
            addChild(video);
            
            dispatchEvent(myEvent);
        }
        //
        //handle security errors
        private function securityErrorHandler(event:SecurityErrorEvent):void
        {
            trace("securityErrorHandler: " + event);
        }
        //
        //handle async error
        private function asyncErrorHandler(event:AsyncErrorEvent):void
        {
            // ignore AsyncErrorEvent events.
        }
    }
 } 





and here is the .fla where I create a videoObject and listen for my event:

PHP Code:



var myVideo:VideoObject = new VideoObject("test.flv",720,405);
myVideo.x = stage.stageWidth/2;
myVideo.y = stage.stageHeight/2
addChild(myVideo);

trace(myVideo.ns);
myVideo.ns.resume();

myVideo.addEventListener("video_loaded", onVideoLoaded);


function onVideoLoaded(event)
{
    trace("video loaded");


[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.

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?

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 Variables Inside A MovieClip
Is there an easier way of referencing variables inside a movieClip, without having to add 'this.' in front of all of them

Here is my code on the main timeline, there is a clip called ball2

Code:
ball2.onEnterFrame = function() {
if (!dragging) {
_x = _x+xspeed;
_y = _y+yspeed;
if (_x+edg>r_e) {
_x = (r_e-edg);
xspeed = -xspeed*bounce;
}
if (_x-edg<l_e) {
_x = l_e+edg;
xspeed = -xspeed*bounce;
}
//ground
if ((_y+ldg)>b_e) {
_y = (b_e-ldg);
yspeed = -yspeed*bounce;
}
yspeed = yspeed*friction+gravity;
xspeed = xspeed*friction;
} else {
xspeed = (_x-oldx);
yspeed = (_y-oldy);
oldx = _x;
oldy = _y;
}
if (_x>throwArea) {
dragButt._visible = false;
} else {
dragButt._visible = true;
}
};
stop();
all variables xspeed.. etc.. are declared within the ball2 clip

Referencing Inside Movieclips Gives 1119
I have searched actionscript.org and the web in general for a solution to this but I have been unable to find an answer.

The issue is this I have a class that extends Loader. This class loads a compiled .swf. I need to do some actions to movieclips nested inside the loaded movieclip. I reference the nested mc's by this.content.mc1, this.content.mc2 ...

With strict mode turned on I get this message
"1119: Access of possibly undefined property mc1 through a reference with static type flash.displayisplayObject."

If I turn off strict mode everything works fine but then I miss out on the compile time error checking fun of as3. Any help would be greatly appreciated
-Derek

Referencing Button Inside A Loaded SWF
Hey everyone,

I'm completely new to ActionScript and have been learning what I can in bits and pieces today. I'll try to keep my problem simple. In my main movie, I have a button that loads a second swf (small window) file into the main movie. The second file "flies" in from the bottom using motion easing. I've accomplished everything fine so far except that when I press close on the popup, it abruptly disappears.

I thought I could use yoyo() to reverse the animation when close is clicked to hide the popup off screen until I need it again. I just don't know how I'm supposed to reference the close button in the second movie from the first one.

The button in the second movie instance is Exit while its class is ExitButton. To accomplish what I'm trying to do I should set up an event listener in the main movie and remove the one from the second correct?

ActionScript Code:
wbutton.buttonMode=true;
wbutton.addEventListener(MouseEvent.CLICK,onClick);
function onClick(event:MouseEvent):void {
    var box:Loader= new Loader();
    var urlrHome:URLRequest = new URLRequest("popup.swf")
    addChild(box);
    var myTween:Tween = new Tween(this, "y",Exponential.easeOut, 600, 0, 1, true)
    box.load(urlrHome);
}

Referencing An Object
I'm trying to identify which Object should be called by passing an arguement to a function


ActionScript Code:
function myAdd(imageUrl,xPos,yPos,myTransition:String) {

            var myImage:LoadObject=new LoadObject(imageUrl);
            var ExpandAPrimary:Object={scaleX:1,scaleY:1,time:.5,transition:"easeOutElastic"};
            var mytest:Object = ExpandAPrimary;
            trace("your test var is: "+ mytest);
            myImage.scaleX=0;
            myImage.scaleY=0;
            myImage.x=xPos;
            myImage.y=yPos;
            Tweener.addTween(myImage,  {base:mytest});
            addChild(myImage);
        }


When i try and replace


ActionScript Code:
var mytest:Object = ExpandAPrimary;
with the arguement myTransition:String


i get:

ReferenceError: Error #1069: Property base not found on String and there is no default value.





the initial call is


ActionScript Code:
var myclock1:ObjectTimer = new ObjectTimer(.5, 'nut1.png', 0, 50, 'ExpandAPrimary');

Referencing From Object
Hi!

Can anyone explain, how can I reference to a timeline from the object not using _root?! Is it posible?

For example:


ActionScript Code:
var someListener:Object = new Object();
someListener.onMouseMove = function() {
    trace("_root "+_root); //_root _level0
    trace("this "+this);   //this [object Object]
};
Mouse.addListener(someListener);

Referencing An Object
I'm not sure if this is good scripting practice...anyhow... I have a constructor function that creates an object and then attaches a movie onto the stage that is referenced within the original object. Now, if I attach a onPress function to the movie, is there any way to reference the very very first object? I think I am seeing a hierarchy that really doesnt exist...
An example would be:

Code:
MainObject = function(){
this.ref = _root.attachMovie("mc","my_mc",1)
this.message = "hi!"
this.ref.onPress = function(){
trace(?***?.message)}
}
Is there anything I can put in ?***? that would reference the original object and display the original objects message? Sorry if this is a dumb quesion!

Referencing Different Keyframes Inside An Embedded File
Hi everyone,

I have another rookie question. I am teaching myself flash and I have come across a problem that has got me stumped. Here it is:

I need to reference different keyframes inside and embedded swf file (sport.swf) from the menu buttons of main file(athletes.swf). Does anyone know the functions to do this?

Thanks for your help,

Robb

XML - Referencing A Text Box Inside Two Movie Clips
I currently have a text box ('text_txt') inside two movie clips ('Section3_mc' and 'Part1_mc').

I am using an XML file to populate this text box.

I am currently using the following code to do this:


Code:
_root.Section3_mc.Part1_mc.text_txt.htmlText=myXML.firstChild.childNodes[0].childNodes[4].childNodes[0].childNodes[1].childNodes[36].firstChild.nodeValue
The reason it is HTML text is that I'm using CDATA tags within the XML.

Why doesn't it work, though?

I'm assuming I have to place the above code outside all the movie clips and in a frame in the root of the Flash file? Would I be wrong in thinking this? Does it actually need to be in the topmost movie clip ('Part1_mc')?

Or is there something else wrong here?

Can I even reference a text box in this way?

All help is greatly appreciated.

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.

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

Referencing An Object In An Array
This is practically spam and I appologize. I think I can better articulate my problem now- and thought a new post would help.

If _inventory[2] = "a string" that is my Event.target I could:

trace(Event.target)

And it would trace "string".

trace(Event.target == "a string")

And it would trace true.

Same is true for:

trace(Event.target == _inventory[2])

Now, if I replace _inventory[2] with an instance of the class string_mc and it is my Event.target I can still:

trace(Event.target)

But now I get:

[object string_mc]

And I can still:

trace(Event.target == _inventory[2])

And get a true.

But if I try the equivelent of trace(Event.target == "string") I cannot make it work.

trace(Event.target == [object string_mc]) gets a syntax error.
trace(Event.target == object string_mc) doesn't work.
trace(Event.target == string_mc) comes back false.

Using === instead of == doesn't work either.

So, what do I put between the == and the closing paren to make this work?

Object Referencing Question
if i've got an MC on the main stage named "mainContact", and this mc has the code:


ActionScript Code:
onClipEvent( load )
{
    phpVars = new loadVars();
    phpVars.load( "pages/contact.php" );
    phpVars.onLoad = function( success )   
    {
        if( success )
        {
            doneLoad = "true";
        }
    }
}

i'm wanting to check from within "mainContact" if doneLoad == true, but since it's in the phpVars.onLoad function, doneLoad is registered under phpVars. how can i make doneLoad be referenced under mainContact without using absolute referecing as in, "mainContact.doneLoad = true;"?

Variable Object Referencing
Hello, I just stumbled across your forums today looking for an answer to my question on Google.

I am in no way very knowledgable with ActionScript, so this might be very simple and I am looking in all of the wrong places... but basically here is my issue:

Instead of accessing an objects attributes like this, _level0.thumbnails.thumbnail0._width = 500;

I want to be able to access it with _level0.thumbnails. (this.id) ._width = 500;

where as (this.id) is a variable that could be equal to "thumbnail0" or "thumbnail99" depending on which object gets clicked. I have everything working to if I hardcode thumbnail0 it works fine, and this.id does get set to whatever thumbnail I click's "thumbnail" + ID

... any help?

Array Referencing Object
I have created an object that I wish to put into an array. I will have several objects with different commands that are going to be in this array. I would like to specifically reference the different variables in the objects. I thought I had everything going but when I traced the array the different variables are listed as undefined. How do I specifically reference a variable of an object that is placed in an array?

var MyObj = new Object();
MyObj.Title = "CTRLA.jpg";
MyObj.Command1 = "yeah";
MyOBJ.Command2 = "Nah";



objective = new Array();
objective[0] = MyObj;
trace (objective);
for(i =0; i < objective.length; i++){
trace(objective[0].Command1);
}

Thanks,
Sam

Dynamic Object Referencing
Hi everyone,

i've built a accordeon like movie clip to present search form results for a web site. The results are "fed" into flash by .NET webservices and the "accordeon" itself is dynamic.

My question is i want to add a button to show further detail on each line of results, but i don't seem to be getting the button to be clickable inside the individual lines.

this is the code i use to build the "accordeon" display:


ActionScript Code:
// _y position
var y = 0;
// _depth
var d = 0;
 
for (i = 0; i < 13; i++) {
linesArray[i] = i;
d = d + 1;
y = y + 20;
// check for empty (undefined) results and stop adding lines
if (theResults.Collection[i].Referencia == undefined) {
i = numRegistos;
return;
} else {
attachMovie("acordeonLine", "line" + i, d);
// fill the line text boxes
txtRef = myresults.ref;
txtName = myresults.name;
}
// use the line it self as a button to slide open and show photos
this["line"+i].onRelease = function{
trace("HEY! YOU CLICKED ME!");
}
}


inside the each "accordeonLine" mc there's a button called btDetails i'm trying to use by adding this (or similar) code inside the for loop that adds line to the accordeon:


ActionScript Code:
this["line"+i].btDetails.onRelease = function{
trace("HEY! YOU CLICKED ME!");
}


the path this["line"+i].btDetails evaluates as undefined. its like its not even there.

i've tried other "tricks" but i simply can't get the click to work.

Any ideas?

Referencing A Clip Inside A Scroll Pane Component?
can someone please tell me how to reference am MC placed inside a scroll pane component?
so i can controll it with actionscript
i tried giving the scroll pane instance a name and then using the name as though it was just part of the path but it doesnt work.....what am i doing wrong???
please ...help

Referencing Instances Inside The Symbol (CS3/4) From A Pure AS3 File
Hello everyone,
now I know this is an ancient question, and there are a million threads out there that discuss this, but they're all a bit chaotic... I've gotten all of my work in AS3 done in a pure code way, and all of my graphics have been programmatic, but now its time to load up some CS3 graphics, and Im running into walls...

I have a symbol, and inside of it I have bunch of other symbols with instance names assigned...
- how would I go about accessing these if I loaded the SWF with that symbol in it?
- how would I create an instance of that main symbol, from a loaded SWF?

help is much appreciated
thank you

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

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 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 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.

Sub MC Referencing From Dynamically Named Object
Hello All!

Here's what I'm trying to do. I have a base movie clip with 2 inner movie clips inside it. I am dynamically setting the color of one of the inner movies. Here is my code

code:
sqColor = new Color(_root["square" + j].filler);
sqColor.setRGB(thisColor);


This code sets the color of a movie labeled filler within my "square"+j MC.

Accessing the dynamic variable name through the _root array works fine. HOWEVER! I cannot use the _root array. I am using the loadMovie function in another MC to call this MC. So the _root array is no longer the same and it doesn't work.

Is there another way to do this? I've tried to access the "square"+j object with out the _root reference, but no luck.

Any suggestions? THANKS IN ADVANCE!!

AttachMovieClip - Referencing A Dyamic Object
I have begun using the attachMovieClip() recently to dynamically assign objects to movieclips. Up until now it has been excellent, and is perfect for assigning various enemy sprites to instances of a movieclip etc.

At the moment though i am having problems getting messages through to the 'attached' clip to tell it to stop() or play() etc. The info is a little unclear on this topic, but it seems that if i use code like:

dummy.attachMovie(cat, cat add i, 1);

and then say dummy.stop(), that it only targets the original 'dummy' clip and not the 'cat' movie i have attached. I have tried referencing it with the assigned name, but i must be missing something or doing it wrong, any ideas??

thanks!!

Referencing Object Using Variable Syntax
I'm having trouble referencing an object using a variable in Flash MX.
In this example, I'm dynamically loading jpegs and need to test that they have finished loading.
The img var contains the url of the image to load.


On the first frame:

for(i=0; i<number_of_images; i++)
{
//duplicate the holder
duplicateMovieClip(my_movie.holder, i, i);

//create reference for the img to load
img_to_load = "my_movie.holder." + i;

//load image into the duplicated movie
img_to_load.loadMovie(img_url);
}

On another frame:
if(img_to_load.getBytesTotal() >= img_to_load.getBytesLoaded() )
{
//image has loaded
}else{
//image still loading
}


My problem is that img_to_load is a variable that returns a string and not an object - what do I need to do?

Thanks in advance

[Help] Classes Object Ownership And Referencing
I want to access methods and data of an object A from another object B - which was created in the object A. However, using the _parent property doesn't work. I need an explanation why doesn't it work.

To futher clarify my question, I have a problem when using classes in this way:

code:
class MyClass
{
var Some_Data:MyOtherClass;

function MyClass
{
Some_Data=new MyOtherClass();
}

function DoSomething():Void
{
trace("Did something.");
}
}

class MyOtherClass
{
function MyOtherClass
{
SomeProcedure();
}
function SomeProcedure:Void
{
_parent.DoSomething();
}
}


When I create an instance of the MyClass there is no output. I need an explanation why this is so.

Edited: Have corrected some mistakes in this thread

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