PDA

View Full Version : addChild from within function



superbungalow
June 2nd, 2007, 07:39 AM
Hi,
I am new to AS3, but in the past I have use the constructor class to draw a circle, using this code:

package {
import flash.display.*;
public class snake extends MovieClip {
public var mc1:MovieClip = new MovieClip();
public function snake() {
mc1.graphics.lineStyle(1);
mc1.graphics.beginFill(0xff0000);
mc1.graphics.drawCircle(20,20,40);
this.addChild(mc1);

}
}
}

and then in frame in the document class, "snake" ( I am trying to make a basic snake game at the moment, but haven't got very far) and I found that that would draw the circle using the constructor.

Now I want to know, how would I call that through a non-constructor.I would like to do something like:
var snakeone:snake: = new snake;
snakeone.displaycircle();

in the actions of frame one, but I can't seem to get that to do anything if I rename he function. What am I doing wrong? DO I need to set the document class as something different?

All help appreciated - I am really new at this.

julcan
June 2nd, 2007, 10:12 AM
You could define the function displaycircle inside of the class definiton.



package {
import flash.display.*;
public class snake extends MovieClip {
public var mc1:MovieClip = new MovieClip();
public function snake() {

}
public function displaysnake() {
mc1.graphics.lineStyle(1);
mc1.graphics.beginFill(0xff0000);
mc1.graphics.drawCircle(20,20,40);
this.addChild(mc1);
}
}
}



Inside your main timeline, you could then use something like:



var snakeone:snake = new snake();
snakeone.displaysnake();
addChild(snakeone);

superbungalow
June 2nd, 2007, 11:35 AM
That is what I thought, but it just doesn't do anything. No errors or anything like that, but no display on the stage. Any ideas?

julcan
June 2nd, 2007, 12:22 PM
I forgot to mention that you have to add the instance of your Snake class (snakeone) to the main timeline using addChild(snakeone) or something similar.

(see edit above)