First, let's do code in the timeline:
NOTE: Ball1 is positioned in the center of the stage based on the height and width of the stage divided by two. The other ball is positioned in the center of the stage horizontally and above the other ball vertically.
Now, let's create the code in a class file to do the same thing:
package { import flash.display.* public class BallsOnStage extends Sprite { public function BallsOnStage () { var Ball1:Ball = new Ball(); Ball1.x = stage.stageWidth / 2; Ball1.y = stage.stageHeight / 2; addChild (Ball1); var Ball2:Ball = new Ball(); Ball2.x = stage.stageWidth / 2; Ball2.y = stage.stageHeight / 2 - 100; addChild (Ball2); } } }
Like the "Hello, World" example, another common tradition for new programmers is to create objects randomly on the stage.
package { import flash.display.*; import flash.geom.ColorTransform; import flash.events.Event; import flash.events.MouseEvent; public class MultipleBallsOnStage extends Sprite { private var ball:Ball; private var changeColor:ColorTransform; public function MultipleBallsOnStage () { stage.addEventListener (Event.ENTER_FRAME, onCreateBalls); } private function onCreateBalls (eventObject:Event):void { for (var i:uint =0; i<50; i++) { //Create ball ball = new Ball(); //Change some properties randomly ball.x = Math.random() * stage.stageWidth; ball.y = Math.random() * stage.stageHeight; ball.scaleX = ball.scaleY = Math.random(); ball.alpha = Math.random(); //Changing color is a little more complex changeColor = new ColorTransform(); changeColor.color = Math.random() * 0xFFFFFF; transform.colorTransform = changeColor; //Display ball addChild (ball); } //Remove EventListener right after loop is completed. Otherwise, it would continue to execute. stage.removeEventListener (Event.ENTER_FRAME, onCreateBalls); } } }