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








BroadcastMessage From Class


For the Flash application I'm developing, I would like to be able to make custom listeners. I've got a class and want to broadcast an event from within that class. Then I would like to let objects outside of that class listen for these events that the instances of the class will broadcast.
First of all, that should be possible right?

Then second, how do we do this in Flash? If I try to use broadcastMessage, the compiler complains: There is no method with the name 'broadCastMessage'.

The problem is that I would like to let my class broadcast an event, not an object I create at runtime like in the examples.




KirupaForum > Flash > ActionScript 1.0/2.0
Posted on: 06-20-2006, 05:59 AM


View Complete Forum Thread with Replies

Sponsored Links:

Add Listener And BroadcastMessage
Im back to learning flash after a year off doing css xhtml sites, forgot how frustrating and satisfying it can be.

im creating a drop down menu, Ive used robert penners easing equation for the motion. Then I noticed that he had used
Code:
this.broadcastMessage("clipIsGone", this._parent);
//Which I traced to make sure of target
trace("broadcast "+ this._parent._name)
So makes sense to add a listener to the mcs which move, however im having no joy, or ive just not understood listeners correctly, ive tried
Code:
_root.myClip["menuItem"+s].addListener(_root.blank)
_root.blank.clipIsGone = function(){
trace("gone");
}
//also tried
function clipIsGone(){
trace("gone");
}
any ideas?

View Replies !    View Related
About BroadcastMessage Problem?
Hi all, I have the code following, but it does not do trace("ClassBegin").
Anyone tell my the problem? Thanks in advance!

King = {};
ASBroadcaster.initialize(King);
function aStudent(){

}
aStudent.prototype = new MovieClip();
aStudent.ClassBegin = function()
{
trace('ClassBegin');
}
aStudent.prototype.ClassEnd = function()
{
trace('ClassEnd');
}
Object.registerClass("aStudent",aStudent);
this.attachMovie("aStudent", "s", i);
King.addListener(_root["s"]);

King.broadcastMessage("ClassBegin");

--------
MT

View Replies !    View Related
Warning: BroadcastMessage Is Not A Function
Targeting Player 8/ AS 2 - this project is generating continual warnings (up to the limit):

Warning: broadcastMessage is not a function

"broadcastMessage" is not anywhere in my code (actually someone else's that I've been asked to modify)
It only appears when I run the SWF in a browser, not when I preview within Flash
It seems to relate somehow to the use of Tween (see code below), but why why why?








Attach Code

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

stop();

//xml loaders

var homeXML:XML = new XML();
homeXML.ignoreWhite = true;
homeXML.onLoad = function(success:Boolean):Void {
if (success) {
//_root.gotoAndStop("init");
trace("loaded");
} else {
trace("xml failed");
}
};


var featureXML:XML = new XML();
featureXML.ignoreWhite = true;
featureXML.onLoad = function(success:Boolean):Void {
if (success) {
homeXML.load("xml/info.xml");
} else {
trace("featureXML failed");
}
};
featureXML.load("xml/features.xml");


var stageTween:Tween = new Tween(stage_mc, "_alpha", Regular.easeIn, 0, 100, 20, false);
trace(stageTween);

View Replies !    View Related
Stage.broadcastMessage("onResize")
Stage.broadcastMessage("onResize") doesn't seem to work. I have a lot of classes that add new content to the stage at runtime and would like to be able to call all the different onResize functions in various classes that listen for a stage resize so things get positioned correctly. Do I need to do some plumbing or is there a way to tell the Stage to broadcast a message?

Thanks for any help.

View Replies !    View Related
AS2: "no Method With The Name 'broadcastMessage'"
Why does this external class file not compile? I want it to be able to broadcast events to listeners but using "AsBroadcaster.initialize(this);" in the constructor does not seem to be enough. Any suggestions?


ActionScript Code:
class QueLoader{    private var mcLoader:MovieClipLoader;    private var qlListener:Object;    private var qlItemsLoadingArray:Array;    private var qlTargetMCArray:Array;    private var qlCurrentLoading:Number;        function QueLoader(){        qlCurrentLoading = 0;        qlItemsLoadingArray = new Array();        qlTargetMCArray = new Array();        mcLoader = new MovieClipLoader();                qlListener = new Object();        //Do when Item begins loading        qlListener.onLoadStart = function(target:MovieClip){                    };        //Do when item loading progresses        qlListener.onLoadProgress = function(target:MovieClip, bLoaded:Number, bTotal:Number){                    };        //Do when item loading complete        qlListener.onLoadComplete = function(target:MovieClip, httpStatus:Number){                    };        //Do when item loading error        qlListener.onLoadError = function(target:MovieClip, errorCode:Number, httpStatus:Number){                    };        mcLoader.addListener(qlListener);                //This que should be able to broadcast events        AsBroadcaster.initialize(this);     }            public function addToQue(item){            }        public function removeFromQue(item){        //If que is now empty        this.broadcastMessage("queEmpty");    }        public function pauseQue(item){        this.broadcastMessage("quePaused");    }        public function resumeQue(item){        this.broadcastMessage("queResumed");    }        public function getTotalBytesInQue(){    }}

View Replies !    View Related
Calling A Function In Main Class From A Loaded Swfs Document Class
Hi
I have a main.swf that loads page.swf. They each have a document class called "Main" and "Page".

How can I call a function in Main from Page?

In AS2 this would be somthing like _parent.myFunction();


Cheers

View Replies !    View Related
Class Question: How To Access Timeline Objects From Class W/o Arguments
Hey all,

I am looking into builiding an application with OO functionality. I understand most of it. Except I cannot figure out how to access something in my app from a class. For instance, lets say I have one Loader class that loads some data and stores it in a variable inside the class (or on the main timeline, doesn't matter). Now, I know I can pass a reference to the data in an argument to another class for that class to manipulate. But if I have several data sources, and other variables and such, that I need to modify in a single class function, how would I do that without having to give the function access to them through arguments? I just want to be able to say, from a class, something like _root.someObject.someFunction();

So, any help would be greatly appreciated, and sorry if that made no sense at all, I tried to explain as best I could.

Happy Holidays!
Dave

View Replies !    View Related
[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.

View Replies !    View Related
AS3 Project In FDT + Flex SDK. Root Class Extends Visual Class From Swc
hello
question about compiling as3 project under FDT 3.0 with Flex SDK.

I want my main root class to contain some graphics already at the start. In Flash IDE I put some objects on the stage, make new symbol with all those objects inside, set linkage to MainClassGraphics, export it to swc, add this swc to source folder class-path. Then I write my root class:

Code:
package {

public class MainClass extends MainClassGraphics {
public function MainClass() {
trace('hey');
}
}
}

compiling with flex2 sdk - and I don't see any graphics. why?

if i try this way:

Code:
package {
import flash.display.Sprite;

public class MainClass extends Sprite {
public function MainClass() {
var s:Sprite = new MainClassGraphics();
addChild(s);
trace('hey');
}
}
}

then I see my graphics.. so swc looks like fine


crosspost here http://fdt.powerflasher.com/forum/vi...hp?f=21&t=2268

View Replies !    View Related
Accessing A Dynamic Text Field In A Class Other Than The Primary Class
I have tried to read and understand some of the other threads for this issue but, I think it would be easier to understand if I show my specific issue. I left some code out to make my issue more clear.

Alpha is the primary class with access to the stage. If I write the event listener and function contained in the Bravo function into the Alpha function it works. Although, I want it to be in a different class in the same package (such as the Bravo class).

I have created a instance of a class which is a physical object on the stage (lets say it's a card). The event listener is in the instance so that each instance has a self contained listener.

The bottom line is it works in the primary class but in no others. How can I make it access the text field (so when I click on the "card" the text field shows "something"?


ActionScript Code:
package a {
     public class Alpha {
          public function Alpha() {
               x:Bravo = new Bravo();
          }
     }
}

package a {
     public class Bravo {
          public function Bravo() {
               this.addEventListener(MouseEvent:CLICK, clickEvt);

               function clickEvt(event:MouseEvent) {
                    <MovieClip>.<MovieClip>.<DynamicTextField>.text = "something";
               }
          }
     }
}

View Replies !    View Related
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);

View Replies !    View Related
ActionScript 2.0 Class Scripts May Only Define Class Or Interface Constructs.
This is driving me nuts. I have an old AS1 project which I upgraded to AS2. It uses an include file, settings.as, which has stuff like this:
settings = new Object();
settings.property = 'some value';

Then I include it on the main timeline like this:
#include "settings.as"

Every time I render, I get a million and one Compile Errors stating:
"ActionScript 2.0 class scripts may only define class or interface constructs."

But it isn't an ActionScript 2.0 class! It's just a regular include. How do I avoid the bogus Compile Errors?

View Replies !    View Related
AddChild Works With Document Class, But Not Timeline-instantiated Class
I cannot get a sprite to display for me when I create an instance of a very simple class in my FLA file's timeline.
However, when I make the class file the FLA's document class file, it displays just fine.
The task in question is simply drawing a square with the shape class.

Problem example:
My class, Test.as, resides in the same folder as my FLA file - so I don't use any import statement. I'm new to lots of CS3 stuff. Can anyone tell me why this doesn't work and create the shape on the stage? This seems to fail silently without any errors:
var myTest:Test = new Test();

Working example:
Setting the document class to Test.










Attach Code

// Test class

package {
import flash.display.*;

public class Test extends Sprite {

public function Test():void{
doThing();
}

private function doThing():void{
var myRect:Shape = new Shape();
myRect.graphics.lineStyle (2, 0xcc0000, 1);
myRect.graphics.beginFill(0xcccccc, 1);
myRect.graphics.drawRect(10, 10, 200, 200);
addChild(myRect);
}
}
}

View Replies !    View Related
[AS3] Making An Auto-generated Class Inherit From Custom Class?
hi, just wondering if this is possible

i was hoping to find a way to get a bunch of objects in my library to inherit from (or even be) one class that i have made, but without having to make .as files for every single one

is this possible, or is there any other way to give objects another classes functionality in an auto-generated class?

cheers

View Replies !    View Related
Tough One: Accessing Class Methodes From Other Class Files
Tough question for the experts...

In my classfile class Classes.tools.depthManager, I've got a static methode


Code:
public static function getLoopDepth():Number {
In another classfile Classes.tools.frameRateViewer, I want to access that methode


Code:
var tempDepth = Classes.tools.depthManager.getLoopDepth();
The compiler claims: "There is no class or package with the name 'Classes.tools.depthManager' found in package 'Classes.tools'."

So I tried writing import Classes.tools.* at the top of my Classes.tools.frameRateViewer.as, hoping I could just write


Code:
var tempDepth =depthManager.getLoopDepth();
But there the compiler claims: "The class being compiled, 'Classes.tools.depthManager', does not match the class that was imported, 'depthManager'."

I'm sure the Classes.tools.depthManager.as works fine: I can call the static depthManager.getLoopDepth() from a button in the fla file...

Any ideas? Thanks!

View Replies !    View Related
Window Class Attach Scrollbar/Pane Class?
I am using MX 2004 Prof...

Is there a way to attach a scrollbar/pane to the body of a Window class to make the content scroll?

View Replies !    View Related
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

View Replies !    View Related
[Flash8] Calling BitmapData Class From Within Custom Class
I've written a custom class which resides in a .as file. Is there any way that functions from within my class can call the BitmapData class for bitmap manipulation?

View Replies !    View Related
**Error** ActionScript 2.0 Class Scripts May Only Define Class........
**Error** ActionScript 2.0 class scripts may only define class or interface constructs.
b2.onPress = function() {

**Error** ActionScript 2.0 class scripts may only define class or interface constructs.
b3.onPress = function() {

**Error** ActionScript 2.0 class scripts may only define class or interface constructs.
b4.onPress = function() {

ok this is what i have.

1 Movie clip with links to a .as file all is working fine the above error occurs when i publish the 1 movie clip which is getting pulled into the main movie

Any idea's it does not happen when 1 movie clip is published on its own just when 1 move clip is pulled into my main movie clip.

View Replies !    View Related
[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.

View Replies !    View Related
Child Class Trigger Event For Parent Class
is there a way for a parent class to listen to a variable in a subclass, and when it changes, run a function?

This seems like a pretty simple thing to do. I'm trying to keep my subclass independent of my main class, so i just have a variable that is set to false, and when its finished, it sets the variable to true.

The only thing i can think of is having an onEnterFrame that keeps checking the variable...but it seems like an event would be more efficient.

thanks!

View Replies !    View Related
Tween Class Applied In Custom Class Not Working
var sizerW:Object = new Tween(pda_mc,"_xscale",mx.transitions.Tween.None.e aseNone,pdaOrigW,pdaSmallW,3,true);

this code produces and error when applied in a custom class but not in a fla?

the error = There is no property with the name 'None'.

View Replies !    View Related
Custom Transitionmanager Class Problem/class Scope?
I'm writing a class that fades from one scene to another in a video game. A custom transitionManager object is created, and a listener is attached. Once the fade out from one scene is complete, the listener is triggered, the scene switches, and the new scene fades in.

This is the error I'm getting: "There is no method with the name 'myTransitionManager'.
myTransitionManager.addEventListener("allTransitio nsOutDone", fadeListener);". It is given everytime myTransitionManager is accessed by any of the class functions.

I assume this is a class scope issue. How can I create a custom transitionManager object accessable to the entire class? I need it to be accessed by at least three separate class functions.

Here's the source, starting with the constructor for the GameSection class:


Code:
public function GameSection(clip_to_fade:MovieClip){
var myTransitionManager:TransitionManager = new TransitionManager();
}

//class methods

function switch_section(clip_to_fade:MovieClip, fade_in_scene:String) {
// Define a listener object to use with the Tween objects.
var fadeListener:Object = new Object();
//create event listener for transitions being complete
fadeListener.allTransitionsOutDone = function(eventObj:Object) {
trace("allTransitionsOutDone event occurred.");
gotoAndPlay(fade_in_scene);
fadeIn(clip_to_fade);
};
myTransitionManager.addEventListener("allTransitionsOutDone", fadeListener);


fadeOut(clip_to_fade);
}

function fadeIn(in_mc:MovieClip) {
myTransitionManager.start(in_mc, {type:Fade, direction:Transition.IN, duration:1, easing:None.easeNone});
}

function fadeOut(out_mc:MovieClip) {
myTransitionManager.start(out_mc, {type:Fade, direction:Transition.OUT, duration:1, easing:None.easeNone});
}


Thanks!

View Replies !    View Related
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?

View Replies !    View Related
Why Is An Event On One Class Object Being Broadcast For All Instances Of That Class?
I have a custom class called McText which extends MovieClip, and includes an input text field. That class has a function to register itself as a listener to Key - Key.addListener(this). It does not register by default.

There are multiple instances of McText. But even though I only call the function to register on one of those instances, ALL of them fire an onKeyDown function when i type into their text field, regardless of whether i've registered that particular object to Key or not. I register one, I register them all.

This is a little annoying because I use this class everywhere, and I want to be able to assign an onKeyDown function for only one of them. At first i tried writing that function outside of the class itself, as in:
classObject.onKeyDown = function()
But that, perhaps unsurprisingly, created an onKeyDown function for every instance again.

I thought to myself "I know, I'll register McText with Key by default (in the constructor), write an McText.onKeyDown function in the class itself, and then get that function to use a broadcaster". The idea being that onKeyDown will fire on all of them, but the broadcaster will be registered to a specific listener on an object by object basis.

So I did that, and created a function to register a broadcaster listener. I then created a broadcaster listener in a seperate, different, class, throw it to the McText function so it registers with its broadcaster and guess what? Now that listener receives an event from every instance of that class.

There's no explicit use of static vars or functions anywhere.

Sorry for the long question, but can anyone enlighten me as to what's going on? You get virtual chocolate if you do

View Replies !    View Related
How Do You Listen In One Class For A Custom Event Dispatched From Another Class?
I am not sure how to word this, so here is what I would like to happen:

MyDocumentClass contains an instance of MyItem and MyItemManager. MyItem will fire an ItemEvent.ITEM_CHANGED event. I want MyItemManager to listen and react to that event. Possible? Here's my code:

ItemEvent.as:

ActionScript Code:
package
{
    import flash.events.Event;
   
    public class ItemEvent extends Event
    {

        public static const ITEM_EVENT:String = "itemEvent";
       
        public function ItemEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false)
        {
            super(type, true);
        }
       
        public override function clone():Event
        {
            return new ItemEvent(type);
        }
       
        public override function toString():String
        {
            return formatToString("ItemEvent", "type", "bubbles", "cancelable");
        }

    }
}

MyDocumentClass.as:

ActionScript Code:
package {
    import flash.display.Sprite;
    import MyItem;
    import MyItemManager;
   
    public class MyDocumentClass extends Sprite
    {
        public var item:MyItem;
        public var manager:MyItemManager;
       
        public function MyDocumentClass()
        {
            item = new MyItem();
            manager = new MyItemManager();
            item.dispatchCustomEvent();
        }

    }
}

MyItem.as:

ActionScript Code:
package
{
    import flash.display.Sprite;
    import flash.events.EventDispatcher;
    import ItemEvent;
   
    public class MyItem extends Sprite
    {
       
        public function MyItem()
        {
        }
       
        public function dispatchCustomEvent():void
        {
            dispatchEvent(new ItemEvent(ItemEvent.ITEM_EVENT));
        }
    }
}

MyItemManager.as:

ActionScript Code:
package
{
    import flash.display.Sprite;
    import ItemEvent;
    import flash.events.EventDispatcher;
   
    public class MyItemManager extends Sprite
    {
               
        public function MyItemManager()
        {
            addEventListener(ItemEvent.ITEM_EVENT, handleItemEvent);
        }
       
        public function handleItemEvent(e:ItemEvent):void
        {
            // do something here
        }
    }
}

View Replies !    View Related
Document Class Initialising Another Class With Display Objects
Hi

I'm currently learning AS3 and have got stuck with something fundamental to do with Flash and the Document Class.

I have a very simple Document Class as follows:

package {

import flash.display.*;
import com.Application;

public class EntryPoint extends Sprite {
public function EntryPoint() {
var app:Application = new Application();}}

}

I then would like to build out into other classes/patterns and want the following code to simply attach an item from the library on to the stage.

The item in the library has a Class reference of CircleTest and has a Base Class of flash.display.Sprite.

My Application class is as follows:

package com {

import flash.display.*;

public class Application extends Sprite{
public function Application() {
var mc_root:Sprite = new Sprite();

addChild(mc_root);

var circleTest:CircleTest = new CircleTest();

mc_root.addChild(circleTest);}}

}


When I compile this from Flash I get nothing other than an empty stage :-(

Please can someone tell me what I'm doing wrong here.

Many thanks in advance

D

View Replies !    View Related
How Do I Access A Variable Declared In My Document Class From Another Class
Hi there,

I'm pretty new to classes and am probably missing something really basic so apologies if this seems like a stupid question.

I'm trying to access a variable that I've declared in my document class from within another class.

I know I can pass the variable through when I call the class as follows:


Code:
var myBall:Ball = new Ball(5);
and pick this up in the Ball function within my Ball class as follows:


Code:
public function Ball(ballSpeed) {
trace(ballSpeed);
}
But what if I don't want to do that as I have a whole load of general global variables I want to access which were defined in my document class?

What I actually want to do is just have access to all the variables defined in the document class from within the Ball class.

I tried parent.variableName and various other ways of accessing what I need but all of them spit back errors.

Any help would be really appreciated - I'm sure this is very basic but I'm totally stuck on this.

Many thanks.
Ian

View Replies !    View Related
Applying A Custom Class To An Object In The Document Class...
How's it going guys. I just started learning Actionscript 3.0 and so far not bad. However, I'm having trouble applying custom created classes to objects in the main document class. I'm using Flash as the application, however there is no timeline scripting involved. I loaded the document class called Main.as:


ActionScript Code:
package
{
    import flash.display.MovieClip;
    import flash.net.URLRequest;
    import flash.display.Loader;
   
    public class Main extends MovieClip
    {
        private var _redBox:Loader = new Loader();
        private var _redBoxLink:URLRequest = new URLRequest("images/redbox.jpg");
        public var buttonScaleHover:ButtonScaleHover = new ButtonScaleHover();
       
        public function Main()
        {
            _redBox.x = 100;
            _redBox.y = 100;
            _redBox.load(_redBoxLink);
            addChild(_redBox);
        }
    }
}

Now, what I'm trying to do is apply this class named ButtonScaleHover.as to the _redBox in the document class. Here is the code for ButtonScaleHover:


ActionScript Code:
package
{
    import flash.display.Sprite;
    import flash.events.MouseEvent;
   
    public class ButtonScaleHover extends Sprite
    {
        private var _xScale:Number;
        private var _yScale:Number;
       
        public function ButtonScaleHover()
        {
            trace("The ButtonScaleHover Class is being loaded");
            _xScale = this.scaleX
            _yScale = this.scaleY
            this.addEventListener(MouseEvent.ROLL_OVER, onRollOver);
            this.addEventListener(MouseEvent.ROLL_OUT, onRollOut);
        }
       
        public function onRollOver(event:MouseEvent):void
        {
            this.scaleX *= 2;
            this.scaleY *= 2;
        }
       
        private function onRollOut(event:MouseEvent):void
        {
            this.scaleX = _xScale;
            this.scaleY = _yScale;
        }
    }
}

I tried using
ActionScript Code:
_redBox.ButtonScaleHover();
in the document class after i added it to the display object list. However, it didn't work. Basically, I'm just trying to apply a custom class to an object(in this case the loader). Thank you guys very much in advance.

View Replies !    View Related
Call Function Of Document Class From MovieClip Class
How can I run a function of the main document class from a class of a MovieClip? I usually just used MovieClip(parent).function(), but now my MovieClip has another parent. Or what do I have to pass to the MovieClip class when creating the MovieClip to acess the main document class?

View Replies !    View Related
Sharing Vars Between Document Class And An Imported Class.
I'm working on my first really in depth AS3 project, learning as I go.

I've been sorting through the XML docs and i've bumped my head into a bit of a question. So, to preface, I have been able to load the XML successfully, but I want to be able to use my own XML loader class to load the XML and then be able to reference it from the document class. Also, I'd like to be able to send a file path to the loader class when I call it.

Not sure if that makes sense, but I will post what I did and see how bad it is


The document class:

ActionScript Code:
package rg.sites{
   
    // flash classes
   
    import flash.display.MovieClip;
    import flash.display.Sprite;
    import flash.events.*;
    import flash.display.Graphics;
    import flash.display.Shape;
    import flash.text.*;
    import flash.utils.Timer;
    import flash.events.TimerEvent;
    import flash.net.*;
    import flash.errors.*;
   

    // RG classes
   
    import rg.classes.XMLSiteLoader;

    // Layout Objects

    public class SiteCurrent extends MovieClip {
       
        // vars
        public var siteLoader:XMLSiteLoader;
        public var site_xml:XML;
        public var xml_site_loading:String = "current_site.xml";
   
        public function SiteCurrent() {
            trace("Site Current is loaded");
            siteLoader = new XMLSiteLoader();
            siteLoader.addEventListener(Event.COMPLETE, xmlSiteLoaded);
        }//end constructor function
       
        private function xmlSiteLoaded(event:Event):void {
       
        trace(site_xml.toXMLString());
        trace("
" + "Background art: " + site_xml.section.(@id == "Splash"));
       
        }
       
       
    }//end class
}//end package

The XMLSiteLoader class:


ActionScript Code:
package rg.classes

//
// XMLSiteLoader version 0.1 beta
//

{
    //import fl.controls.*;
    import flash.net.*;
    import flash.events.*;
    import flash.errors.*;
   
    public class XMLSiteLoader extends EventDispatcher {
        //public var site_xml:XML;
       
        private var siteReq:URLRequest;
        private var siteLoader:URLLoader = new URLLoader();
        public var site_xml:XML;
        public var xml_to_load:String;
       
       
        public function XMLSiteLoader() {
            //trace(stage.xml_site_loading);
            if(xml_to_load == true) {
                trace("xml file path sent");
                siteReq = new URLRequest(xml_to_load);
               
            }
            else {
                trace("No XML file path sent, use default value");
                siteReq  = new URLRequest("current_site.xml");
            }
           
            trace("XML Site Loader is loading: " + siteReq);
            siteLoader.load(siteReq);
            siteLoader.addEventListener(Event.COMPLETE, xmlLoaded);
           
           
           
        } // constructor class
       
       
        private function xmlLoaded(event:Event):void {
        site_xml = new XML(siteLoader.data);
        trace("
" + "from XML Site Loader: " + site_xml.section.(@id == "Splash"));
        dispatchEvent(new Event(Event.COMPLETE));
        }
       
       
    }//end class
}//end package

I get an error that says:


Quote:




Site Current is loaded
No XML file path sent, use default value
XML Site Loader is loading: [object URLRequest]

from XML Site Loader: portfolios/splash_gallery/splash.xml
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at rg.sites::SiteCurrent/xmlSiteLoaded()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at rg.classes::XMLSiteLoader/xmlLoaded()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()




Thanks in advance for any thoughts or suggestions.
-g

View Replies !    View Related
Displaying A TextField From A Class That Is Called From My Document Class
I'm having a problem with my main project so I've made a small test project to replicate it. The code's included here.

I've created a new .fla called TextboxFromClass.fla that's empty except for a linked in Document class called TextboxFromClass.as

I've created another class called TextboxClass.as

Everything's linked and referenced properly - when I run it there's no errors and I get a trace output "Got here" but only the TextField for the Document Class displays ("From the Doc Class"), not the one from the TextboxClass ("From the TextBoxClass Class").

I'm guessing it's a scope thing but I'm fairly new to ActionScript 3.0 so I'd appreciate your help.







Attach Code

//Code in the Document Class (called TextboxFromClass.as

package script
{
import script.*
import flash.display.MovieClip;
import flash.text.*;

public class TextboxFromClass extends MovieClip
{
var inputNameLabel:TextField = new TextField();
var backgroundGreen : int = 0x2E510B;
var foregroundGreen : int = 0x00FF99;

public function TextboxFromClass()
{
with (inputNameLabel)
{
x = 300;
y = 200;
width = 200;
height = 30;
text = "From the Doc Class";
}
var format:TextFormat = new TextFormat();
with (format)
{
font = "Arial";
color = foregroundGreen;
size = 20;
}
inputNameLabel.setTextFormat(format);
addChild(inputNameLabel);

//This should output some text like the above - but doesn't
var abc:TextboxClass = new TextboxClass();
}
}
}

// Code in TextboxClass.as

package script{
import script.*;
import flash.display.MovieClip;
import flash.text.*;

public class TextboxClass extends MovieClip {
var t:TextField = new TextField();
var backgroundGreen : int = 0x2E510B;
var foregroundGreen : int = 0x00FF99;

public function TextboxClass() {
with (t) {
x = 300;
y = 250;
width = 300;
height = 30;
text = "From the TextBoxClass Class";
}
var format:TextFormat = new TextFormat();
with (format) {
font = "Arial";
color = foregroundGreen;
size = 20;
}
t.setTextFormat(format);
addChild(t);
trace("Got here");
}
}
}

























Edited: 02/09/2008 at 07:42:24 AM by SoCentral2

View Replies !    View Related
Tween Class In Custom Extend MovieClip Class
I want to use the tween prototype in a custom class that extends MovieClip. I am already including "lmc_tween.as" in my root and I have already replaced the "MovieClip.as" file in my flash directory with the one from the shared/Zigo directory. However, I still get compiler errors if I try to include "lmc_tween.as" in the class file, or without the include in the class it will compile but the tween prototype will not work in the custom class. Does anyone know how to fix this?

View Replies !    View Related
Checking To See If One Instance Of Class Hits Other Instances Of The Same Class?
Hi guys, the idea is similar to Yugop.com JAMPACK 01.

Let's say i have a bunch of balls/cells. I'm having trouble figuring out how to make it so that every other ball bounces off of every other ball.

so in short, it's really one instance being able to check all other instances of the same ball class?

any ideas guys and if you dont know what im talking about, please feel free to state that also.

View Replies !    View Related
Instantiating Character Class Inside Of Game Class
I am having a problem instantiating a Character class inside of a game class.

P.S. I am working on converting http://oos.moxiecode.com/tut_01/index.html these tutorials to A.S. 2.0.

Game:
ActionScript Code:
if ( i == charPos[1] && j == charPos[0] ) {
var char:Character = new Character();
char._x = (j*tileWidth)+tileWidth/2;
char._y = (i*tileHeight)+tileHeight/2;
}




Character:
ActionScript Code:
class classes.Character extends MovieClip {
function Character() {
var h = createEmptyMovieClip("holder", getNextHighestDepth());
var char = h.attachMovieClip("char", "char", getNextHighestDepth());
trace("new character created");
}
}

View Replies !    View Related
How Can A Child Class Pass Values To A Parent Class?
How can a child class pass values to a parent class?

Thanks to joshchernoff I've learned how to send events to a parent class and that works great. However I can't figure out how to pass values thru an event. Can anyone enlighten me?

View Replies !    View Related
Applying A Custom Class To An Object In The Document Class...
How's it going guys. I just started learning Actionscript 3.0 and so far not bad. However, I'm having trouble applying custom created classes to objects in the main document class. I'm using Flash as the application, however there is no timeline scripting involved. I loaded the document class called Main.as:

package
{
import flash.display.MovieClip;
import flash.net.URLRequest;
import flash.display.Loader;

public class Main extends MovieClip
{
private var _redBox:Loader = new Loader();
private var _redBoxLink:URLRequest = new URLRequest("images/redbox.jpg");
public var buttonScaleHover:ButtonScaleHover = new ButtonScaleHover();

public function Main()
{
_redBox.x = 100;
_redBox.y = 100;
_redBox.load(_redBoxLink);
addChild(_redBox);
}
}
}


Now, what I'm trying to do is apply this class named ButtonScaleHover.as to the _redBox in the document class. Here is the code for ButtonScaleHover:


package
{
import flash.display.Sprite;
import flash.events.MouseEvent;

public class ButtonScaleHover extends Sprite
{
private var _xScale:Number;
private var _yScale:Number;

public function ButtonScaleHover()
{
trace("The ButtonScaleHover Class is being loaded");
_xScale = this.scaleX
_yScale = this.scaleY
this.addEventListener(MouseEvent.ROLL_OVER, onRollOver);
this.addEventListener(MouseEvent.ROLL_OUT, onRollOut);
}

public function onRollOver(event:MouseEvent):void
{
this.scaleX *= 2;
this.scaleY *= 2;
}

private function onRollOut(event:MouseEvent):void
{
this.scaleX = _xScale;
this.scaleY = _yScale;
}
}
}


I tried using
_redBox.ButtonScaleHover();in the document class after i added it to the display object list. However, it didn't work. Basically, I'm just trying to apply a custom class to an object(in this case the loader). Thank you guys very much in advance.

View Replies !    View Related
Import Entire Class Directory Vs Specific Class
First off i've already tried searching for the answer with no luck.

Is there any benefit to only importing the specific classes you need as opposed to importing the entire class directory?

Example:
import flash.display.Loader;
import flash.display.StageScaleMode;
import flash.display.StageAlign;
import flash.display.Sprite;
import flash.display.BlendMode;
import flash.display.Bitmap;
import flash.display.BitmapData;
etc.....

vs
import flash.display.*;


Id like to clean up my code but not at the expense of performance....or does this just increase compile time?

View Replies !    View Related
Call Function In Parent Class From Child Class
Right, so I have a main Document class called Bundl where I'm loading all my other classes (navigation, portfolio, ...). What I'm trying to accomplish is to call a function inside my main Bundl class from a click from the navigation class.

The situation in code:
The Bundl Class (located in the root folder)

Code:
package {
import be.bundl.Navigation;

public class Bundl extends Sprite {
//vars called here

public function Bundl() {
nav=new Navigation("xml/navigation.xml");
addChild(nav);
}
//some more irrelevant functions here

//the function I need to call from the Navigation Class
public function portfolioXML(newXML:String):void {
portfolio=new Portfolio(newXML);
contentContainer.addChild(portfolio);
}
}
}
The code from Navigation class (located in /be/bundl)

Code:
//inside the btnClick function
var test:Bundl = new Bundl();
test.portfolioXML(_someVar)
Which results in an :
Error: Error #2136: The SWF file file:///Macintosh%20HD/Users/cerbellum/Projects/Bundl/site/FINAL/FULL.swf contains invalid data.at be.bundl::Navigation/btnClick()

I'm guessing this is due to the fact that I'm calling the parent class in a child or something like that, but how do I get this done otherwise? I must totally be overlooking something here.

Thanks in advance,
Kevin

View Replies !    View Related
CycleManager Class: Helper Class To Handle Events
Last edited by Codemonkey : 2007-01-24 at 10:55.
























I am just starting to get my feet wet with AS3 and thought I would post one of my first classes here for everyone to check out. While reading about Events in AS3 I noticed that one of the snippets of code I use most often as a Flash animator in AS2 is onEnterFrame functions. Seeing as how handling events takes a bit more legwork in AS3 and I would be typing the same stuff over and over to make something loop easily, I thought I would write this helper class to make it easier. I plan on adding to this but basically it allows you to add an onEnterFrame or Timer event as easily as this:


ActionScript Code:
_newManager = new CycleManager ();
_newCycle = _newManager.add (functionNameHere);

This would continue by default to just start an onEnterFrame loop and call the thrown function each time, etc. I know, I know, it's an easy class but hey I'm just getting started

Please see below for full classes and usage examples. Thank you!


ActionScript Code:
/*
    -------------------------------------
    DESCRIPTION:
    -------------------------------------
   
    Cycle Class that wraps both the TimerEvent.TIMER and Event.ENTER_FRAME classes
   
    -------------------------------------
    USAGE:
    -------------------------------------   
   
    function Cycle (action:Function, interval:Number = 0, begin:Boolean = true);       
   
    action: Function - the function that will be called each cycle
    interval: Number - the delay in milliseconds (if using the Timer class) (if this is
omitted the cycle defaults to frame-based) (defaults to 0)
    begin: Boolean - whether cycle should start immediately on init (defaults to true)
   
    -------------------------------------
    CREDITS:
    -------------------------------------
    Cycle Class by Ash Warren ([url]www.losthumans.com[/url])

*/
package
{
    import flash.utils.*;
    import flash.events.*;
    import flash.display.*;
   
    public class Cycle
    {
        private var _sprite:Sprite;
        private var _time:Timer;
        private var _action:Function;
        private var _isTimer:Boolean;
           
        public function Cycle (action:Function, interval:Number = 0, begin:Boolean = true)
        {
            _action = action;
           
            if (interval)
            {
                _time = new Timer (interval);
               
                _isTimer = true;
            }
            else
            {
                _sprite = new Sprite ();
               
                _isTimer = false;
            }
           
            if (begin)
            {
                start ();
            }
        }
       
        public function start ():void
        {
            if (_isTimer)
            {
                _time.addEventListener (TimerEvent.TIMER, cycleTimer);
                _time.start ();    
            }
            else
            {
                _sprite.addEventListener (Event.ENTER_FRAME, cycleFrame);            
            }
        }
       
        public function stop ():void
        {
            if (_isTimer)
            {
                _time.stop ();
                _time.removeEventListener (TimerEvent.TIMER, cycleTimer);
            }
            else
            {
                _sprite.removeEventListener (Event.ENTER_FRAME, cycleFrame);               
            }
        }
 
        private function cycleTimer (event:TimerEvent):void
        {
            _action ();
        }      
 
        private function cycleFrame (event:Event):void
        {
            _action ();
        }
    }
}



ActionScript Code:
/*
    -------------------------------------
    DESCRIPTION:
    -------------------------------------
   
    CycleManager Class that can control all aspects of a stack of Cycles for a Flash movie
   
    -------------------------------------
    USAGE:
    -------------------------------------   
   
    function add (action:Function, interval:Number = 0, begin:Boolean = true);   
   
    action: Function - the function that will be called each cycle
    interval: Number - the delay in milliseconds (if using the Timer class) (if this
is omitted the cycle defaults to frame-based) (defaults to 0)
    begin: Boolean - whether cycle should start immediately on init (defaults to true)
   
    returns: Number - the index of the added Cycle
   
    function remove (index:Number = -1);       
   
    index: Number - if left as default the manager will remove the last cycle added,
else it will remove the cycle at listed index value
   
    function start/stop (index:Number = -1);       
   
    index: Number - if left as default the manager will start/stop the last cycle added,
else it will start/stop the cycle at listed index value
   
    -------------------------------------
    CREDITS:
    -------------------------------------
    CycleManager Class by Ash Warren ([url]www.losthumans.com[/url])

*/
package
{
    import Cycle;
   
    public class CycleManager
    {
        private var _cycles:Array;
       
        public function CycleManager ()
        {
            _cycles = new Array ();
        }
       
        public function add (action:Function, interval:Number = 0, begin:Boolean = true):Number
        {
            return _cycles.push (new Cycle (action, interval, begin)) - 1;
        }
       
        public function remove (index:Number = -1):void
        {
            if (index >= _cycles.length || index < -1 || index == undefined)
            {
                return;
            }
            else if (index == -1)
            {
                var _c:Cycle = _cycles.pop ();
                _c.stop ();
                delete _c;
            }
            else
            {
                var _ca:Array = _cycles.splice(index, 1);
                _ca[0].stop ();
                delete _ca;
            }
        }
       
        public function start (index:Number = -1):void
        {
            if (index >= _cycles.length || index < -1 || index == undefined)
            {
                return;
            }
            else if (index == -1)
            {
                _cycles[_cycles.length - 1].start ();
            }
            else
            {
                _cycles[index].start ();
            }
        }
       
        public function stop (index:Number = -1):void
        {
            if (index >= _cycles.length || index < -1 || index == undefined)
            {
                return;
            }
            else if (index == -1)
            {
                _cycles[_cycles.length - 1].stop ();
            }
            else
            {
                _cycles[index].stop ();
            }
        }
       
        public function startAll ():void
        {
            for (var i:int = 0; i < _cycles.length; i++)
            {
                _cycles[i].start ();
            }
        }
       
        public function stopAll ():void
        {
            for (var i:int = 0; i < _cycles.length; i++)
            {
                _cycles[i].stop ();
            }
        }
       
        public function reset ():void
        {
            var _l:Number = _cycles.length;
           
            for (var i:int = 0; i < _l; i++)
            {
                var _c:Cycle = _cycles.pop ();
                _c.stop ();
                delete _c;
            }
        }
    }
}



ActionScript Code:
/*
    -------------------------------------
    USAGE EXAMPLE: CycleManager Class
    -------------------------------------
*/
package
{
    import flash.display.*;
    import CycleManager;
   
    public class Main extends Sprite
    {
        private var _test:CycleManager;
        private var _index:Number;
           
        public function Main ()
        {
            _test = new CycleManager ();
            _index = _test.add (test, 50);
        }
       
        public function test ():void
        {
            trace ("cycle loop");
           
            _test.stopAll ();
        }
    }
}

View Replies !    View Related
Create Child Class From Sound Class?
Hi everybody,
I have just started Flash and it seems I have stepped into the first Problem:
Creating child classes from a user-defined class works fine, but when I try to make one from "Sound"-class, nothing happens.

A simplified example, doesn't actually do much:

function MySoundClass() {
}

MySoundClass.prototype = new Sound();

mySound = new MySoundClass();
mySound.attachSound("music01");

mySound.start(0,0);

The result? No sound at all! :-(
Can anyone help?

Henning

View Replies !    View Related
How To Run A Function Within A Class From OnSoundComplete Located In The Same Class
Hi,

I have a class called CSound.
I´m trying to let soundobject.onSoundComplete = function () within this class call another function within the same class but I don't know how. Any one who knows how to manage this.

Below you see the CSound class

function CSound ()
{
// a variable holding the sound
var m_sndSound = new Sound (_root);
// function to start the sound
this.PlaySound = function (strSound)
{
trace("Running the PlaySound Function ");
m_sndSound.attachSound (strSound);
m_sndSound.start ();
};
// checks if sound has finished playing
m_sndSound.onSoundComplete = function ()
{
trace ("SoundFinished");
// How can I call the PlaySound function within here ?????
// This does not work...
this.PlaySound ("sound");
};
}

View Replies !    View Related
Class's Movieclip Calling A Function In It's Own Class
For the life of me I can't find an internet source that explains why this doesn't work. I know it's a scope problem but I know no other way around it and there must be a way to do it, I'm thinking.

I have a class. Inside this class I create a movieclip which I have a class variable link to. The movieclip is created on _root. When I click on this movieclip, I want it to call a function inside the class. Here's what it looks like.


Code:
class Whatever extends Movieclip {
private var mc:MovieClip;

public function Whatever() {
this.mc = _root.createEmptyMovieClip("rootmc",_root.getNextHighestDepth());
[code for drawing a square]
this.mc.onPress = this.doSomething();
}

public function doSomething {
[do something]
}
In the above sample, when I click on the movieclip, the "doSomething" function is not called, obviously because the movieclip is on root and has nothing to do with the class. Is there a way to do what I want to do?

View Replies !    View Related
Button Class Affect The Document Class
I want it so when you click the button, it can make the movie go to the next scene or change a variable in the document class. I can do it on the timeline but I want it as a class instead

And it would be cool if I could figure out how to make seperate packages just for functions and variables so I didn't have to write it all in one document, I just don't want to code in a big pile after I heard you can do this


Cheers

View Replies !    View Related
Call Class Getter & Setter From Another Class
I have 2 classes (triangle.as and circle.as) each of the classes draws a shape and another shape inside a movieclip which acts as a button.
Then from the document root (main.as) I create an instance of the triangle.as (tri) and the circle.as (cir) and add them to the displaylist.
when run displays a triangle + button and a circle + button on the stage.

The triangle class has getter and setter functions which are getValue & setValue.

when I call these getter and setter functions from main.as

tri.setValue = 100;
trace(tri.getValue);

everything works fine, but then when I try

tri.setValue = 100;
trace(tri.getValue);

from within the circle class the error says it doesn't recognize 'tri' which I can understand as it is referencing another class outside of the current class it is called in.

I did try....

parent.tri.setValue = 100;
trace(parent.tri.getValue);

but made no difference.

So the problem is how to reference a classes getter & setter functions from within another class.

Any help would be much appreciated. Thanks

View Replies !    View Related
Bouncing Ball Class Off Other Class Objects
Hello again people. Im getting far now with this AS3 learning and classes in general. Now im wondering how I will get my ball which is in a class and is called to the stage to bounce off my bats which are in other classes and are called to the stage. Heres my code all help would be great thanks in advance

Heres my Main.as class file which calls the classes onto the stage and moves m bats


Code:
package classes{

import flash.display.Sprite;
import flash.display.Stage;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;

import classes.nets.Nets;
import classes.bats.Leftbat;
import classes.bats.Rightbat;
import classes.ball.Ball;

public class Main extends Sprite{

// Variables
public var nets:Sprite;
public var myleftbat:Sprite;
public var myrightbat:Sprite;
public var myball:Sprite;

public function Main(){
nets = new Nets();
myleftbat = new Leftbat();
myrightbat = new Rightbat();
myball = new Ball();
//
addChild(nets);
addChild(myleftbat);
addChild(myrightbat);
addChild(myball);

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressedDown);

}

private function keyPressedDown(event:KeyboardEvent):void {
var key:uint = event.keyCode;
var step:uint = 5
switch (key) {
case Keyboard.UP :
myleftbat.y -= step;
if (myleftbat.y <-250) {
myleftbat.y =-250;
}
break;
case Keyboard.DOWN :
myleftbat.y += step;
if (myleftbat.y > 249) {
myleftbat.y = 249;
}
break;
case Keyboard.NUMPAD_8:
myrightbat.y -= step;
if (myrightbat.y <-250) {
myrightbat.y =-250;
}
break;
case Keyboard.NUMPAD_2:
myrightbat.y += step;
if (myrightbat.y > 249) {
myrightbat.y = 249;
}
break;
}
}

}
}
And here are my bat classes, these just draw the bats

The left bat

Code:
package classes.bats{

import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.events.*;

public class Leftbat extends Sprite {

public function Leftbat():void {
graphics.lineStyle(1);
graphics.beginFill(0x2f9b4b);
graphics.drawRect(0,250,25,100);
graphics.endFill();
}
}
}
The right bat

Code:
package classes.bats{

import flash.display.Sprite;

public class Rightbat extends Sprite{

public function Rightbat(){
graphics.lineStyle(1);
graphics.beginFill(0x2a00ff);
graphics.drawRect(774,250,25,100);
graphics.endFill();

}
}
}
And Finally my ball class, this creates the ball and makes it move around the stage


Code:
package classes.ball{

import flash.display.Sprite;
import flash.utils.Timer;
import flash.events.TimerEvent;

public class Ball extends Sprite

{

private var myBall:BallClip;

public function Ball( )
{
myBall = new BallClip( );
addChild( myBall );

var moveTimer:Timer = new Timer( 25 );
moveTimer.addEventListener( TimerEvent.TIMER , myBall.step );
moveTimer.start( );
}
}
}

import flash.display.Sprite;
import flash.events.TimerEvent;

class BallClip extends Sprite
{

private var xspeed:Number;
private var yspeed:Number;

public function BallClip ( )

{

graphics.lineStyle(1);
graphics.beginFill( 0xffffff , 1 );
graphics.drawCircle( 20 , 20 , 15 );
graphics.endFill( );

x = 400;
y = 300;

xspeed = Math.random( )*5;
yspeed = Math.random( )*3;

}

public function step ( timeEvent:TimerEvent ):void
{

if ( x + xspeed > 850 ) xspeed *= -1;
if ( x + xspeed < -50 ) xspeed *= -1;
if ( y + yspeed > 570 ) yspeed *= -1;
if ( y + yspeed < 0 ) yspeed *= -1;

x += xspeed;
y += yspeed;

}
}
Now I know it will involve checking the balls x posistion and then bouncing it back if it meets the bats x posistion, but how do I do this? Can I check classes within classes?

View Replies !    View Related
Can I Get The MouseX From One Class's Stage From Inside A Different Class?
I'm working on a first time game using Flash CS3 ActionsScript 3.0 that has a crow class placed on the stage of a main gameStage class. I need to access the mouseX coordinate from the stage of the gameStage class from inside my crow class. I'm attempting to do it via a getter function but seem to be having trouble tracking down the exact proper syntax to avoid errors. Is there any chance I could get an exact syntax example as apposed to hours of online research and study.................8-)

View Replies !    View Related
When Should I Use Document Class And External Class Files?
Hello all,

I was recently sent on an intensive three day Actionscript 3 course by my employers - it was fantastic and gave me a great understanding of the fundamentals of coding with Actionscript.

I have one question that I wasn't really able to raise during training, the topic was touched on briefly but wasn't explained in any detail.

When should I use document class files and external class files? If I understand it correctly, creating Linkage with an element in my library then creates a class file, and that file should contain specific functionality relating to the element. For instance, if it was a movie clip in my library that is used to contain loaded product images, then the associated external class file should contain the code that handles the URLRequest and the Loader, plus any extra functionality such as Event Listeners and a function for dragging and dropping of the MC. When I want to access that functionality, I call the function in my class file from my main movie and pass it the correct parameters. Am I on the right track here?

When should I use the document class? I know how to set a document class, and going by my previous logic, I imagine it's used to contain global functions that may be required (such as exiting the movie, file handling etc). Am I correct?

One more - say I'm using an external class file - do I need to import it on the first frame of the actions layer, or can I import in my document class?

That's it, a little clarification need really.
Thanks in advance.

View Replies !    View Related
Problems With Document Class Interacting With Another Class
Here is my problem:

I need to have a menu on the bottom of the screen to have mouse overs / on / off states. When the user mouses over a button I need to have the slide name change in the text field on the Stage, when they mouse off, the Slide name of the button with the on state should be displayed. When the click on it, a slide should load.

I have a Movie Clip with a linkage ID: Nav Button in the library that has timeline animations with labels: over, on, off, and passed and onBut that makes the button change states.

I have a Document Class(Presentation.as) that creates instances of the external class NavButton class (NavButton.as) with the values it received from XML.

When user mouse overs a button I need a text in the textField that is created from the Document class to change value. but I can't access that text field from the NavButton class.
code from Document Class: Presentation.as

public var pageTitle:TextField = new TextField();
pageTitle.x = 500;
pageTitle.y = 500;
if (sStatus == "on"){
pageTitle.text = sTitle; // works! sTitle comes from XML
}
addChild(pageTitle);

code from NavButton.as

public function onButtonOver(e:MouseEvent):void
{
e.currentTarget.gotoAndPlay("over");
////NOT WORKING, need to assign this text value to the text field on stage!
stage.pageTitle.text = this._btnTitle;

}

public function onButtonClick(e:MouseEvent):void
{
e.currentTarget.gotoAndPlay("on");
////NOT WORKING, need to call this function in document class
createSlide();

}
Also, once the user click on the button I need another slide to load so I need to call a function in the document class to start loading that data from XML.

So I am having few problems, for about 5 days already. Let's say my hair is in place but I really really want to know how to do it.

1). How to assign values from the mouseover function of the NavButton class, to the textField that was created in the Document class? So that it changes when u mouse over and goes back to the default value when it's off.

2). How to call a function in the Document class from the mouseClick function of the NavButton class, to start building out the rest of the info.


I tried having a textField placed manually on stage with a different name, but still I can't access it from the NavButton class!

My code is attached.

Thank you very much for your help!
-D.

View Replies !    View Related
Call Class Method Inside Another Class.
Hello, I have one class that creates another object from another custom class. Then it calls a method from the newly created class. I want this class to then call a parent's method after it's completed.

Something like this:

PHP Code:



//First Class
class FirstClass{
    function FirstClass(){
        var newClass:SecondClass = new SecondClass();
        newClass.doSometing();
    }
    public function doSomethingAfter():Void{
        // Do this after newClass.doSomethign is done
    }
}

// Second Class
class SecondClass{
    private var _mc:MovieClip;
    private var _incrVar:Number;
    function SecondClass(){
        _mc = _root.createEmptyMovieClip(...);
        _incVar = 0;
    }
    public function doSomthing():Void{
        _mc.onEnterFrame = function():Void{
            _incVar++;
            if(_incVar > 10){
                delete this.onEnterFrame;
                // This is where I would now like to call
                // a method of First Class.. but How?
            }
        }
    }





I know that I could pass the FirstClass object as a parameter to the SecondClass's doSomething function.. but I was wondering if there was another easier way I do not know about to call the parent or calling classes methods. Or maybe there is a way for FirstClass to detect when SecondClass is finished with what it must do before moving on without having to have SecondClass call a FirstClass method?

Thanks!

View Replies !    View Related
Function Not Being Called In A Class Yet Works Outside Of Class
i have a function to test for ints placed on the main timeline...

function isInt(num){
trace('Function called(not in a class though)!');
return num == int(num);
}
isInt(20);
calls the function and returns like i would expect 'Function called(not in a class though)!'


Yet if i move this function into a class and call it from within the class's other method getEmpInfo(), it doesnt work...

class Employee
{
var empID;
var empName;
var ProStaff;

...

function isInt(num) {
trace('Function called(from class)!');
return (num==int(num));
}

function getEmpInfo()
{
var EmployeeID = 20;
trace( this.isInt(EmployeeID) + ', EmployeeID='+EmployeeID); //returns "undefined , 20"
this.isInt(EmployeeID); //never returns a value and doesnt output 'Function called(from class)!' like i would expect it to; almost as if it doesnt know that isInt is part of my class?
}

}

View Replies !    View Related
Copyright © 2005-08 www.BigResource.com, All rights reserved