Be a Supporter!
Inglor
Inglor
  • Member since: Jan. 26, 2003
  • Offline.
Forum Stats
Member
Level 17
Blank Slate
AS: Functions Jun. 29th, 2005 @ 05:32 PM Reply

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

KJDunwoody
KJDunwoody
  • Member since: May. 9, 2004
  • Offline.
Forum Stats
Member
Level 28
Blank Slate
Response to AS: Functions Jun. 29th, 2005 @ 05:35 PM Reply

Cool nice work.

Inglor
Inglor
  • Member since: Jan. 26, 2003
  • Offline.
Forum Stats
Member
Level 17
Blank Slate
Response to AS: Functions Jun. 29th, 2005 @ 05:39 PM Reply

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

T-H
T-H
  • Member since: Jan. 7, 2004
  • Offline.
Forum Stats
Member
Level 40
Blank Slate
Response to AS: Functions Jun. 30th, 2005 @ 09:17 AM Reply

Can you add a bit on the-

onClipEvent = function{
doStuff();
}

-command methods?

Inglor
Inglor
  • Member since: Jan. 26, 2003
  • Offline.
Forum Stats
Member
Level 17
Blank Slate
Response to AS: Functions Jun. 30th, 2005 @ 09:29 AM Reply

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

Inglor
Inglor
  • Member since: Jan. 26, 2003
  • Offline.
Forum Stats
Member
Level 17
Blank Slate
Response to AS: Functions Jun. 30th, 2005 @ 03:33 PM Reply

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 ;)

Rustygames
Rustygames
  • Member since: May. 7, 2005
  • Offline.
Forum Stats
Member
Level 19
Programmer
Response to AS: Functions Jul. 22nd, 2005 @ 10:09 AM Reply

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

dELtaluca
dELtaluca
  • Member since: Apr. 16, 2004
  • Offline.
Forum Stats
Member
Level 20
Blank Slate
Response to AS: Functions Jul. 23rd, 2005 @ 01:13 PM Reply

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;


using ShamelessPlug; NapePhysicsEngine.advertise();

BBS Signature
Glaiel-Gamer
Glaiel-Gamer
  • Member since: Dec. 28, 2004
  • Offline.
Forum Stats
Member
Level 28
Game Developer
Response to AS: Functions Jul. 23rd, 2005 @ 01:28 PM Reply

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?

dELtaluca
dELtaluca
  • Member since: Apr. 16, 2004
  • Offline.
Forum Stats
Member
Level 20
Blank Slate
Response to AS: Functions Jul. 23rd, 2005 @ 01:31 PM Reply

you could use with

ie

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


using ShamelessPlug; NapePhysicsEngine.advertise();

BBS Signature
Nemo
Nemo
  • Member since: Jun. 13, 2003
  • Offline.
Forum Stats
Member
Level 34
Game Developer
Response to AS: Functions Jul. 26th, 2005 @ 10:53 PM Reply

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


BBS Signature
zoohl
zoohl
  • Member since: Mar. 22, 2005
  • Offline.
Forum Stats
Member
Level 05
Blank Slate
Response to AS: Functions Jul. 27th, 2005 @ 01:28 AM Reply

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?

dELtaluca
dELtaluca
  • Member since: Apr. 16, 2004
  • Offline.
Forum Stats
Member
Level 20
Blank Slate
Response to AS: Functions Jul. 27th, 2005 @ 03:54 AM Reply

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


using ShamelessPlug; NapePhysicsEngine.advertise();

BBS Signature
GeoKureli
GeoKureli
  • Member since: Apr. 1, 2003
  • Offline.
Forum Stats
Supporter
Level 19
Game Developer
Response to AS: Functions Jul. 27th, 2005 @ 04:04 AM Reply

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

zoohl
zoohl
  • Member since: Mar. 22, 2005
  • Offline.
Forum Stats
Member
Level 05
Blank Slate
Response to AS: Functions Jul. 27th, 2005 @ 11:05 PM Reply

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.

dELtaluca
dELtaluca
  • Member since: Apr. 16, 2004
  • Offline.
Forum Stats
Member
Level 20
Blank Slate
Response to AS: Functions Jul. 28th, 2005 @ 03:57 AM Reply

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


using ShamelessPlug; NapePhysicsEngine.advertise();

BBS Signature
Inglor
Inglor
  • Member since: Jan. 26, 2003
  • Offline.
Forum Stats
Member
Level 17
Blank Slate
Response to AS: Functions Jul. 28th, 2005 @ 03:58 AM Reply

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

dELtaluca
dELtaluca
  • Member since: Apr. 16, 2004
  • Offline.
Forum Stats
Member
Level 20
Blank Slate
Response to AS: Functions Jul. 28th, 2005 @ 04:14 AM Reply

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


using ShamelessPlug; NapePhysicsEngine.advertise();

BBS Signature
zoohl
zoohl
  • Member since: Mar. 22, 2005
  • Offline.
Forum Stats
Member
Level 05
Blank Slate
Response to AS: Functions Jul. 28th, 2005 @ 01:05 PM Reply

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

liam
liam
  • Member since: Dec. 11, 2004
  • Offline.
Forum Stats
Member
Level 22
Blank Slate
Response to AS: Functions Aug. 22nd, 2005 @ 07:55 AM Reply

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
liam
liam
  • Member since: Dec. 11, 2004
  • Offline.
Forum Stats
Member
Level 22
Blank Slate
Response to AS: Functions Aug. 24th, 2005 @ 08:05 AM Reply

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
JackSmack
JackSmack
  • Member since: Nov. 11, 2004
  • Offline.
Forum Stats
Member
Level 22
Game Developer
Response to AS: Functions Sep. 7th, 2005 @ 10:32 AM Reply

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
Rustygames
Rustygames
  • Member since: May. 7, 2005
  • Offline.
Forum Stats
Member
Level 19
Programmer
Response to AS: Functions Sep. 7th, 2005 @ 11:03 AM Reply

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

JackSmack
JackSmack
  • Member since: Nov. 11, 2004
  • Offline.
Forum Stats
Member
Level 22
Game Developer
Response to AS: Functions Sep. 7th, 2005 @ 11:17 AM Reply

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
JackSmack
JackSmack
  • Member since: Nov. 11, 2004
  • Offline.
Forum Stats
Member
Level 22
Game Developer
Response to AS: Functions Sep. 7th, 2005 @ 11:26 AM Reply

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
liam
liam
  • Member since: Dec. 11, 2004
  • Offline.
Forum Stats
Member
Level 22
Blank Slate
Response to AS: Functions Sep. 7th, 2005 @ 01:23 PM Reply

_root.partPower();?


Sup, bitches :)

BBS Signature
4as
4as
  • Member since: Nov. 18, 2004
  • Offline.
Forum Stats
Member
Level 20
Blank Slate
Response to AS: Functions Sep. 7th, 2005 @ 06:38 PM Reply

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

Creepy
Creepy
  • Member since: Nov. 28, 2004
  • Offline.
Forum Stats
Member
Level 07
Blank Slate
Response to AS: Functions Nov. 10th, 2005 @ 07:57 AM Reply

what does the :Void means in a function?

authorblues
authorblues
  • Member since: Jun. 21, 2005
  • Offline.
Forum Stats
Member
Level 12
Blank Slate
Response to AS: Functions Nov. 10th, 2005 @ 09:17 AM Reply

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
nacritico
nacritico
  • Member since: Oct. 3, 2005
  • Offline.
Forum Stats
Member
Level 12
Blank Slate
Response to AS: Functions Nov. 12th, 2006 @ 06:54 PM Reply

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