00:00
00:00
Newgrounds Background Image Theme

pixiesweetheart7 just joined the crew!

We need you on the team, too.

Support Newgrounds and get tons of perks for just $2.99!

Create a Free Account and then..

Become a Supporter!

AS: Functions

9,690 Views | 34 Replies
New Topic Respond to this Topic

AS: Functions 2005-06-29 17:32:38


AS: Main
---------------------------

I wanted to make a section about recursive function calling, but I've decided I have to make one on functions first.

There are four types of programming

simple programming
procedural programming which we will now discuss
modular programming
object oriented programming (tutorial coming later

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

The idea behind procedural programming is that there are several actions that we wish to repeat more then once during our movies. Lets say for example we have the code:

if ((rot<0) && (rot>-180)) {
rot *= -1;
} else if (rot>0) {
rot = 180-rot;
rot += 180;
}

for those of you experianced with roation, this might seem fermiliar, it converts flash rotation to workable rotation (for trig functions)

now lets say we want the player to have this code, the player's turret to have this code, and the player's second turret to have this code.

without functions we would have to have the same unreadable code 3 times, with functionswe can save that.

another issue is readability, with functions your code could look like this

onClipEventLoad(){
initLocation();
initScore();
}
onClipEvent(enterFrame){
move();
if(attacking()==true){
attack();
}
checkHP();
}

isn't that nifty ;)?
---------------------

Actual use, a function and a procedure are different in 1 thing, a function has a return value, for example the hitTest function is a function because it returns either true or false, but trace is a procedure because it does not return anything.

Full function structure

function functionName(param:Type,param2:Type....paramN:Type):returnType{
//code
return returntType;//if there is no return type, no return command is needed
}

Patrial function structure

function functionName(param1,param2,param3....paramN){
//code
return anything; //return is optional
}

There is a third type called methods, they are very similar to functions only they work on the containers variables, in functions each variable you declare is a LOCAL VARIABLE, meaning you'll only have access to it within the function, and the local vars only have access to params and otehr local vars (and superglobals).

In methods however you use the this. expression to act using the container's properties, remmember, any param you change inside a function will not change outside of it.

I recommand the full decleration over the partial one, but it's only smart debugging wise.

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

Examples:

procedure:

function setStageAlpha(alpha:Number):Void{
_root._alpha=alpha;
}

function trace7times(expression:String):Void{
for(var i:Number=0;i<7;i++){
trace(expression);
}
}

function:

function toStringAdd(num1:Number,num2:Number,num3:Number):String{
return "The result is: " (num1+num2+num3);
}

function add(num1:Number,num2:Number):Number{
return num1+num2;
}

function isDownBoth(key:Number,key2:Number):Boolean{
return Key.isDown(key) && Key.isDown(key2);
}

methods example:

function moveX(){
if(Key.isDown(Key.RIGHT)){
this._x+=5;
}else if(Key.LEFT)){
this._x-=5;
}
}

functions may also call other functions, as long as they are in the same container...

ask any questions here

Response to AS: Functions 2005-06-29 17:39:59


thanks, it's always nice to get good critisizm ;)

Response to AS: Functions 2005-06-30 09:17:58


Can you add a bit on the-

onClipEvent = function{
doStuff();
}

-command methods?

Response to AS: Functions 2005-06-30 09:29:40


At 6/30/05 09:17 AM, T-H wrote: Can you add a bit on the-

onClipEvent = function{
doStuff();
}

-command methods?

sure

a container such as _root or a movieclip (in it's frame actions more usefully) has handlers like onPress onEnterFrame and onLoad that trigger when they should thanks to flash's complex triggering system.

now, let's split this to 2 things:

1)the unnamed function()

2)the handlers

when you type
function(params:Type):RetType{
//do stuff
}
flash declares an unnamed function, a function with some random name with the return type actions and params you specified

you can theoretically do
fname=function(){
trace("lolk");
}

and then type fname() (i don't reccomand it)

now for the handlers,

basically you could write a function, call it funame and then go

this.onEnterFrame=funame();

but since ususally each enter frame has different actions then the other, it's ususally done

this.onSomeTrigger=function(){
//actions here
}

note it's good to use it since you'll be able to use
delete this.onSomeTrigger;
afterwards

now there is one trick that YOU MUST REMMEMBER

when accessing the variables/properties of the movieclip/object your'e onSomeTriggering always use this. otherwise it will use the variables of the location you declared the onSomeTrigger in instead of the variables of the location it is onSomeTriggering

useful triggers

onEnterFrame
onKeyDown
onKeyUp
onUnload
onMouseDown
onPress

and so on

remmember that onPress has the REVERSE DEPTH CHECK as on(release) it will check objects below before objects above ;)

hope this helped

Inglor

Response to AS: Functions 2005-06-30 15:33:42


a useful distance function :P

function distance(mc:MovieClip):Number{
return sqrt((mc._x-this._x)*(mc._x-this._x)+(mc._y-thix._y)*(mc._y-thix._y));
}

place it onClipEvent(load) actions of a movieclip, and check it's distance from other movieclips ;)

Response to AS: Functions 2005-07-22 10:09:02


At 6/30/05 03:33 PM, Inglor wrote: a useful distance function :P

function distance(mc:MovieClip):Number{
return sqrt((mc._x-this._x)*(mc._x-this._x)+(mc._

y-thix._y)*(mc._y-thix._y));

}

place it onClipEvent(load) actions of a movieclip, and check it's distance from other movieclips ;)

Oh how I love pythagoras
See it does have some uses


- Matt, Rustyarcade.com

Response to AS: Functions 2005-07-23 13:13:10


At 6/29/05 05:32 PM, Inglor wrote: return returntType;//if there is no return type, no return command is needed

for good practice - if you dont have anything returned the return type should be set to Void
ie.
function helloto(name:String):Void
{
trace("hello "+name+", you smell like piss but we dont care");

also sometihng which can come very useful (but not in my example)
is using the return command to end a function for example and you didnt explain what return also does apart form returning the var.

the return command also ends the function for example (as an extension to your distance function)

function dist(m1:MovieClip, m2:MovieClip, a:Boolean):Number
{
var x:Number = m1._x-m2._x;
var y:Number = m1._y-m2._y;
var d:Number = x*x+y*y;
if (a)
{
return d;
}
return Math.sqrt(d);
}

gets the distance between m1 and m2 - if a is true then it returns the squared distance
if it isnt true (ie false or undefined) then it returns the distance

notice that the second return isnt inside of an else? you might think that it would return d and then return the sqrt(d) aswell? because the return command ends the function at that point it is not neccesary to encapsulate the second return in an else (not sure if im using the word encapsulate correctly here, infact this is the first time ive ever used it)

this also comes into another useful point: because the return command ends the function
you can also use it to end the function wherever you like - what if you have no return type or it is set to Void ? then you just call return with no data i.e. ' return; '

i cant actually think of a good example but you can think of it like the break command in a loop;

Response to AS: Functions 2005-07-23 13:28:40


I have a q.
Most of my functions look similar to this

function moveLeft(tgt){
tgt._x -= 5
}

onClipEvent(enterFrame){
_root.moveLeft(this)
}

Is there an easier way so I don't have to use tgt.everything?

Response to AS: Functions 2005-07-23 13:31:06


you could use with

ie

function moveLeft(tgt:MovieClip):Void
{
with(tgt)
{
_x -= 5;
}
}

Response to AS: Functions 2005-07-26 22:53:21


If you declare a function in the _root timline, can you call it in a child timline?


BBS Signature

Response to AS: Functions 2005-07-27 01:28:31


Question: I've noticed in my code that I cannot call recursive functions where the nested function has a variable named the same as in the parent function. The nested function overwrites the parent's variable. For instance:

When coding in C++, I like to use the same iterator in for() loops, so naturally I assume I can do that in AS:

for(i = 0; i < x; i++) {
do something here.
callFunc();
}

function callFunc() {
dosomething here.
for(i = 0; i < y; i++) {
if(blah)return;
}
}

Note that callFunc() has a for() loop with an identical iterator as the parent loop - "i". When the nested loop returns, the parent iterator "i" will be set to whatever the last "i" was in callFunc()'s nested loop. Eek!

Sooooo, I've been naming for() loop iterators differently in every loop. Get a main AS file that's over 1000 lines long, and you tend to forget what you haven't used yet. Anyway, is there any way to correct this issue? Should I be declaring the "i" as "i:Number" instead? Or am I screwed either way?

Response to AS: Functions 2005-07-27 03:54:49


thats because you are using the same variable
you should have
var i:Number;
for(i=.......... bladibla

if you declare a variable inside of the function then it is local to that function and is seperate from any other variable under the same identifier and is deleted when the function returns or ends

Response to AS: Functions 2005-07-27 04:04:37


also i dont think anyone said this already. but theres a way to check how many different variables are used
like
function actupon(a, b, c, d) {
if (arguments.length != 4) {
return;
}
}
it can be used alot of other ways too

Response to AS: Functions 2005-07-27 23:05:33


At 7/27/05 03:54 AM, dELta_Luca wrote: thats because you are using the same variable
you should have
var i:Number;

Ahhh, thanks! I'll make a habit of declaring variables with the :Type in the future to avoid these little nasties.

Response to AS: Functions 2005-07-28 03:57:03


its not the strict data typing (Object:ObjectType etc), thats just something i do for good practice, its the fact that you werent declaring it as a new local variable to the function so it was using the non local one that had already been declared

Response to AS: Functions 2005-07-28 03:58:29


it's good for many other reasons delta, in fact it's faster, smoother and allows the debugger to prompt you on type mismatch

Response to AS: Functions 2005-07-28 04:14:34


yeh, but thats included in good practice lol (well to me it is anyways)

Response to AS: Functions 2005-07-28 13:05:59


At 7/28/05 03:58 AM, Inglor wrote: it's good for many other reasons delta, in fact it's faster, smoother and allows the debugger to prompt you on type mismatch

I think when I first started using AS last year, I was surprised that I could do this:
myvar = 0; or myvar = "string"; without declaring the variable's type (at least in the main Flash app, realized right away I couldn't do that in included .as files).

A light should have gone on in my noggin': "Hey, you! Maybe you should declare things all the time!" But, it didn't, haha. Must've been broken...

Response to AS: Functions 2005-08-22 07:55:24


function say(amount:Number, a, b, c, d, e, f, g, h) {
trace(a);
if (amount == 2) {
trace(b);
}
if (amount == 3) {
trace(b), trace(c);
}
if (amount == 4) {
trace(b), trace(c), trace(d);
}
if (amount == 5) {
trace(b), trace(c), trace(d), trace(e);
}
if (amount == 6) {
trace(b), trace(c), trace(d), trace(e), trace(f);
}
if (amount == 7) {
trace(b), trace(c), trace(d), trace(e), trace(f), trace(g);
}
if (amount == 8) {
trace(b), trace(c), trace(d), trace(e), trace(f), trace(g), trace(h);
}
}

Usage

say(4, _x, _y, _xscale, _yscale);

It's a lot easier than having to put

trace(_x);
trace(_y);
trace(_xscale);
trace(_yscale);

or

trace(_x+" "+_y+" "+_xscale+" "+_yscale);

Etc.. just copy and paste the code then use say.


Sup, bitches :)

BBS Signature

Response to AS: Functions 2005-08-24 08:05:56


At 8/22/05 07:55 AM, -liam- wrote: function

Wow, was that long.. a shorter version:

function say(amount:Number, a, b, c, d, e, f, g, h, i, j, k, l, m, n) {
myArray = [a, b, c, d, e, f, g, h, i, j, k, l, m, n];
myArray.length = amount;
trace(myArray);
}

Usage, still the same..

say(2, 1, 2); will output 1 and 2..


Sup, bitches :)

BBS Signature

Response to AS: Functions 2005-09-07 10:32:12


I'm trying to make a function that will effect a base attribute... lets say

base = 1;

I would like to either add, subtract, multiply, or divide the base with a random number... I have that part working thanks to the MAN Inglor...

I'm thinking I had better make it a function though... I'm kinda lost on this point though... I am trying to get this code to work by placing it on the main timeline's first frame.

stop();

base = 1;
rand = random(10);
function partpower(){
switch (random(4)){
case 0:
base = base + rand;
break;
case 1:
base = base - rand;
break;
case 2:
base = base * rand;
break;
case 3:
base = base / rand;
break;
}
return base;
}

It's not working though when I test it, base returns 1 every time. the random+-*/ works great though. this is my first funtion I've tryed to write so I'm a little lost. If anyone could help me out I would be greatful.

Thanks.


Visit JackSmack.com and submit your Flash Games!

BBS Signature

Response to AS: Functions 2005-09-07 11:03:59


Silly boy you didnt run the function
try this
base = 1;
rand = random(10);
function partpower(){
switch (random(4)){
case 0:
base = base + rand;
break;
case 1:
base = base - rand;
break;
case 2:
base = base * rand;
break;
case 3:
base = base / rand;
break;
}
return base;
}
partpower ()
trace (base)


- Matt, Rustyarcade.com

Response to AS: Functions 2005-09-07 11:17:33


At 9/7/05 11:03 AM, Ninja-Chicken wrote: Silly boy you didnt run the function
try this
base = 1;
rand = random(10);
function partpower(){
switch (random(4)){
case 0:
base = base + rand;
break;
case 1:
base = base - rand;
break;
case 2:
base = base * rand;
break;
case 3:
base = base / rand;
break;
}
return base;
}
partpower ()
trace (base)

ok that works on the main timeline. So lets say I had an actions clip... and I create this function on the main timeline. How do I call this function and have it give each part+i different values?

LOL also it just returned "infinity" when I ran it this last time... might not be good for setting stats... lol


Visit JackSmack.com and submit your Flash Games!

BBS Signature

Response to AS: Functions 2005-09-07 11:26:20


fixed the infinity problem I forgot that random(10) starts at 0... =P so needs a +1 on the end.

anyway... I still don't get how to call funtions in clips that they are not contained in...

I made a new clip on the stage and put a dynamic text field in it.

I keep getting 1 for the base variable in the clip.

onClipEvent (load) {
base = 1;
rand = random(10)+1;

partpower()
trace (base)
}


Visit JackSmack.com and submit your Flash Games!

BBS Signature

Response to AS: Functions 2005-09-07 13:23:00


_root.partPower();?


Sup, bitches :)

BBS Signature

Response to AS: Functions 2005-09-07 18:38:38


I have mixed feeling about this tut :S

At 6/29/05 05:32 PM, Inglor wrote: functions may also call other functions, as long as they are in the same container...

huh?
onClipEvent(load) {
_root.someOtherMC.fun();
}

like this?
It works pretty well...

:you can theoretically do
:fname=function(){
:trace("lolk");
:}
:and then type fname() (i don't reccomand it)

huh ...again
and I DO reccomand it
It gives more flexibily.
you can always strict data type it, so theres no lose in speed:
var fun:Function=function(s:String):Void {//code}
and also you can do some scoping this way:
_root.someMC.fun=function() {
trace("word");
}
_root.someMC.onEnterFrame=function() {
this.fun()//output: "word"
}

Response to AS: Functions 2005-11-10 07:57:28


what does the :Void means in a function?

Response to AS: Functions 2005-11-10 09:17:44


At 11/10/05 07:57 AM, Creeepy wrote: what does the :Void means in a function?

its a return type. it means the function never returns a value, it just does a few operations and then quits.


BBS Signature

Response to AS: Functions 2006-11-12 18:54:09


stupid question here (I'm too noob) ..

_root.probability= Math.round(Math.random()*4);
var sign;
if(probability=0){
sign="miss"
}else{
if(probability<3){
_root.damage= Math.round(Math.random()*100);
enemiehealth-= _root.damage
sign= _root.damage
}else{
_root.damage= Math.round(Math.random()*100+200);
enemiehealth-= _root.damage
sign= _root.damage+"CRITICAL HIT!"}
}

This doesn't work...
My character doesn't miss nor make critical hit (he just make a hit between 1 and 100)...
why?

salu2s

Response to AS: Functions 2006-11-12 18:59:29


Good.

You forgot about Functional programming and Logic programming though. ;) Of course, those aren't possible with ActionScript anyway.


I believe that games will be as significant a new medium as the printed word ever was, and as powerful a force for change.

I am here to make that happen. Making life more fun