Actionscript Functions
i'm new to AS but familiar with javascript, i'm hoping i can get some point of reference from you guys. i don't really get how functions work in AS, and i've read up a bit but i think i learn better with examples. i'll put a couple simple javascript functions down and how/why it works the way it does, and maybe if somebody gets a free minute they could write the same function in actionscript (with how/why comments too), that'd be cool and i'd appreciate the help. and i'm assuming that arguements, strings, variables, etc all have roughly the same meaning in AS...
Code: //basic element feature change functionname() { elementToBeAffected.featureOfElement.currentSetting = "newSetting"; } //usually the above is in head and the below is in body but doesn't need to be. onSomeEvent="functionname();" a working example, incl. simple var and if
Code: <html> <head> <script language="javascript"> //declare variables, default to global var size = 100 function grow(obj) { //follow an 'if' or 'else' with anything, just put in curlies if (size < 200) { obj.style.width = size++; //amend the vars anywhere you want, in function or outside or event driven, whatever size=size+1; //and a little self-fulfilling setTimeout to create the anim setTimeout(function(){grow(obj)}, 10); } } </script> </head> <body> //called with id, passed with object reference so no ' needed <a href="#" onmouseover="grow(divA);">grow it</a> <div id="divA" style="width:100px;height:100px;background:navy;"></div> </body> </html> thanks.
FlashKit > Flash Help > Flash ActionScript
Posted on: 05-19-2004, 04:44 PM
View Complete Forum Thread with Replies
See Related Forum Messages: Follow the Links Below to View Complete Thread
MC 'on' Functions Through Actionscript
I'm trying to assign on functions (press, release, etc...) to MC generated by action code in a for loop. This is the code I've got but it does not do anything.
Code:
_level0.newmenu.subMenu[i].onRollOver = function (){
_level0.isay = sub[i].attributes.over;
setProperty ("_level0.imcbaloon", _visible, true);
}
_level0.newmenu.subMenu[i].onRollOut = function (){
_level0.isay = "";
setProperty ("_level0.imcbaloon", _visible, false);
}
MC On Functions Actionscript
on a for loop creating buttons on a menu i've got the following on functions added which refer to an xml file for the actions. the problem is that they load the functions but the last one ends up being applied to all of the buttons.
Code:
duplicateMovieClip("_level0.newmenu.buttonMC", "subMenu"+i, i);
menuna = sub[i].attributes.title;
set("_level0.newmenu.subMenu"+i+".menuname", menuna);
_level0.newmenu["subMenu"+i].onRollOver = function() {
_level0.isay = sub[i].attributes.over;
setProperty("_level0.imcbaloon", _visible, true);
};
_level0.newmenu["subMenu"+i].onRollOut = function() {
_level0.isay = "";
setProperty("_level0.imcbaloon", _visible, false);
};
Actionscript 2.0 Functions - Help
Hi all. Hope your all well.
I'm having a spot of bother with some scripting. Any help would be much appreciated.
The problem is this. I'm scripting a slide show. The slide show has three buttons. mcNextButton, mcBackButton and mcResetButton. I can get the mcNextButton to fade the images forwards when the user presses the button. But i'm having problems fading the images in reverse when the user presses the mnBackButton.
Below is the scritpt:
var aImages:Array = new Array(mcOne, mcTwo, mcThree, mcFour, mcFive, mcSix);
var nIndex:Number = 0;
var nInterval:Number;
mcNextButton.onRelease = function():Void{
clearInterval(nInterval);
nInterval = setInterval(fadeImageForwards, 20, aImages[nIndex] )
};
mcBackButton.onRelease = function():Void {
clearInterval(nInterval);
nInterval = setInterval(fadeImageBackwards, 20, aImages[nIndex])
};
mcResetButton.onRelease = function():Void {
for(var i:Number = 0; i < aImages.length; i++){
aImages._alpha = 100;
};
nIndex = 0;
};
function fadeImageForwards(mcImage:MovieClip):Void{
mcImage._alpha -= 20;
if(mcImage._alpha <= 0){
clearInterval(nInterval);
nIndex++;
};
updateAfterEvent;
};
function fadeImageBackwards(mcImage:MovieClip):Void{
mcImage._alpha -= 20;
if(mcImage._alpha <= 0){
clearInterval(nInterval);
nIndex--;
};
updateAfterEvent;
};
Recursive Functions In Actionscript
Im trying to create a maze generator, i already wrote a recursive function that creates the maze, the problem is that when a copy of a function ends, the program doesnt continue with the execution of the function that invoked it. So.....when my maze generator randomly gets trapped(dead end) the algortm doesnt continue creating another path.
Is this behavior natural in actionscript, or im making something wrong?
Ideas are welcome.
Multible Functions Using Actionscript
Hello. I need to know how to make 3 differant fucntions work at the same time using actionscript on a button. Below is my code.
getURL("javascript:focus(); for (j=186; j>1; j--) {moveBy(1,0); } for (j=6; j>0; j--) {resizeBy(0,1); } for (i=10; i>0; i--) { for (j=6; j>0; j--) { moveBy(0,i); moveBy(i,0);moveBy(0,-i); moveBy(-i,0); }} void(0);");
I want to get it to move, resize and shake all at the same time.Is there anything I can change or add to this code to do that?
Thank you for reading.
Order To Functions In Actionscript?
Say I have something that looks like this:
play_again.onRelease = function()
{
clean_up();
setup();
}
Is there a way to make sure that clean_up() runs BEFORE setup() starts? As it is right now, they seem to be running simultaneously. My flash game doesn't have time to clean up all the loose ends before it starts again. When it runs the second time around, nothing works correctly because certain variables or movie clips haven't been reset.
Nested Functions In ActionScript 2.0
In my previous post i explained that i can't get to write in to a global variable when it is in nested function. Im using
on change listener and xml.onLoad when im trying to write from the XML.onLoad i have a problem cause that value is written to the varaible only locally and i can't use it in other frame. Is there any solution for ex any other way to retrieve XML without onLoad function ?? Thanks.
Variables In Actionscript Functions
Okay, so I'm calling an actionscript function from an HTML file, that I called displayImage (guess what it does!).
here is the function:
CODEfunction displayImage(imageName){
_root.introMovie.siteMovie.imageName._visible=1;
}
Who Can Combine This ActionScript Into A Few Simple Functions?
For cleanliness and versatility, I am attempting to combine the following action script into a few functions. Download the movie to get a good idea of what I'm doing; I want to add several more of the color movie clips with respective buttons, but the code is getting too big. Please help me combine these into simple functions on the main timeline if possible!
Thanks!
// initial hill locations - these vars are located on the main timeline - first frame.
hill1X = 275;
hill1Y = 160;
hill1XS = 100;
hill1YS = 100;
hill1A = 100;
hill2X = 275;
hill2Y = 148;
hill2XS = 100;
hill2YS = 100;
hill2A = 100;
hill3X = 275;
hill3Y = 132;
hill3XS = 100;
hill3YS = 100;
hill3A = 100;
play();
// math placed on the movie clip to be moved - this script has to be on each movie clip so far... any way to make dynamic or into a handy single function...?
onClipEvent (enterFrame) {
// moves the hill movie clip to a new position smoothly
// get current hill position
var currentXhill = this._x;
var currentYhill = this._y;
var currentXhillScale = this._xscale;
var currentYhillScale = this._yscale;
var currentXhillAlpha = this._alpha;
// distance from current hill Xcoord to final hill Xcoord
var hillXdifference = _root.hill1X-currentXhill;
var hillYdifference = _root.hill1Y-currentYhill;
var hillXdifferenceScale = _root.hill1XS-currentXhillScale;
var hillYdifferenceScale = _root.hill1YS-currentYhillScale;
var hillXdifferenceAlpha = _root.hill1A-currentXhillAlpha;
// create a decreasing increment until hill reaches final location
var hillXmove = (hillXdifference/6);// smaller = faster
var hillYmove = (hillYdifference/6);
var hillXmoveScale = (hillXdifferenceScale/12);
var hillYmoveScale = (hillYdifferenceScale/12);
var hillXmoveAlpha = (hillXdifferenceAlpha/12);
// set the new wall position
this._x = currentXhill+hillXmove;
this._y = currentYhill+hillYmove;
this._xscale = currentXhillScale+hillXmoveScale;
this._yscale = currentYhillScale+hillYmoveScale;
this._alpha = currentXhillAlpha+hillXmoveAlpha;
}
// button script to set a new location for the moving the movie clips on the main timeline
on (release) {
hill1X = 325;
hill1Y = 160;
hill1XS = 300;
hill1YS = 300;
hill1A = 70;
hill2X = 575;
hill2Y = 148;
hill2XS = 80;
hill2YS = 80;
hill2A = 70;
hill3X = 175;
hill3Y = 132;
hill3XS = 150;
hill3YS = 150;
hill3A = 10;
}
ActionScript Functions In The Flash Player 7
I need this ActionScript functions in the flash player 7, but, only function in the 6, I am trying to arrange to function in the 7, but all my attempts had given wrong, if somebody will be able to help.
Quote:
// Action script...
// [Action in Frame 1]
function ExtDef(s) {
var _l1 = s;
_l1.indexOf(".") != -1 ? (_l1) : (_l1+".jpg");
return (_l1.indexOf(".") != -1 ? (_l1) : (_l1+".jpg"));
}
// End of the function
imagem = new Array(_root.i1, _root.i2, _root.i3, _root.i4, _root.i5, _root.i6, _root.i7, _root.i8, _root.i9, _root.i10);
var QtdImagens = 0;
while (QtdImagens<10 && imagem[QtdImagens] != null) {
QtdImagens++;
}
// end while
var pic_arr = [ExtDef(_root.i1), ExtDef(_root.i2), ExtDef(_root.i3), ExtDef(_root.i4), ExtDef(_root.i5), ExtDef(_root.i6), ExtDef(_root.i7), ExtDef(_root.i8), ExtDef(_root.i9), ExtDef(_root.i10)];
pic_arr.length = QtdImagens;
var currentSlide = 0;
this.attachMovie("slideshow", "show", 1, {_x:0, _y:0, _visible:false, fps:15, nFrames:5, alphaIncr:6, slides_arric_arr, slideDepth:1, repeat:true, slideTracker:"currentSlide"});
show.addListener(this);
this.onAllSlidesLoaded = function() {
show._visible = true;
show.beginTransitions();
};
this.onShowOver = function() {
};
pausa_mc.onRelease = function() {
// if playing
if (this._currentframe == 1) {
this.gotoAndStop("stopped");
// para a imagem no slide atual
show.stopTransitions();
// certifique-se que a imagem atual está indicando alpha 100
for (var t = 0; t<pic_arr.length; t++) {
if (t == currentSlide) {
show["slide"+t]._alpha = 100;
} else {
show["slide"+t]._alpha = 0;
}
}
// if parado
} else {
// começa acima transições do slide atual
this.gotoAndStop("playing");
show.activateInSeq(currentSlide);
}
};
Executing Functions In Variables In Actionscript
My question is, how do you execute functions in variables when put into the parameter of a function?
Code:
function a(afnct){
var i = 0
while(i < afnct.length){
_root["button"+i+"_btn"].onRelease = afnct[i]
i++
}
}
var functions = Array([function(){trace("Yes")}], [function(){trace("No")}])
a(functions)
When I execute, the buttons don't do anything. What's my problem?
ActionScript To Mimic Some JavaScript And PHP Functions
Here are the functions:
Code:
PHP: foreach(array_array as value_mixed){}
JS: alert("message")
JS: confirm("message")
JS: prompt("message", "input")
With PHP foreach, I realize that I can use a for or while loop. For the three javascript functions, I have made my own, but the code keeps "running". It doesn't "pause". So, if I have this code:
ActionScript Code:
var a = prompt("Enter a word", "")
trace(a)
nothing gets traced. Is there a way to "pause" ActionScript?
Can You Achieve Math Functions With Actionscript?
I want to put a mortgage calculator inside a flash file but don't know how to re-code this page in actionscript. I need math functions in a big way...
Anybody know the best way to achieve this?
It needs to work similarly to this page...
luxurymountainproperties.info/calculator.html
Creating Reusable Functions In ActionScript 3.0
Hello,
I'm working on my first ActionScript 3.0 project. It involves having two NetStreams (ns1 and ns2). The code I have works, but it's bloated. Example:
ns1.addEventListener(NetStatusEvent.NET_STATUS, onStatusEvent1);
function onStatusEvent1(stat:Object):void {
if (stat.info.code == "NetStream.Play.Stop") {
trace("rewind");
ns1.seek(0);
ns1.pause();
}
return;
}
ns2.addEventListener(NetStatusEvent.NET_STATUS, onStatusEvent2);
function onStatusEvent2(stat:Object):void {
if (stat.info.code == "NetStream.Play.Stop") {
trace("rewind");
ns2.seek(0);
ns2.pause();
}
return;
}
Is there someway I could combine this into one function that would have enough intelligence to know which NetStream is being referenced?
Any help appreciated!
Bill
Actionscript Not Calling Some Javascript Functions In IE
Hi guys,
I've been having some problems in Flash MX 2004 with regards to calling Javascript functions in IE.
I've got two actions assigned to a button. The first one calls a Javascript function in the HTML page, sending it some variables which update the contents of the HTML page.
The second action then changes the visibility of the DIV that has just been updated.
All works hunky-dory in FireFox, but only does the show/hide DIV bit in IE. Anybody come across any quirks with calling a Javascript function with variables in IE (6 on Win2k)?
Code example...
on (release) {
getURL("javascript:MM_setTextOfLayer('calculator', '','calculator');void(0);");
getURL("javascript:MM_showHideLayers('calculator', '','show')")
}
After seeing some advice that maybe adding the void(0) to the end of the call may help it, I've tried that, but to no avail.
I know that the JS function isn't being called because I've replaced my original function with a simple JS function that just makes an alert window that says "OK". As I say, it works fine in Firefox, but not IE...
Any help is hugely appreciated
Is There Any Way To Dynamically Call Functions In Actionscript?
ActionScript Code:
for(x=1;x<=num_of_things;x++){
eval("thing" add x) .gotoAndStop("needed_place");
}
I know the above code won't work, but I'm hoping that it gets my question across.
I want to know if there is a way to call functions in movie clip instances defined by a variable. Thanks for your time.
Actionscript Assistance (Functions And Parameters)
Ok, I'm new to flash actionscript, usually coding .Net/PHP. I need to assemble a simple flash game below is the code I have so far basically there is a cannon which fires a cannonball when the cannon ball hits the wall _x < 50 it resets awaiting the next shot. Can anyone see what I am doing wrong. At the moment the cannon ball just resets instantly I believe it something to do with the fireCannonBall function (the parameter perhaps?)
Thanks!
Attach Code
//Set out values up
var gravity = 20;
var noOfBullets = 10;
var endGame = false;
var canReFire = true;
var curBullet = 0;
// Attatch the graphics
attachMovie("tank", "tank", 2, {_x:550, _y:750});
tank.onEnterFrame = function() {
// Mouse determines power so gte the position
mousex = _xmouse-this._x;
mousey = (_ymouse-this._y)*-1;
angle = Math.atan(mousey/mousex)/(Math.PI/180);
if (mousex<0) {
angle += 180;
}
if (mousex>=0 && mousey<0) {
angle += 360;
}
if (angle>180) {
angle = 180;
}
if (angle<0) {
angle = 0;
}
firepower = Math.sqrt(mousex*mousex+mousey*mousey);
if (firepower>500) {
firepower = 500;
}
this.cannon._rotation = angle*-1;
};
function onMouseDown() {
//Check if its the end of the game!
if (endGame==false) {
//Check to see if the canrefire flag is set. (Basicly means another bullet is around)
if (canReFire==true) {
angle = tank.cannon._rotation-1;
start_ball_x = tank._x+48*Math.cos(angle*Math.PI/180);
start_ball_y = tank._y+48*Math.sin(angle*Math.PI/180);
cannonball_fired = attachMovie("cannonball", "cannonball_"+curBullet, _root.getNextHighestDepth(), {_x:start_ball_x, _y:start_ball_y});
curBullet = curBullet + 1;
if (curBullet==11) {
curBullet = 1;
endGame = true;
}
cannonball_fired.dirx = Math.cos(angle*Math.PI/180)*firepower;
cannonball_fired.diry = Math.sin(angle*Math.PI/180)*firepower;
cannonball_fired.finished = false;
canReFire = false;
fireCannonBall(cannonball_fired);
}
}
}
function fireCannonBall(cannon_ball:MovieClip) {
if (cannon_ball.finished==false) {
do {
cannon_ball.diry += gravity;
cannon_ball._x += this.dirx / 10;
cannon_ball._y += this.diry / 10;
} while (cannon_ball._x < 50)
//If we exited the loop collision occured so reset.
cannon_ball._x = 550;
cannon_ball._y = 750;
cannon_ball.dirx = 1;
cannon_ball.diry = 1;
cannon_ball = nothing;
canReFire = true;
cannon_ball.finished = true;
}
}
Edited: 11/23/2007 at 02:08:19 AM by Liam Bateman
Calling Javascript Functions From Actionscript 2
Hello
I am having trouble calling a function in a separate .js file using actionscript 2.
Is this actually possible?
I have a Flash 8 login form and I need it to pass the username and password to an AJAX function in a separate file.
Thanks anyone
Actionscript Hash Functions Download
Hi,
I just finished uploading my AS2 and AS3 Hash classes. They allow you to hash a string using the following algorithms in a much cleaner way than with the Adobe libraries:
MD5
SHA-1
SHA-256
http://www.jamesthompsondigital.com/developers/actionscript/classes/hash.php
//---------------------
Example Code:
import jtd.crypto.Hash;
trace(Hash.SHA256("MyPassword"));
ActionScript Functions In The Flash Player 7
I need this ActionScript functions in the flash player 7, but, only function in the 6, I am trying to arrange to function in the 7, but all my attempts had given wrong, if somebody will be able to help.
Quote:
// Action script...
// [Action in Frame 1]
function ExtDef(s) {
var _l1 = s;
_l1.indexOf(".") != -1 ? (_l1) : (_l1+".jpg");
return (_l1.indexOf(".") != -1 ? (_l1) : (_l1+".jpg"));
}
// End of the function
imagem = new Array(_root.i1, _root.i2, _root.i3, _root.i4, _root.i5, _root.i6, _root.i7, _root.i8, _root.i9, _root.i10);
var QtdImagens = 0;
while (QtdImagens<10 && imagem[QtdImagens] != null) {
QtdImagens++;
}
// end while
var pic_arr = [ExtDef(_root.i1), ExtDef(_root.i2), ExtDef(_root.i3), ExtDef(_root.i4), ExtDef(_root.i5), ExtDef(_root.i6), ExtDef(_root.i7), ExtDef(_root.i8), ExtDef(_root.i9), ExtDef(_root.i10)];
pic_arr.length = QtdImagens;
var currentSlide = 0;
this.attachMovie("slideshow", "show", 1, {_x:0, _y:0, _visible:false, fps:15, nFrames:5, alphaIncr:6, slides_arr:pic_arr, slideDepth:1, repeat:true, slideTracker:"currentSlide"});
show.addListener(this);
this.onAllSlidesLoaded = function() {
show._visible = true;
show.beginTransitions();
};
this.onShowOver = function() {
};
pausa_mc.onRelease = function() {
// if playing
if (this._currentframe == 1) {
this.gotoAndStop("stopped");
// para a imagem no slide atual
show.stopTransitions();
// certifique-se que a imagem atual está indicando alpha 100
for (var t = 0; t<pic_arr.length; t++) {
if (t == currentSlide) {
show["slide"+t]._alpha = 100;
} else {
show["slide"+t]._alpha = 0;
}
}
// if parado
} else {
// começa acima transições do slide atual
this.gotoAndStop("playing");
show.activateInSeq(currentSlide);
}
};
ActionScript Functions In The Flash Player 7
I need this ActionScript functions in the flash player 7, but, only function in the 6, I am trying to arrange to function in the 7, but all my attempts had given wrong, if somebody will be able to help.
Quote:
// Action script...
// [Action in Frame 1]
function ExtDef(s) {
var _l1 = s;
_l1.indexOf(".") != -1 ? (_l1) : (_l1+".jpg");
return (_l1.indexOf(".") != -1 ? (_l1) : (_l1+".jpg"));
}
// End of the function
imagem = new Array(_root.i1, _root.i2, _root.i3, _root.i4, _root.i5, _root.i6, _root.i7, _root.i8, _root.i9, _root.i10);
var QtdImagens = 0;
while (QtdImagens<10 && imagem[QtdImagens] != null) {
QtdImagens++;
}
// end while
var pic_arr = [ExtDef(_root.i1), ExtDef(_root.i2), ExtDef(_root.i3), ExtDef(_root.i4), ExtDef(_root.i5), ExtDef(_root.i6), ExtDef(_root.i7), ExtDef(_root.i8), ExtDef(_root.i9), ExtDef(_root.i10)];
pic_arr.length = QtdImagens;
var currentSlide = 0;
this.attachMovie("slideshow", "show", 1, {_x:0, _y:0, _visible:false, fps:15, nFrames:5, alphaIncr:6, slides_arr:pic_arr, slideDepth:1, repeat:true, slideTracker:"currentSlide"});
show.addListener(this);
this.onAllSlidesLoaded = function() {
show._visible = true;
show.beginTransitions();
};
this.onShowOver = function() {
};
pausa_mc.onRelease = function() {
// if playing
if (this._currentframe == 1) {
this.gotoAndStop("stopped");
// para a imagem no slide atual
show.stopTransitions();
// certifique-se que a imagem atual está indicando alpha 100
for (var t = 0; t<pic_arr.length; t++) {
if (t == currentSlide) {
show["slide"+t]._alpha = 100;
} else {
show["slide"+t]._alpha = 0;
}
}
// if parado
} else {
// começa acima transições do slide atual
this.gotoAndStop("playing");
show.activateInSeq(currentSlide);
}
};
Embedded Actionscript Class Functions
In an actionscript Class definition file is it possible to have a function within a function? Like so:
public function clear () {
public function end () {
var = dothis;
}
}
When i have tried this i get this error message:
Attribute used outside class.
public function end() {
Any help is appeciated.
ActionScript Functions In The Flash Player 7
I need this ActionScript functions in the flash player 7, but, only function in the 6, I am trying to arrange to function in the 7, but all my attempts had given wrong, if somebody will be able to help.
// Action script...
// [Action in Frame 1]
function ExtDef(s) {
var _l1 = s;
_l1.indexOf(".") != -1 ? (_l1) : (_l1+".jpg");
return (_l1.indexOf(".") != -1 ? (_l1) : (_l1+".jpg"));
}
// End of the function
imagem = new Array(_root.i1, _root.i2, _root.i3, _root.i4, _root.i5, _root.i6, _root.i7, _root.i8, _root.i9, _root.i10);
var QtdImagens = 0;
while (QtdImagens<10 && imagem[QtdImagens] != null) {
QtdImagens++;
}
// end while
var pic_arr = [ExtDef(_root.i1), ExtDef(_root.i2), ExtDef(_root.i3), ExtDef(_root.i4), ExtDef(_root.i5), ExtDef(_root.i6), ExtDef(_root.i7), ExtDef(_root.i8), ExtDef(_root.i9), ExtDef(_root.i10)];
pic_arr.length = QtdImagens;
var currentSlide = 0;
this.attachMovie("slideshow", "show", 1, {_x:0, _y:0, _visible:false, fps:15, nFrames:5, alphaIncr:6, slides_arric_arr, slideDepth:1, repeat:true, slideTracker:"currentSlide"});
show.addListener(this);
this.onAllSlidesLoaded = function() {
show._visible = true;
show.beginTransitions();
};
this.onShowOver = function() {
};
pausa_mc.onRelease = function() {
// if playing
if (this._currentframe == 1) {
this.gotoAndStop("stopped");
// para a imagem no slide atual
show.stopTransitions();
// certifique-se que a imagem atual está indicando alpha 100
for (var t = 0; t<pic_arr.length; t++) {
if (t == currentSlide) {
show["slide"+t]._alpha = 100;
} else {
show["slide"+t]._alpha = 0;
}
}
// if parado
} else {
// começa acima transições do slide atual
this.gotoAndStop("playing");
show.activateInSeq(currentSlide);
}
};
Adv Actionscript: Calling Functions From Array Or XML
The question is twofold. I've written a group of functions. I want to call the functions based off of entries in an xml file. So, XML 1 will call function 4. XML 2 will call function 1, etc...
What happens is this, the string in the xml file relates to a function in my actionscript, however Flash is only recognizing the string as a string, and not as one of the functions in my code. I've tried strict datatyping the xml text to a variable...
Code:
var functionname:Function = xmlNode.childNodes...nodeValue
I then push the variable to an Array, and call the element in the array on a button click. If I trace my variable, it has the same name as my function, but my function isn't running
...2nd part, Other languages have what's called "collections"...for example, when compiling in .Net, or a similar language, I can use a global "collection" reference to access any of the function written in the code. Does Actionscript have a similar reference? (not only for functions, but for say Movie Clips, images, sounds, etc)
thnx,
-j
ActionScript 2.0 - MovieClip Events As Class Functions
Hi
I was wondering if you code help me out with Actionscript 2.0 and classes.
I have built a movie which has some nested movies within. I have created a class called ButtonMc in a .as file and used linkage to connect the symbol in the .FLA file with the class code in the ButtonMc.as file . This is the code for ButtonMc class:
Code:
class ButtonMc extends MovieClip
{
//stores the MovieClip Instance which will be assigned to this class
private var mcButton:MovieClip;
/* Constructor - takes in the movieclip*/
public function ButtonMc(mcInstance:MovieClip, mcInstanceName:String, mcInstanceDepth:Number, xPos:Number, yPos:Number)
{
//mcInstance will hold value "this"- which will mean a connectionwill be made
//between this objects (when created) movieclip property and the symbol in the .fla.
mcButton = mcInstance.attachMovie("ButtonMc", mcInstanceName, mcInstanceDepth);
//set the initial position of movie on stage
setPosition(xPos, yPos);
//dont display the handcursor for this movie clip
mcButton.useHandCursor = false;
//starts the onrollover event
}
/* Sets/Changes the position of the movie clip on stage*/
public function setPosition(x:Number, y:Number)
{
mcButton._x = x;
mcButton._y = y;
}
/* when mouse rolls over */
public function onRollOver()
{
mcButton.gotoAndPlay("over");
}
}
Then on my _root(main timeline) i have a action to create an instance of the the class and display the movie. I have this action:
Code:
var mc:ButtonMc = new ButtonMc(this, "mcunderstand", 0, 10, 50);
This movieclip displays when run, but nothing happens when i rollover the movieclip, it does not work and does not go to and play the specified frame for the "over" state.
Am i doing this wrong? I thought that all code related to an object would go inside the class and be ready to use?
Any help on this would be great
Thanks alot.
Why Do Button Functions Included In External Actionscript Not Persist Across Frames?
this one drives me nuts!
if i include an external actionscript file in frame one of my movie, then [as you'd expect] all the functions, global variables etc contained in that external AS file are available throughout my movie - with one notable exception.
if i add a button to the stage - in a frame other than frame one - whose onRelease handler is defined in the external AS, the function is not called when the button is clicked - i have to re-include the external AS file again on the frame in which the button resides, in order for the buttons function to be called. anyone know why this is - and if there's a way round it?
how come all the other functions in the AS persist across all frames and all timelines in the movie, but the button handlers only seem to be available on the actual frame in which the AS file is included?
download example
Edited: 01/26/2007 at 06:50:40 AM by madramadramadramadra
Dynamic Functions - Creating Functions At Runtime Without So Many Ifs/elses...
Hi, nice to register after lurking for a while and seeing how smart people are on here......
I am writing some code that needs to be very efficient, yet flexible. This is in a class and when the class gets initialized a function is setup. I want this function to run straight through without doing any time-consuming things such as calling other functions or routines, or doing any if/else logic/branching.
Now I know that you can setup a function at anytime during runtime such as:
Code:
var myFunction:Function = function() {trace('HELLO!')}
But what I am trying to do is to try and append code to a function based on logic, yet I don't want the function to be deciding this logic when it is running as it will only need deciding when the function is created.... imagine if it were a string it would be something like myFunction+="do somethingelse;" which would be the same as having initially setup myFunction as such:
Code:
var myFunction = function() {do something; do somethingelse;}
With this I seem to be having no luck
Here's an example where I setup the most compact/efficient function at runtime depending on what I want the function to do. Now this was fairly simple because when we create the function there are only a few possible variations, but I need someway of doing a function+= as my real code has quite a few variations and it would be a nightmare have a zillion if/else branches. REMEMBER I do not want any logic/decisions in the function itself as it to be the most efficient the function must be as compact as possible and run straight-through.
Code:
var dynamicFunction:Function;
//
// Setup the dynamic function & call it
// In this example outputs "Hello Jim" & "Goodbye Jim"
dynamicFunction = CrapSetupRoutine(true, true, "Jim");
dynamicFunction();
//
// Try and setup the dynamic function using a less ify/elsey (less complicated) routine & call it
// In this example it doesn't work if we try and make it say both Hello & Goodbye like above :(
dynamicFunction = SetupRoutineIWouldLike(true, true, "Jim");
dynamicFunction();
//
function CrapSetupRoutine(sayHello:Boolean, sayGoodbye:Boolean, yourName:String):Function {
var returnFunction:Function;
// Far too many ifs/elses...but remember the function created cannot have any if/else logic or calls to other functions
if (!sayHello and !sayGoodbye) {
returnFunction = function () {
trace("<dynamicFunction> sits bored");
};
} else if (sayHello and sayGoodbye) {
returnFunction = function () {
trace("Hello "+yourName);
trace("Goodbye "+yourName);
};
} else {
if (sayHello) {
returnFunction = function () {
trace("Hello "+yourName);
};
} else {
returnFunction = function () {
trace("Goodbye "+yourName);
};
}
}
return returnFunction;
}
//
//What I actually want the Setup function to resemble is this
function SetupRoutineIWouldLike(sayHello:Boolean, sayGoodbye:Boolean, yourName:String):Function {
var returnFunction:Function;
// the ifs/elses are as minimal as possible, which is good
if (!sayHello and !sayGoodbye) {
returnFunction = function () {
trace("<dynamicFunction> sits bored");
};
} else {
if (sayHello) {
returnFunction = function () {
trace("Hello "+yourName);
};
}
if (sayGoodbye) {
// the += below doesn't work.....so the question is how to append to it?????
returnFunction += function () {
trace("Goodbye "+yourName);
};
}
}
return returnFunction;
}
// The end
P.S. I knew the += would never work as this is a function and not a string. But at least if you think of the function as a string you'll get what I'm trying to do.....I suspect if it can be done it involves casting or something and maybe using strings initially??
Class Functions Not Able To See Other Member Functions/variables?
I am having a problem which has crept up on me a few times now. I am trying to call another member function within the same class, but Flash is unable to recognize it. This also happens when I try to read values of come variables.
For example, here I am trying to set the private boolean member variable to the state of the checkbox.
//NOTE: This is an EventListener. Does this change something major?
private function CheckBoxClick( evt )
{
_enabled = _root["test_sp"].content[_checkBoxName].selected;
trace( _checkBoxName + " checked: " + _root["test_sp"].content[_checkBoxName]._y );
}
This will output the following: "undefined checked: undefined"
Now in the function directly above it, I have the following function:
public function SetYPosition(pos:Number)
{
trace( _checkBoxName );
_root["test_sp"].content[_checkBoxName]._y = pos;
}
And this function will correctly output the checkbox name as well as update the position.
If I try adding the function call "SetYPosition(500);" to the first function (CheckBoxClick), the function will never be called as if Flash cannot see it.
In the past I have avoided this by using the global instance of the class such as _global.settings.function(blah), but the class I am working on now does not have a global instance.
Any ideas? This is really annoying!
Thanks!!!
Edited: 06/27/2007 at 03:30:12 PM by JoMasta
External Actionscript And Calling External Functions
I have not been able to figure out or find a good tutorial on how to use external actionscript or how to call functions located externally. What I have found in flash help and livedocs has not proved to be helpful and I have not managed to make it work. Has anybody seen anything?
Even a simple thing, such as creating an external function that tells a button to go to the next frame and how to call that in my flash file would be greatly helpful.
[F8] Running Functions From Within Functions In A Class
For some reason, whenever I try to run a private function from within another private function in a class, it doesn't work.
Code:
private function getVars(theVar) {
switch (theVar) {
case "m" :
return this.m;
break;
case "nI" :
return this.nI;
break;
case "rX" :
return this.rX;
break;
case "rY" :
return this.rY;
break;
case "cX" :
return this.cX;
break;
case "cY" :
return this.cY;
break;
case "s" :
return this.s;
break;
case "a" :
return this.a;
break;
default :
return "";
}
}
Code:
private function cSpeed():Void {
// ccX is just a placeholder for the cX variable
// so that the function can use it.
var ccX:Number = cX;
m.onMouseMove = function() {
s = (this._xmouse-ccX)/1500;
getVars("m");
}
}
I just used getVars("m") for the hell of it...just to see if it would work...but it didn't. Any idea why not?
[F8] Calling Functions Within OnEvent Functions.
Ive just stumbled upon an annoying problem, Im writing a custom class which, in its constructor attaches a movie clip to a main one (passed in as a parameter).
this all works fine.
My problem arises when i try to, also in the constructor, create an onRollOver event on the movieclip i attached earlier (its stored in a field).
The onRollOver event works fine, calling the trace statement ive been using, but it won't call any function which i ask for.
this is the code where im having issues:
Code:
function Corner(xPosition:Number, yPosition:Number, circ:Circle, deep:Number, baseClip:MovieClip)
{
this.image = baseClip.attachMovie("Corner","CornerX",deep);
this.image._x = xPosition;
this.xPos = xPosition;
this.image._y = yPosition;
this.yPos = yPosition;
this.circle = circ;
this.image.onRollOver = function()
{
trace("debugOne"); //this trace statement works fine
this.otherFunction(); //Problem is here, The code wont call this function for some reason
}
this.depth = deep;
}
function otherFunction()
{
trace("debugTwo");
}
any ideas why its not calling my function?
[F8] Functions Inside Functions? Urgent
Hi, is this in any way valid?
Code:
this.onRelease = function(){
_root.mainbutton(){
freeze == false;
}
i have a set of buttons id like to play their animations when i press a button. Can this be done?
Any help or pointers would be greatly appreciated, thanks!
Declaring Functions In Other Functions And Callbacks
Hi - I'm curious to know if the following situation is possible (I haven't gotten it to work yet).
I'd like to load a series of images, and in the callback, place them in different positions in my array. Instead of writing a separate callback for each image, I'd like to do something like the following:
But it looks like each version of the function gets the end version of "i", not the version of i that existed when the function was declared.
Is something like this at all possible?
Attach Code
public function loadImages():void
{
for (var i:int = 0; i < 4; i++)
{
function myCallback(e:Event):void
{
myArray[i] = Bitmap(e.target.loader.content);
}
loadImageWithCallback(image, myCallback);
}
}
Functions Passed As Arguments To Other Functions
FLASH MX 2004 - AS2.0
I have a function with 4 necessary arguments (aka parameters) in order to perform the actions. I would like to have the ability to pass the same function to itself as an argument (sort of like a recursive function) along with its arguments. Basically I want to "base" to engage an onMotionFinished event handler if there is another function passed as an argument. Something like...
PHP Code:
function base (arg1, arg2, arg3 arg4, {arg5:another function, arg6:arg5s arg).....}){ //do the stuff instructions = blahblahblah if (arg5 is present){ instructions.onEventHandler = function(){ //perform function which is arg5...argN } } }
Would there be a way to use listeners to do this or the AsBroadcaster? Thanks
Functions Trough Functions...
Hi, I have some problems with relative/absolute functions...
The code is:
--------Main.fla:
Code:
import Bus;
var aBus:Bus=new Bus(wooz);
function wooz()
{
trace("wooz!!");
trace(this);
}
this.onMouseUp=function()
{
wooz();
}
wooz();
aBus.TryCallback();
---Bus.as
Code:
class Bus
{
var _couleur:String;
private var _Func:Function;
function Bus(Func:Function)
{
trace("exec func...");
_Func=Func;
}
function TryCallback()
{
_Func();
}
}
I would like to have an output like this:
wooz!!
_level0
wooz!!
_level0
...But i obtain this
wooz!!
_level0
wooz!!
[object Object]
I would like to keep _level0 as this, and not object, who aBus
Can U help me please???
thanks
Trace A Functions Name From Within Functions
I am setting up a series of function. I want to use the function name as a variable inside each function like this:
var thisFunction;
function functionName(){
thisFunction = this.name
trace(thisFunction)
}
I want to set funcName to the the name of the function, someName.
Thanks in advance!
Functions Inside Functions?
Hello all -
The following code is in a external AS file that is called in the first frame of the movie. When I have it play outside of a function, it works fine. As soon as I put inside a function, it does not work. The code is
ActionScript Code:
var _mcl:MovieClipLoader = new MovieClipLoader();
var _listener:Object = new Object();
_listener.onLoadInit = function(_mc:MovieClip)
{
trace("Done loading...");
}
_mcl.addListener(_listener);
this._mcl.removeMovieClip(clip_1);
this.createEmptyMovieClip("clip_1", this.getNextHighestDepth());
_mcl.loadClip("back.swf", clip_1);
I am new to AS, so I am trying to figure out if something in this code is not allowed when I put it into a function. I tested the function using trace statements to make sure it was being called and it was, so the problem seems to lie in this code. Does anybody know why this code will not work when put in a function? Thanks!
Functions Calling Other Functions
what i need to do is call a set of functions several times in sequence with different parameters each time. here's what i've got
Code:
/////photoload code////
this.fadeSpeed = 10;
this.fadeSpeed2 = 10;
var picToLoad = "";
var whereToLoad = "";
MovieClip.prototype.changePhoto = function(ddd,whatwhat) {
this.picToLoad = ddd;
this.whereToLoad = whatwhat;
trace("this.picToLoad = ddd **** "+this.picToLoad+" + "+ddd);
trace("this.whereToLoad = whatwhat ***** "+this.whereToLoad+" + "+whatwhat);
this.onEnterFrame = fadeOut;
};
MovieClip.prototype.fadeOut = function() {
if (this.whereToLoad._alpha>this.fadeSpeed) {
this.whereToLoad._alpha -= this.fadeSpeed;
} else {
this.loadPhoto2();
}
};
MovieClip.prototype.fadeOut2 = function(xox) {
trace("fadeOut2 function called");
this.whichToFade = xox;
if (this.whichToFade._alpha>this.fadeSpeed2) {
this.whichToFade._alpha -= this.fadeSpeed2;
}
};
MovieClip.prototype.fadeOut3 = function() {
trace("this.whichToFade = "+this.whichToFade);
if (this.whichToFade._alpha>this.fadeSpeed) {
this.whichToFade._alpha -= this.fadeSpeed;
}
};
MovieClip.prototype.loadPhoto = function() {
// specify the movieclip to load images into
var p = _root.sectImg;
//------------------------------------------
p._alpha = 0;
p.loadMovie(this.pathToPics+this.pArray[this.pIndex]);
//this.onEnterFrame = loadMeter;
};
MovieClip.prototype.loadPhoto2 = function() {
// specify the movieclip to load images into
var p = this.whereToLoad;
//------------------------------------------
p._alpha = 0;
p.loadMovie(this.picToLoad);
this.onEnterFrame = loadMeter;
};
MovieClip.prototype.loadMeter = function() {
var i, l, t;
l = this.whereToLoad.getBytesLoaded();
t = this.whereToLoad.getBytesTotal();
if (t>0 && t == l) {
this.onEnterFrame = fadeIn;
} else {
trace(l/t);
}
};
MovieClip.prototype.fadeIn = function() {
if (this.whereToLoad._alpha<100-this.fadeSpeed) {
this.whereToLoad._alpha += this.fadeSpeed;
} else {
this.whereToLoad._alpha = 100;
this.onEnterFrame = null;
}
}
and then i've written the following to run the above functions:
Code:
MovieClip.prototype.controlPhoto = function(props) {
var ddd;
var whatwhat;
trace("arguments.length = " + arguments.length);
trace("props = "+props);
trace("arguments = "+arguments);
for (var cpi = 0; cpi<arguments.length; cpi++) {
trace("------ "+ cpi + " ------");
trace("arguments[cpi] = "+arguments[cpi]);
var my_array:Array = arguments[cpi];
my_array.slice();
trace(my_array[0]+" *** "+my_array[1]);
ddd=my_array[0];
whatwhat=my_array[1];
this.changePhoto(ddd,whatwhat);
}
}
and i'm calling this function like this:
Code:
curr_item.onRelease = function() {
_root.controlPhoto([this.img1,sectImg],[this.img2,leadImg]);
}
but what happens is only the last set of parameters actually get loaded. everything else seems to be skipped over. any help is appreciated!
thanks,
david
Mc Functions Inside Functions
I created an empty movie clip. The object in the clip is drawn with actionscript.
I wanted for the object to do different things when different keys were pressed. Like so:
ActionScript Code:
clip.onKeyDown = function() {if (Key.getCode() == Key.DOWN) {clip.onEnterFrame = function() {_root.callFunction();}} else if (Key.getCode() == Key.UP) {clip.onEnterFrame = function() {_root.callFunction();}}}
It's a simple example showing that the onEnterFrame function does about the same thing for each keys. Am i doing this right, or can the onEnterFrame function be defined once and i can call it from the onKeyDown function?
Thanks,
Jerome
Functions Calling Other Functions
what i need to do is call a set of functions several times in sequence with different parameters each time. here's what i've got
Code:
/////photoload code////
this.fadeSpeed = 10;
this.fadeSpeed2 = 10;
var picToLoad = "";
var whereToLoad = "";
MovieClip.prototype.changePhoto = function(ddd,whatwhat) {
this.picToLoad = ddd;
this.whereToLoad = whatwhat;
trace("this.picToLoad = ddd **** "+this.picToLoad+" + "+ddd);
trace("this.whereToLoad = whatwhat ***** "+this.whereToLoad+" + "+whatwhat);
this.onEnterFrame = fadeOut;
};
MovieClip.prototype.fadeOut = function() {
if (this.whereToLoad._alpha>this.fadeSpeed) {
this.whereToLoad._alpha -= this.fadeSpeed;
} else {
this.loadPhoto2();
}
};
MovieClip.prototype.fadeOut2 = function(xox) {
trace("fadeOut2 function called");
this.whichToFade = xox;
if (this.whichToFade._alpha>this.fadeSpeed2) {
this.whichToFade._alpha -= this.fadeSpeed2;
}
};
MovieClip.prototype.fadeOut3 = function() {
trace("this.whichToFade = "+this.whichToFade);
if (this.whichToFade._alpha>this.fadeSpeed) {
this.whichToFade._alpha -= this.fadeSpeed;
}
};
MovieClip.prototype.loadPhoto = function() {
// specify the movieclip to load images into
var p = _root.sectImg;
//------------------------------------------
p._alpha = 0;
p.loadMovie(this.pathToPics+this.pArray[this.pIndex]);
//this.onEnterFrame = loadMeter;
};
MovieClip.prototype.loadPhoto2 = function() {
// specify the movieclip to load images into
var p = this.whereToLoad;
//------------------------------------------
p._alpha = 0;
p.loadMovie(this.picToLoad);
this.onEnterFrame = loadMeter;
};
MovieClip.prototype.loadMeter = function() {
var i, l, t;
l = this.whereToLoad.getBytesLoaded();
t = this.whereToLoad.getBytesTotal();
if (t>0 && t == l) {
this.onEnterFrame = fadeIn;
} else {
trace(l/t);
}
};
MovieClip.prototype.fadeIn = function() {
if (this.whereToLoad._alpha<100-this.fadeSpeed) {
this.whereToLoad._alpha += this.fadeSpeed;
} else {
this.whereToLoad._alpha = 100;
this.onEnterFrame = null;
}
}
and then i've written the following to run the above functions:
Code:
MovieClip.prototype.controlPhoto = function(props) {
var ddd;
var whatwhat;
trace("arguments.length = " + arguments.length);
trace("props = "+props);
trace("arguments = "+arguments);
for (var cpi = 0; cpi<arguments.length; cpi++) {
trace("------ "+ cpi + " ------");
trace("arguments[cpi] = "+arguments[cpi]);
var my_array:Array = arguments[cpi];
my_array.slice();
trace(my_array[0]+" *** "+my_array[1]);
ddd=my_array[0];
whatwhat=my_array[1];
this.changePhoto(ddd,whatwhat);
}
}
and i'm calling this function like this:
Code:
curr_item.onRelease = function() {
_root.controlPhoto([this.img1,sectImg],[this.img2,leadImg]);
}
but what happens is only the last set of parameters actually get loaded. everything else seems to be skipped over. any help is appreciated!
thanks,
david
Using Functions To Define Functions
Hi all,
I'm trying to recode an MX script to F5, and its not working.
on a mc 'mcGoalie' i have the code;
onClipEvent(enterframe){
this.moveGoalie';
}
on root timeline:
function moveGoalie(){
....
}
so at the beginning, the prototype is not defined, so nothing happens.
then on a button (to start the game) i have the code
on(press){
Movieclip.prototype.moveGoalie=_root.moveGoalie();
}
then to stop
on(press){
Movieclip.prototype.moveGoalie=undefined;
}
which works.
problem is, i want a general startGame function to get everything going.
function startGame(){
Movieclip.prototype.moveGoalie=_root.moveGoalie();
}
then on start button
on(press){
_root.startGame();
}
which doesn't work.
can use use functions (here startGame) to define other functions and Movieclip prototypes? if not anyone know of a work around?
cheers
s[H]ura
Functions
Can functions be "called" in frames? I've experimented with "calling" functions within buttons...no prob there, but if I want to "call" it in the last frame of a clip, for example, will it work?
red penguin
A Bit Of Help With Functions
hey all, i was wondering if anyone knew the easiest way to make "global" functions
ones that i could access from any movie clip, at anytime
i tried putting them all in a movie clip but i couldn't get them to execute right after.
Fun With Functions
I'm relatively new to this actionscript malarky, and am having a bit of trouble with functions: I want to be able to reference a number of instances with one 'word'. I presume to do this with functions rather than a variable. Any help may or may not be financially rewarded! M
Functions
Hi! long time no word but now I'm back
Have a question - how to delcare and call functions in Flash? I guess functions are useful just like in C or Pascal... so I want to use them... please give me some directions.
Thanks in advance....
Star
Functions
when you define a function from a movie clip, can you use it on all levels or just that specific mc?
Key Functions? Please Help.. 911
First off, thank you for any replys.
I am creating a Flight Sim, and using flash for a little bit of it. I need to know if it is possible to use a JoyStick with Flash.. Kinda like on key press, but with a Joystick. It there AS or anything to do this?? Maybe a plugin? Or would I have to use like VB6 or something?
Also, How do you do object collision? to where if something moves over another thing it performs an action. Like on MouseOver, but when you move a MC with Keys or JS.. so like... on MC over. So when the MC goes over a button it does something? Any ideas? Thank's for everything guys!
-Paradoxz
|