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




Scope In Tween Class



Hello all!

Can any one tell me why cant i control objects inside MovieClip play by tween class.

Thanks.



ActionScript.org Forums > ActionScript Forums Group > ActionScript 1.0 (and below)
Posted on: 06-13-2007, 11:10 AM


View Complete Forum Thread with Replies

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

Using Tween Class Changes Scope?
i have a custom class which implements the tween class. I'm just shrinking and enlarging a box.

when I just set the variables:
box_mc._width = boxOrigW;
box_mc._height = boxOrigH;

it changes the box to the correct size
but when i apply the same variables in the folling tween code, the size change is totally wrong

var boxSizerW:Object = new Tween(box_mc,"_xscale",mx.transitions.easing.None. easeNone,boxSmallW,boxOrigW,3,true);

var boxSizerH:Object = new Tween(box_mc,"_yscale",mx.transitions.easing.None. easeNone,boxSmallH,boxOrigH,3,true);

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!

Tween Scope
I'm using tween animations imported in.

Most of my code is on my root, however there is a MC which gets dupilcated and loads in seperate xml data

atm I'm just using one alpha tween in the mc, but so far I seem to lose scope unless I load the tween class in to the MC, which is daft, seeming it gets duplicated.

.....

the MC in question, loads in XML and displays a thumbnail gallery, the tween is onLoadComplete function and alphas the file in.

var myAlpha:Tween = new Tween (targetMC,"_alpha",Strong.easeOut,0,100,3,true);

is there a simple way of just referring to the imported tween on the root

or would I have to call a function on the root, referring to targetMC?


....

thanks

Tween Class If Moved Mc Passed Point Start Another Tween
Hey Actionscript Gurus

Now I am using the Tween Class to move some boxes in my movie, now I can move the first mc and then another mc after the first tween has finished with onMotionFinished but I was hoping someone could help with how do I start the second tween when the first mc has passed a certain _x coordinate.

ie starting the second mc moving while the first tween is still moving.

I am trying to do a intro loader for my front page controlling around 7 boxes. So I need to repeat this a few times.

Regs,
Jacko

Tween Class If Moved Mc Passed Point Start Another Tween
Hey Kirupa Flash Gurus

Now I am using the Tween Class to move some boxes in my movie, now I can move the first mc and then another mc after the first tween has finished with onMotionFinished but I was hoping someone could help with how do I start the second tween when the first mc has passed a certain _x coordinate.

ie starting the second mc moving while the first tween is still moving.

Regs,
Jacko

Scope Trouble... Unregister/ Remove Object / Tween ?
Hi,

I hope somebody can help with the following problem.
I'm trying to make a powerpoint kind of projector:
- Main flash movie: works as a container to load different flash files.
reacts on the left and right arrow buttons to go to the next or previous movie, which is loaded in a movieClip.

- Several external swf files all exported from the same: slide.fla only adjusting xml node settings make the differences in text and pictures.
This works, but after loading into the container I use to show the images the tween of my images gets messed up. (Not in the first loaded movie, but sure after around the third)

Please can anybody look at my code and tell me what could be the problem?
I'm sure it has to do with the scope after loading into the container.fla, and all the objects having the same name, for the submovies. (exported from the same .fla)
Do I have to unregister/ remove these objects after usage - I think this might be it, but don't know how.

In the container.fla I already set:
clipLoader_mc._lockroot = true;
but this doesn't solve the problem.


Code:
/// **************************** ///
/// START TWEEN METHODS FOR SCREENS ///
/// **************************** ///
var mcl_obj:Object = new Object();
mcl_obj.onLoadInit = function(target_mc:MovieClip):Void {
target_mc._width = 500;
target_mc._height = 395;
target_mc._x = 500;
var distance:Number = 5;
var angleInDegrees:Number = 45;
var color:Number = 0x000000;
var alpha:Number = 75;
var blurX:Number = 7;
var blurY:Number = 7;
var strength:Number = 1;
var quality:Number = 3;
var inner:Boolean = false;
var knockout:Boolean = false;
var hideObject:Boolean = false;
var filter:DropShadowFilter = new DropShadowFilter(distance, angleInDegrees, color, alpha, blurX, blurY, strength, quality, inner, knockout, hideObject);
var filterArray:Array = new Array();
filterArray.push(filter);
target_mc.filters = filterArray;
var tween_target:Object = new Tween(target_mc, "_y", Back.easeInOut, Stage.height, 300, 1, true);
tween_target.onMotionFinished = function() {
intervalClearScreenId = setInterval(ClearScreen, 8000, counter);
};
screenCounter++;
//initiated on top of the page.
};
function ClearScreen():Void {
var tween_screen:Object = new Tween(mover_mc, "_x", Strong.easeInOut, mover_mc._x, 1250, 1, true);
tween_screen.onMotionFinished = function() {
if (screenCounter<screenMaxCount) {
ShowScreens();
} else {
screenCounter = 0;
ShowScreens();
}
clearInterval(intervalClearScreenId);
};
}
ShowScreens = function ():Void {
// Create a movie clip instance.
this.createEmptyMovieClip("mover_mc", getNextHighestDepth());
var img_mcl:MovieClipLoader = new MovieClipLoader();
img_mcl.addListener(mcl_obj);
// Load an image into the movie clip
img_mcl.loadClip(imageArray[screenCounter], mover_mc);
};
//load XML voor screens on the left:
function loadScreensXML(loaded) {
if (loaded) {
_rootNode = this.firstChild.childNodes[imageNodeNr].childNodes[0];
trace(_rootNode);
total = _rootNode.childNodes.length;
for (i=0; i<total; i++) {
//add images to imageArray:
imageArray[i] = _rootNode.childNodes[i].firstChild.nodeValue;
}
screenMaxCount = imageArray.length;
//initiated on top of the page
//Show the screens:
ShowScreens();
} else {
content = "file not loaded!";
}
}
xmlScreens = new XML();
xmlScreens.ignoreWhite = true;
xmlScreens.onLoad = loadScreensXML;
xmlScreens.load(urlImagesXML);
/// **************************** ///
/// END TWEEN METHODS FOR SCREENS ///
/// **************************** ///
I'm trying all day already to solve this so please can anybody help?
Thanks in advance!

Tween Class Scaling Breaks Motion Tween?
I have a movie clip which uses a motion guide to animate the entry (and eventually the exit) of a bunch of other movie clips. These smaller clips contain buttons, and animate on rollOver and rollOut using the following code:


Code:
on(rollOver) {
this.swapDepths(2);
ParentxScale = new mx.transitions.Tween(this, "_xscale", mx.transitions.easing.Back.easeOut, this._xscale, 100/.6, .5, true);
ParentyScale = new mx.transitions.Tween(this, "_yscale", mx.transitions.easing.Back.easeOut, this._yscale, 100/.6, .5, true);
play();
}
on(rollOut) {
ParentxScale = new mx.transitions.Tween(this, "_xscale", mx.transitions.easing.Bounce.easeOut, this._xscale, 100, .5, true);
ParentyScale = new mx.transitions.Tween(this, "_yscale", mx.transitions.easing.Bounce.easeOut, this._yscale, 100, .5, true);
stop();
}
However, once an object has been moused over, it doesn't exit with the others. Any ideas why it seems to "fall off the track" of the motion guide?

XML Scope When Used In A Class
I'm building a event calendar, re-building in 2.0 actually. The first thing the constructor does is load an XML file. Then onLoad I fire off 3 functions. For some reason, nothing happens with an unqualified reference and I don't know what the scope of the function is.
This does not work.
code:
tempXML.onLoad = function(success){
trace("XML loaded!");
buildCalendar();
setDates();
leapYearCheck();
}


I don't understand why these both kinda work
code:
tempXML.onLoad = buildCalendar();//runs a trace and attachMovie within buildCalendar works


code:
tempXML.onLoad = buildCalendar;//runs a trace but attachMovie does not work

Class And Scope
G r e e t i n g s ~

If I use something like this in a seperate class.as file ...

//imagine a for loop here ...
this.attachMovie("d", "c"+i, depth);
this["c"+i]._x = xVar;
this["c"+i]._y = yVar;

I get nada in the movie. but ...

If I use the exact code on the timeline it works great. It seems I'm missing the point when using a seperate class file. On the timeline I'm declaring ...

import MyClass
myClass = new MyClass();



what do I need to do to get this to work from the class I'm bringing in ?

Scope In Class
if there is a way to reach to fRes function from fRelease() --> onRelease i need to know it.need any help.thanks.



private function fRelease() {
for (i=0; i<4; i++) {
eval("btn_"+i).onRelease = function() {
// it traces
// the go to fRes function
fRes();
};
}
}


private function fRes() {
// never came here
trace("damn");
}

Scope Within Class
I'm trying to do something I feel is pretty straight forward, but I keep running into problems.

I have a bunch of swfs that operate basically the same. They all have a row of buttons and depending on the button pressed an associated MC is displayed and the visibility of all the other MCs is set to false. I didn't want to build a component for this because each swf has a completely different look and style to it.

I figured it would be easy to create a TabSet class with a method where I pass in an array of references to all the buttons, and a similar array with references to all the MCs. That method would then set the onRelease event of each button to set the visibility of its associated MC to true and all others to false. Unfortunately when trying to set the onRelease even within a function in the class I keep running into errors dealing with scope because inside the event it can't access the original arrays that were passed in. I've tried using the Delegate.create method, but it seems to have the same limitations. I've included code below to show what I mean.


ActionScript Code:
import mx.utils.Delegate;
import mx.events.EventDispatcher;

class dhti.sc.TabSet{
   
        //Private Vars
    private var _btnArr:Array;
    private var _contentArr:Array;
   
        //Constructor
    function TabSet(){
        _btnArr         = new Array();
        _contentArr     = new Array();
    }
   
        //Setting the Tab Set
    function setTabSet(btnArr:Array, contentArr:Array):Void{
        _btnArr     = btnArr;
        _contentArr = contentArr;

        var i:Number = 0;

        for(i=0;i<_btnArr.length;i++){
           
            //Below are 3 ways of setting up the onRelease event
            //but none of them allow me to do what I need
           
                //Trying with a nested function
            _btnArr[i].onRelease = function(){
                //This will trigger the onRelease Event
                //but from in here you cannot access
                //_btnArr or _contentArr
            }
           
                //Trying Delegate setting the Scope to the Class
            _btnArr[i].onRelease = mx.utils.Delegate.create(this, buttonClicked);
               
                //Trying Delegate setting the Scope to the Button
            _btnArr[i].onRelease = mx.utils.Delegate.create(_btnArr[i], buttonClicked2);
        }
    }
   
   
    private function buttonClicked(){
        //This function is triggered with the button click
        //and it has access to _btnArr and _contentArr, but I
        //cannot determine which button was clicked
        //since "this" refers to the class
    }
   
    private function buttonClicked2(){
        //This function is triggered with the button click
        //but no access to _btnArr and _contentArr, but I
        //can determine which button was clicked
        //since "this" refers to the button itself
    }
}

Class Scope (again)
i thought i had this subject nailed and decided to re-write my code based on this new knowledge but for the life of me i cant see why this is not working.

i know it is a scope problem but i cant see it. The function loadXML does not work unless it is a static. I can't see why it needs to be static. myXML is declared ok, myXML is within the checkEntry function as is the onLoad etc. there is nothing wrong with the Delegate function - its SCOPE but i cant see the sucker - please put me out of my misery - i have looked at this for too long and put together so many different ways (which all work) but this just doesnt. thank you



PHP Code:



import mx.utils.Delegate
class XmlComponent
{
    var previousText:String;
    var keyListener:Object
    private var myXML:XML;
    static var controller;
    
    public function XmlComponent()
    {
        keyListener = new Object();
        controller = this;
        previousText = "";
        checkEntry();
    }
        
    private function checkEntry()
    {
        keyListener.onKeyDown = function(){    
            if((Selection.getFocus() == "_level0.controller.xmlInput_txt") and (Key.isDown(Key.ENTER)))
        {
            if(previousText != controller.xmlInput_txt.text)
            {
                myXML = new XML;
                myXML.ignoreWhite = true;
                myXML.onLoad = Delegate.create(controller,loadXML)
                myXML.load(controller.xmlInput_txt.text);
            }
            previousText = controller.xmlInput_txt.text;

        }
    }
            Key.addListener(keyListener);
    
    }
    
    //static function loadXML(success:Boolean):Void{
    function loadXML(success:Boolean):Void{
        if(success){
        trace("loadxml " + controller);
        }
    }
    
    public function tr() {
        trace(arguments.join(" : "));
    }
    
    


Class Scope
I just cant understand how can we retrieve the private variables of a class through other class. To explain in detail i ve 2 class files Person and Person2. Here is the code inside them.

Person.as class file

class Person {
private var fn:String;
private var ln:String;
function Person() {
fn = "myFirstName";
ln = "myLastName";
}
}



Person2.as class file

class Person2 {
private var root:MovieClip;
function Person2(mov) {
root = mov;
trace(root.pObj.fn);
}
}


The fla file that calls the class has this code on its first frame:

var pObj:Person=new Person()
trace(pObj.fn)
var p2:Person2=new Person2(this) //myFirstName


My question is how Person2 class can access Person class private variable.

Tween Class: Can One Tween More Than One Property Using The Same Tween
I want to scale both the _xscale and the _yscale properties of a clip, using a single execution of the Tween Class. See example below:


Code:
import mx.transitions.Tween;
var myTween:Tween = new Tween(myMovieClip_mc, "_xscale", Strong.easeOut, myMovieClip_mc._xscale, 300, 5, false);

Since one property at a time must be passed as a string to the constructor, I tried the following code, but it does not work quite as flawless as I expected:


Code:
myTween.onMotionChanged = function() {
//trace( this.position );
myMovieClip_mc._yscale += (300 - myMovieClip_mc._yscale)/12;
};
Any suggestions?

Custom Class Scope?
I created a custom class on the root of _level0.

Code:
FXML = function ()
{
...
}

FXML.prototype.getValue = function (xPath)
{
...
}
I want the scope of my class to be in all the movieclip.
I don't want to have to this:


Code:
var myfxml = new _level0.FXML()
How can my custom class have a global scope like others Flash objects?

Variable Scope In Class (AS 2.0)
I have a movie clip attached at runtime. I have a class linked to the movie clip. The movie clip is attached at root. All this works but check out how I am accessing the variables in the functions (ie: _parent.alphaon and _parent.alphaoff) Surely there must be a better way. Thanks for your comments.


Code:
//Constructor Function
function Screen() {
id = id;
path = _root["Screen"+id];
alphaon = 80;
alphaoff = 100;
setupdrag();
}

//Set Up Drag
function setupdrag() {

path.dragger.onPress = function() {
_parent.startDrag();
_parent._alpha = _parent.alphaon;
_parent.swapDepths(myDepth);
}

path.dragger.onRelease = function() {
stopDrag();
_parent._alpha = _parent.alphaoff;
}
}
}

AS 2.0 // Interval Scope In A Class
i have a function that i assign to an interval, after an amount of time it is to stop. problem is that interval is not able clear itself or access any properties in the class.

in the debug window it shows the function in the root of the class as i would expect but this. and _parent. have no effect.

class alpha
{
var myInterval;
var myNumber:Number

function myFunction()
{
trace(myNumber) // undefined
if(myNumber==20)
{
clearInterval(myInterval) // doesn't clear;
myNumber=0;
}else{
myNumber++;
}

function alpha()
{
myNumber=0
myInterval=setInterval(myFunction, 5000)
}

Math Class....available Everywhere? (scope)
I want to create a Class containing functions (similar to the Math class).
Also, like the Math class, I want it to be available everywhere.

For example, if I type
Code:
Math.floor(myNumber);
It works, no matter where I am in my code.

How can I make a class which has this ability?
I want to be able to type
Code:
MyMathClass.functionName();
and have it work, wherever I am in my code.

Is that possible??

Please help!
Cheers,
David

Help Xml Class Scope Issue
I am having a xml problem that is driving me crazy! I wrapped the the general methods for processing xml in a new class and the function that that is referenced by the onLoad handler loses the reference to the xml obj so I can't work with the xml obj. I did this so I can easily reuse this functionality.

In as the general method to process xml is create a new xml obj instance, set the onLoad to a function that will process the xml doc and set up all the business methods and then load an xml file into the xml obj. I wrapped these into a class for an app I'm working on.

The constuctor for the class sets my classes xmlObj instance variable to a new XML() obj. The loadXML(xmlfile) method sets up some variables and loads the file. The processXML() file is the method that is reference by the xml obj onLoad handler. But by the time the control enters this function the reference to my xmlObj is lost. It passes the if (success) confition meaning that the file was loaded successfully, but for some reason the my instances variable holding the xmlObj data is no longer an instance of XML type and is undefined.

PLEASE can somebody think about what might be causing this?

Variable Scope In Class
Hello,
I'm just getting started with OOP and writing classes. I've come across a problem. where Variables declared in the class are lost somewhere in the scope of things...

The static var X is'nt available to the method onBtn().. why? I'm probably missing something simple...


ActionScript Code:
class TestVars
{
    // reference to timeline
    var root:MovieClip; 
    // VARS
    var a:Number = 0;
    static var X:Number = 5;

    //constructor
    function TestVars(root:MovieClip)
    {
        this.root = root;
        init();
    }   
    // set up
    function init()
    {
        //  SET UP BUTTON 
        root.btnNext.scope = this;
        root.btnNext.onRelease = function()
        {
            this.scope.onBtn();
        }
       
        // START UP
        setVar(a);
    }
    //Set new variable 
    function setVar(t:Number)
    {
        a = t;
        trace('a: '+ a +' :'+ typeof(a))
    }   
           
       
    function onBtn()
    {
        trace('onBtn called: '+a+' + '+X+' = '+a+X) // TRACES: 0 + undefined = 0undefined   
        setVar(a + X);
    }
}

any help apreciated.
thanks

.henkedo

Scope In A Class Question
Hello, i'm new to OOP programming, and having trouble with scope within a class.

This class tweens an object, and at the end of the tween, i'm trying to use onMotionFinished to call another function in the class...

Can anyone tell me why it isn't working, and how it can?

Thank you

Mikey99

here's the code...
it works by passing the target movie clip to be tweened as the first parameter, then the speed of the tween.


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

class TweenTest {
private var _endTween:Tween;
private var False:Boolean;


public function TweenTest() {}

public function startTween(target:MovieClip, speed:Number):Void {
new Tween(target, "_alpha", Regular.easeIn, 100, 0, speed, False);
new Tween(target, "_xscale", Regular.easeIn, 100, 60, speed, False);
new Tween(target, "_yscale", Regular.easeIn, 100, 60, speed, False);
_endTween = new Tween(target, "_rotation", Regular.easeIn, 0, Math.floor(Math.random()* 360 - 180), speed, False);


_endTween.onMotionFinished = function() {
trace("Has testFunction been called?");
testFunction();
}

}

private function testFunction():Void {
trace("Yes.. it has!");
}
}

Class Variable Scope
I am trying to call an object's method in an event handler. It seems that the object was never defined.


Code:
// Main.as

class Main
{
var mc:MovieClip = null;
var b:Body = null;

static function main()
{
trace("main");

var m = new Main();
}

function Main()
{
trace("Main::Main");

this.mc = _root.createEmptyMovieClip("z00", 1);
this.b = new Body();

this.mc.onEnterFrame = this.onFrame;
}

function onFrame()
{
trace("Main::onFrame");
trace(this.b);
}
}

Code:
// Body.as

class Body
{
function Body()
{
trace("Body::Body");
}

function draw(mc:MovieClip)
{
trace("Body::draw");
}
}

Code:
// Output
main
Main::Main
Body::Body
Main::onFrame
undefined
Main::onFrame
undefined
Main::onFrame
undefined
...
Strangely, if I trace(this.mc) in Main::onFrame it is undefined also. The object that is generating the event is undefined?! I am going mad. Someone please help!

Scope Issue With Class
Hi,
It's been a while since I've posted, so hello everyone.

I've FINALLY got round to learing classes. Gawd knows how I've managed this far; I guess I like my functions laid out on the timeline too much!

Anyway... I've written a basic box class, then extended it a couple of times, making it more specialized each time.


Code:
Box // creates a movieclip, draws a box, sets it's color (optional)
DraggableBox // adds draggability
Draggable Square // makes sure the box is square, also adds color change on rollover
The last specialization is where I'm falling down with a scope issue. What I'm trying to do within an onRollOver handler is change the color of teh movieclip using my Box's setColor method.

However, the scope of the function now appears to be the movieclip, and I can't seemto reference the class anymore. I attempted to set an instance variable 'thisBox' in the head of the class that refers to the class instance, but I'm having no luck.

Bottom line is I can't seem to reference the class - so how do I do this?

Code snippet included below, and zip file attached. It's really very basic stuff, so thanks for your help if you choose to get involved.

Cheers,
Dave


Code:
class DraggableSquare extends DraggableBox {

private var thisBox:Box

function DraggableSquare(w:Number, h:Number, parent:MovieClip){
super(w,w,parent)

thisBox = this
trace('thisBox:' +thisBox)

setColor(0x999999) // SUCCESSFUL call to Box.setColor method
setDrag()
}

function setDrag(){

mc.onRollOver = function(){
trace('thisBox:' +thisBox)
thisBox.setColor(0xFF0000) // FAILED call to Box.setColor method
}

mc.onRollOut = function(){
thisBox.setColor(0x999999)
}

}

}

Scope Issue With Class Help
here's my code for my class...

it's used to make it easy to program keys to press in a game. and makes for smooth gameplay. Before this, i simply copy/pasted this code, and it has worked for awhile, but I want to make it a class to make my coding more organized.

anyway, here's the code...


Code:
class GamePlayControl extends Key
{
private var p_keyValues:Array;
private var p_externalFunction:Function;
private var p_updateRate:Number;

private var p_keysDownInterval:Number;
private var p_keysAreDown:Boolean;

private var p_keyListen:Object;

public function GamePlayControl(keyValues:Array, externalFunction:Function, updateRate:Number)
{
super();
trace("GamePlayControl instance created");
p_keyValues = keyValues;
p_externalFunction = externalFunction;
if (updateRate == undefined) updateRate = 30;
p_updateRate = updateRate;

p_keysAreDown = false;

p_keyListen = new Object;

trace("values initiated");

p_keyListen.onKeyDown = function()
{
trace("");
trace("KeyCode Pressed: "+getCode());
if (!p_keysAreDown)
{
trace("now check to see if any of the keys pressed are defined for gameplay");
if (pf_checkForKeysDown())
{
trace("the key pressed was defined");
p_keysDownInterval = setInterval(pf_runKeysDown, p_updateRate);
p_keysAreDown = true;
}
else trace("the key pressed was NOT defined");
}
}
addListener(p_keyListen);
trace("listener addded successfully");
}
private function pf_checkForKeysDown():Boolean
{
trace("checking for keys down");
var k:Number = p_keyValues.length;
for (var i:Number = 0; i<k; i++)
{
if (isDown(p_keyValues[i][1])) return true;
}
}
private function pf_runKeysDown():Void
{
trace("running 'pf_runKeysDown()'");
var k:Number = p_keyValues.length;
for (var i:Number = 0; i<k; i++)
{
if (isDown(p_keyValues[i][1])) p_externalFunction(p_keyValues[i][0]);
}
if (!pf_checkForKeysDown())
{
trace("keys no longer being pressed");
clearInterval(p_keysDownInterval)
p_keysAreDown = false;
}
}
}
everything works up until the key listener has to call the function 'pf_checkForKeysDown'

the problem is that it's not being called at all, because that trace never shows up... how can I make this work?

thanks for the help in advance.

oh yeah and you need to use this code in the FLA that uses the class...


Code:
var myKeyValues:Array = new Array();
myKeyValues[0] = ["left", 37];
myKeyValues[1] = ["right", 39];

var gpc:GamePlayControl = new GamePlayControl(myKeyValues, testFunc, 30);

function testFunc(val):Void
{
trace("testFunc()");
if (val == "left") trace("move left buddy");
if (val == "right") trace("move right buddy");
}
thank you!

Interval Scope Within A Class
Hello,
I'm trying to figure something out. Basically I am having trouble understanding the scoping of an interval when called from within a class. Here is an example I hacked up.


Code:
class TestClass {
var foo:String;
var i:Number;
var ID:Number;

public function TestClass() {
foo = 'bar';
i = 0;
ID = 0;
}

public function ShowFoo():Void {
trace("foo equals : "+foo);
if(i>5) clearInterval(ID);
}

public function IntervalFoo():Void {
var n:Number = 0;
trace('Please wait...');
ID = setInterval(ShowFoo,1000);
}
}
Why does IntervalFoo trace 'undefined' when calling ShowFoo directly reports the correct output? I boiled my bigger problem down to this example. I thinking solving this in my head will help me overcome the real issue.

Thanks for helping.
webg

Class Scope Question
Just a quick question, whats the correct way to access the "Stage" class in a diffrent class?

Example

ActionScript Code:
class classes.ScaleControl {
   
    function ScaleControl(){
        Stage.scaleMode = "noScale";
        Stage.align = "TL";
        Stage.showMenu = false;
       
        this.stageListener = new Object(); // not really sure this way works yet...
        this.stageListener.onResize = function(){
           this.doResize();
        };
        Stage.addListener(stageListener);
    }
}
/* [b]Output[/b] returns


**Error** D:ProjectsGovflashclassesScaleControl.as: Line 13: There is no property with the name 'stageListener'.
           this.stageListener = new Object();

**Error** D:ProjectsGovflashclassesScaleControl.as: Line 14: There is no property with the name 'stageListener'.
           this.stageListener.onResize = function(){

**Error** D:ProjectsGovflashclassesScaleControl.as: Line 17: There is no property with the name 'stageListener'.
           Stage.addListener(stageListener);

*/


For kicks I tried to access it via "_parent" and "_root" with no luck. I had assumed it was globaled by default. Do I need to global it somehow or is there a better way to access the other classes?

Scope In Actionscript Class
I'm having some problems with scope when trying to do some oop development within flash. Let's say I have a class that sends some params to a server and loads an xml snippet back, then traces out the xml value:

Code:
class printXML {
private var response_xml:XML = new XML();

public function printXML() {
var myloadVars:LoadVars = new LoadVars();
loadVars.ID = 12345;

response_xml.onLoad = function(success:Boolean) {
if(success) {
printValue();
}
}

nextAd_lv.sendAndLoad("http://myserver.com",response_xml,"POST");
}

private function printValue() {
trace(response_xml.firstChild.nodeValue);
}
}
The above code has a problem because within the response_xml.onLoad function, the printValue method doesn't exist. "this" refers to response_xml instead of the instance. I could maybe get around this by doing something like:

response_xml.onLoad = this.printValue;

but then I can't pass in the success boolean to see if the xml loaded properly. How can I keep my class in my scope when using handlers like onLoad within a class?

Scope Inside A Class AGAIN
Code:
private function mServerValidate() {
var xmlOUT:XML = new XML(schema00);
var xmlRTN:XML = new XML();
xmlRTN.ignoreWhite = true;
xmlRTN.onLoad = myOnLoad;
xmlOUT.sendAndLoad(this.path, xmlRTN);
//xmlOUT.sendAndLoad = Delegate.create(this, myOnLoad);
function myOnLoad(success:Boolean) {
var xmlpath = "/server/body";
var aTempXML = mx.xpath.XPathAPI.selectNodeList(this.firstChild, xmlpath);
trace(aTempXML[0].firstChild.attributes.success);
if (success) {
if (String(aTempXML[0].firstChild.attributes.success) == "1") {
trace("good login"+this);

//cant see this !!!!
im loosing scope after the "if (success) { " bit if i use delegate i cant pass the attributes i think.

??also can send it a ref to where it currently is..

Class Scope Within KeyListener
Hey everyone! First off this is my first post to this forum so if I miss some sort of forum etiquette please let me know and I apologize for the offense in advance.

On to my issue!

I have a class that puts things on the stage and will eventually make an object move on an isometric grid. The problem is I can't get a method to be called from another method in the same script with an onKeyDown function.

I understand when I try to call a method from a method that is in the same class the scope is on the movieclip or current object not the actual script. Using the delegate class is fine, but when I'm in the onKeyDown function that I have set up in one of my methods and try to use the delegate class it's like the scope has changed because it just ignores my method call. I found this here..http://www.actionscript.org/forums/a...3/t-98338.html

It seems like he's having the same problem but then the solution he posts doesn't make sense to me. I don't understand what he means in his last post on that thread by "changed the call to the keyListener"

Please help! This assignment is due in a week and my brain is about to explode!

Thank you in advance!

Class Scope And Events
Hi,

I've got a class that makes use of URLLoader with an event that fires when XML is loaded into my application. The event function however has no access to the class properties or functions. I would like to be able to access quizQuestions from within the event handler. What must I do?


Code:
public class QuizApp extends Sprite
{
//for managing questions:
private var quizQuestions:Array;

private function createQuestions()
{
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, showXML);
xmlLoader.load(new URLRequest("questions.xml"));
}

private function showXML(e:Event):void
{
XML.ignoreWhitespace = true;
var questions:XML = new XML(e.target.data);
var question:String;
var correct:Number;

for (var i:Number = 0; i < questions.question.length(); i++)
{
// Get question text.
question = questions.question[i].@title;
correct = 1;
var answers:Array = new Array();

for(var j:Number = 0; j < questions.question[i].answers.answer.length(); j++)
{
answers.push(questions.question[i].answers.answer[j].text());
}
}

quizQuestions.push(new QuizQuestion(question, 1, answers));
}
}

I Hate Class Scope
Why can't i access the Preloader and Container objects clips from my onMotionFinished function in my class?!


ActionScript Code:
/**
    Load Sub Stage class
    author: Ahmed I. Masri
    version: 1.1
    modified: 08/11/2008
    copyright: Ahmed I. Masri

    This code defines a custom class that loads the correct sub movie.
*/

// Import Built-In Classes
import mx.utils.Delegate;
import mx.transitions.Tween;
import mx.transitions.easing.*;

// Class to Load SubStages
class LoadSubStage {

    // Variable Definitions
    var Container:MovieClip;
    var StageLoader:MovieClipLoader;
    var Listener:Object;
    var Preloader:MovieClip;
   
    // Constructor Function to Select SubStage and prepare Stage
    public function LoadSubStage(linkToFile:String) {
        if (linkToFile != "intro_stage.swf") return;
        LIntroStage(linkToFile);
    }
   
    // Constructor Function to PreLoad and present Intro SubStage
    private function LIntroStage(linkToFile):Void {
        // Variable definitions
        StageLoader = new MovieClipLoader();
        Listener = new Object();
        StageLoader.addListener(Listener);

        // Empty Movie Clip to place Intro SubStage
        Container = _root.createEmptyMovieClip("MC_emptyHolder", _root.getNextHighestDepth());
        Container._x = 0;
        Container._y = 55;

        // Function to handle (pre)loading
        Listener.onLoadStart = Delegate.create(this, onLoadStart);
        Listener.onLoadProgress = Delegate.create(this, onLoadProgress);
        Listener.onLoadInit = Delegate.create(this, onLoadInit);
       
        Preloader = _root.attachMovie("MC_stageLoader", "MC_stageLoader" , _root.getNextHighestDepth(), {_x:400, _y:261.5});
        Preloader.MC_loadingProgressBar._width = 0;
        Preloader.txt_PercentLoaded.text = "00";
       
        // Loading of SubStage
        StageLoader.loadClip(linkToFile, Container);
    }
   
    // Function to handle start of (pre)loading
    private function onLoadStart() {
        Container._visible = false;
    }
   
    // Function to handle progress of (pre)loading
    private function onLoadProgress(mc:MovieClip, l:Number, t:Number):Void {
        Preloader.MC_loadingProgressBar._width = (l / t) * (Stage.width * 1.2);
        Preloader.txt_PercentLoaded.text = Math.round((l / t) * 100);
    }
   
    // Function to handle completion of (pre)loading
    private function onLoadInit():Void {
        // Variable definition
        var middleOrangeBarY:Number = _root.MC_headerBackground.MC_middleOrangeBar._y;
        var bottomOrangeBarY:Number = _root.MC_headerBackground.MC_bottomOrangeBar._y;
       
        // Fade out Preloader;
        var tweenPreloaderFade:Tween = new Tween(Preloader, "_alpha", Strong.easeOut, 100, 0, 10, false);
        var tweenMiddleBar:Tween = new Tween(_root.MC_headerBackground.MC_middleOrangeBar, "_y", Strong.easeOut, middleOrangeBarY, -3.5, 10, false);
        var tweenBottomBar:Tween = new Tween(_root.MC_headerBackground.MC_bottomOrangeBar, "_y", Strong.easeOut, bottomOrangeBarY, 619, 10, false);
       
        // On completion of Fade out
        tweenPreloaderFade.onMotionFinished = function() {
            Preloader.removeMovieClip();
            Container._visible = true;
        }
    }
}

Class Scope And GotoAndStop..
Hello,
I have a flash file with three labeled frames ("intro", "game" and "game_over"). And an .as file called Application.as. In the 2nd frame of the flash file ("game") I instantiate an instance of the Application class like so:


ActionScript Code:
var app:Application = new Application() ;
addChild( app ) ;

Within the Application.as file I invoke the function, gotoAndStop( "game_over" ) whenever the game has concluded. My problem is that the previously noted invocation doesn't transverse the main timeline to the "game_over" frame, instead, it does nothing. I'm assuming this is a problem of scope.

Here is the Application.as file, please note that I've omitted a great deal of code for simplicity:

Application.as

ActionScript Code:
package
{

   public class Application extends MovieClip
   {

      public function Application():void
      {

         gotoAndStop( "game_over" ) ;
      }

   }

}

Scope Of A Listener Within A Class
Here i am again.
I've wrote a class that manages the input from keyboard. It associates a button to an action and sends it to an object.
The problem appears at the key listener object.
At the constructor i define the variables of the class, but i can't access them from within the listener.

I've searched all this forum, found similar problems with no satisfactory answer. And the google didn't help too

How do i access these vars?







Attach Code

class KeyManager{

private var _UP:Object=new Object();

private var klisten:Object=new Object();

public function KeyManager(target:Corpo){
_UP.code=Key.UP;
_UP.action="UP";

trace(_UP.action) // returns "UP"

klisten.onKeyDown=function(){
trace(_UP.action) //returns "undefined"
}
Key.addListener(klisten);
}
}

Callback / Scope Within A Class
So this works when I move the function to call outside of the callback method onLoad, trace works inside the onLoad, so I know the function and the onLoad work fine. I was thinking it was a scope issue, but I followed ...

http://www.adobe.com/devnet/flash/articles/as_bestpractices_04.html

I think to a tee, unless I have something spelled wrong, or maybe I've just gone crazy? Your help is much appreciated.

HmcH







Attach Code

//in the var declare
var thisObj:ghost;

//in the constructor
var thisObj:ghost = this;

//the function with the scoping issue is called...
function addLinkDoc() {
toSend.Active = 1;
toSend.sendAndLoad("http://something.asp", toReceive, "post");
toReceive.onLoad = function(success:Boolean) {
if (success) {
thisObj.ENDit();
}
};
}

Class Variable Scope
Take a look at this code:


ActionScript Code:
import mx.utils.Delegate;class Test{  var secret:Number = 50;  function Test(mc:MovieClip)  {    var i:Number;    var new_mc:MovieClip;    for(i = 0; i < 5; i++)    {      new_mc = mc.attachMovie("my_movie", "new_name" + i, mc.getNextHighestDepth(), {_x: i * 50});      new_mc.i = i;      new_mc.onRelease = Delegate.create(this, alert);    }  }  function alert()  {    trace(this.i);    trace(this.secret);  }}


Well... Doesnt work at all... In the class, there isnt a instance of i, so, how may i access this property inside a class function? But i still have an way to access the class.

I could do this way:


ActionScript Code:
class Test{  function Test(mc:MovieClip)  {    var i:Number;    var new_mc:MovieClip;    for(i = 0; i < 5; i++)    {      new_mc = mc.attachMovie("my_movie", "new_name" + i, mc.getNextHighestDepth(), {_x: i * 50});      new_mc.i = i;      new_mc.class = this;      new_mc.onRelease = function()      {        trace(this.i);        this.class.alert();      }    }  }  function alert()  {    trace(this.secret);  }}


But this way, doesnt sounds good

Any suggests?

Class Variable Scope
I'm somewhat new to writing classes so forgive me if I get some wrong terminology.

I have a MC with a class attached to it, and I have other MCs within that MC. I need those MCs to be able to access variables within the main MC class. Here is a quick'n'dirty:


Code:
class Foo extends MovieClip{private var h:Number;
private var subMC:MovieClip;
function Foo(_h:Number){h = _h;
}

subMC.onEnterFrame = function(){trace(h);
}
}
How can I access variables in the Foo class from another MCs scope? I have tried using static var but aren't they constant regardless of instance?

Class Scope And Events
Hi,

I've got a class that makes use of URLLoader with an event that fires when XML is loaded into my application. The event function is a method of the class itself but it has no access to the class properties or functions.


Code:
private function createQuestions()
{
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, showXML);
xmlLoader.load(new URLRequest("questions.xml"));
}

private function showXML(e:Event):void
{
// Cannot access class properties and methods from here!
}
Are there any popular/common solutions to this problem?

Class Scope Loop
Hi

I have a base swf, which loops through xml, calling a page.as which pulls in seperate xml files and populates the pages.

I therefore need buttons to communicate back to thier respect page.as to do thier work...

atm I'm calling the pages via


Code:

var tempPage:Page = new Page(mc, i, 15, 155*i+100);
however unless I'm wrong I have to increment the tempPage variable so I can access the correct page.as

right? how do I do this?

thanks

I Cant Figure It Out Class And Scope AGAIN
Code:
class KeyTrap extends MovieClip
{
private var self:KeyTrap;
private var parent : MovieClip;
function KeyTrap (parent)
{
var self = this;
//constrctor
}
private function onEnterFrame ()
{
_root.debug.text = "fff";
trace ("looping");
self.onEnterFrame ();
};
}
SIMPLY WHY CANT I GET THE onEnterFrame working. Do I Have to have a graphic instance on the stage, im just using a single "new" object but cant get onEnterFrame to work.

thanks for any help

Function Scope In Class
In the 1st frame of my fla, i put 1 line:
var classScope:ClassScope = new ClassScope();


Code:
class ClassScope {
public var min:Number = 10;

function ClassScope() {
var keyListener:Object = new Object();
keyListener.onKeyDown = function () {
trace(min);
}

Key.addListener(keyListener);
}
}
But the trace result shows 'undefined'! How to get the 'min' value?

Scope Problem In Class
I am trying to have a some actions happen after onMotionFinished


ActionScript Code:
var subNavTween:Tween = new Tween(subNavContainer, "_alpha", Strong.easeOut, 0, 100, .5, true);
        subNavTween.onMotionFinished = function() {
            //trace(depth);
            var navArrow = subNavContainer._parent.attachMovie("navArrow_mc", "navArrow_mc", depth++);
            //trace(navArrow);
            var arrowTween:Tween = new Tween(navArrow, "_alpha", Strong.easeOut, 0, 100, 1, true);
            var arrowTween:Tween = new Tween(navArrow, "_y", Strong.easeOut, $target._y + $target._height + 5, $target._y + $target._height + 6, 2, true);
            navArrow._x = $target._x + ($target._width / 2);
        }


The problem is that depth is not accessible.

If this was just on a timeline i could do this

ActionScript Code:
subNavTween.classPath = this;

but the above class will reject that stating that

anyone know how i can reference the class path in that onMotionFinished function?

thanks

After Tween, Jump To New Frame (using Tween Class)
I need some help with using the tween class (among other things).

See my attached test file. It's clearer than my description.

You're supposed to be able to click the "next" or "prev" buttons and see the movie clip move forwards or backwards. It works, but only on the first click of the button. After the initial click I need the timeline to jump to frame label "2", and after the second click I need the timeline to jump to frame label "3", and so on, so that I can implement a new set of perameters. Is that clear? I'm so annoyed with this. Please help!

Thanks.

Tween Class Problem. Tween Freeze?
I am using the tween class to do an alpha tween on some jpgs that get loaded into a movieclip. Everything thing works great until the user rapidly clicks on the 'next' arrow to jump forward to a new picture. If the user clicks too quickly something happens and the tween function stops working.

Here is the tween code:

Code:
//set up tweening
import mx.transitions.easing.*;
import mx.transitions.Tween;
var tweenAlpha:Tween;
function alphaTween(object,duration){
easeType = mx.transitions.easing.Regular.easeIn;
tweenAlpha = new mx.transitions.Tween(object, "_alpha", easeType, 0, 100, duration, true);
}
http://12dogsofchristmas.com/12_dogs_menu2.swf

You'll notice that if you click slowly on the arrows the pictures load correctly with the story. However, if you click fast they stop tweening.

thanks for the help.

Tween.stop(). Part Of The Tween Class?
I need to know if tween.stop() is part of the Tween class in Flash 8 or if it's related to an extension I installed (ie. TweenExtended).

Tween Class Not Always Fulling Complete Tween
I have a switch statement that is a part of the tween effects found on the header of http://gfxcomplex.com/blog.

the problem is this case will change the rotation of a sprite and then tween it to zero. The funny thing is some times ("not all the time") some of the tween stop in the middle and do not complete leaving the sprite with a rotation somewhere in the middle of 180 to 0. My question is, is there something in my code that could be the reason for this or is this a bug??

You may have to watch the header for a long time to see this bug happen as it seems to be more a fluke then a true code bug.


PHP Code:



case 7 :            var u:uint = 0;            test1.getChildAt(0).rotation = 180;            test1.getChildAt(1).rotation = 180;            test1.getChildAt(2).rotation = 180;            test1.getChildAt(3).rotation = 180;            test1.getChildAt(4).rotation = 180;               intervalId = setInterval(function myFunction(){                                                          myTween1 = new Tween(test1.getChildAt(u), "rotation", Bounce.easeOut, 180, 0, 3, true);                                                          u++;                                                          if(u == 5){                                                                                                                      clearInterval(intervalId);                                                                                                                        }                                                          },                                                          150);break; 

Arrays Within A Class? Can't Figure Out Scope.
I'm having the hardest time figuring out how Flash handles the scope of Arrays within a Class definition. If I define an integer, it can only be accessed by one instance of that Class. But if I define an Array, all instances access the same array.

here's my basic class:

Code:
class TestObject {
var myNumber;
var myArray=new Array();
}
and here's the FLA's use of that code:

Code:
stop();

test=new TestObject();
test2=new TestObject();

test.myNumber=50;
trace(test2.myNumber);
//returns "undefined", as it should

test.myArray[0]=4;
trace(test2.myArray[0]);
//returns 4, even though it shouldn't?
Does that make sense to anyone? Thanks for the help!

Lost Scope In A Class File
hi.

i've got a function that draws out a calendar for me. first it creates a movie clip and then a text field inside.
code:
// Create the Empty Movie Clip
_dateClipHolder = _root.createEmptyMovieClip("_dateClip"+j,_root.get NextHighestDepth());

// Create a Text Field Inside them
_dateClipHolder.createTextField("_thisDate"+j,j,0, 0,_columnWidth,_colHeight);

now in a totally separate function i want to access those text fields and set their properties -- like this:
code:
// I lose focus in this function
_dateClipHolder["_thisDate" + _today].border = true;
_dateClipHolder["_thisDate" + _today].borderColor = 0xFFFFFF;
_dateClipHolder["_thisDate" + _today].background = true;
_dateClipHolder["_thisDate" + _today].backgroundColor = 0xCCCCCC;

_dateClipHolder is a private class member. i think that i have to pass a reference back to the text field or something but i'm not sure how to do it. any ideas?? all help is greatly appreciated.

thanks. - fumeng

[AS2] Scope Of Class And Clearing Data
Hi :

I am using a class to create a random array of words.
In, for example, frame 30 I declare the class and create a new instance.

code:
import RandWord;
var Dummy:RandWord = new RandWord();
Dummy.Scramble
var Scrambled:Array = Dummy.ScrambledArray;


pseudo code
loop to add each word to 50 textfields
place a button on the stage to reset
reset button should reinitialise the class getting back a different order and then put those into the textfields.

At present the class works fine but on the reset button displays exactly the same as the first run.

If I re-enter this frame to re scramble the array how do I re declare the class or clean out the returned data.

TIA

Scope Or Path Issue In Class
Hello again!

I just watched an OOP video on gotoAndLearn the other day. I was messing with the idea, and I think I have a scope and/or path issue in my class. The class is very bare bones, so please don't laugh too hard.

ActionScript Code:
class Preloader extends MovieClip {
    var l:Number;
    var t:Number;
    var percent:Number;
    var preloader:MovieClip;
    var bar:MovieClip;
    //
    public function Preloader(url:String, level:MovieClip) {
        //
        var shell:MovieClip = level.createEmptyMovieClip("shell", level.getNextHighestDepth());
        var shell2:MovieClip = level.createEmptyMovieClip("shell2", level.getNextHighestDepth());
        shell.loadMovie(url);
        trace(level.preloader); // traces fine
        trace(typeof (level.preloader.bar)); //trace movieclip
        level.preloader._visible = false; // movieclip can be targeted here
        shell2.onEnterFrame = function() {
            l = shell.getBytesLoaded();
            t = shell.getBytesTotal();
            percent = (l/t)*100;
            if (t>4) {
                if (percent>0) {
                    level.preloader._visible = true; // can NOT taget clip here
                    level.preloader.bar._xscale = percent;
                }
                if (percent == 100 && shell._width>0) {
                    delete shell2.onEnterFrame;
                    shell.removeMovieClip();
                    shell2.removeMovieClip();
                    level.preloader._visible = false;
                    loadMovieNum(url, 0);
                }
            }
        };
    }
}
level.preloader._visible = true; // can NOT taget is where I have problem. I can traget the MC right away in the constructor but not here. Any ideas?

As always, Thanks

_Me.

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