ActionScript 3.0: A Simple StarField

I’ve been pootlin’ about with Flash a little behind the scenes of late, just making the occasional graphical trinket, and it struck me that I hadn’t made a starfield yet in ActionScript – so I knocked together a quick and dirty one in about 20 minutes…

The “star” itself is just a really small, white circle – so small that it turns into a single-pixel block with filtering on it – you can change out the symbol to anything you like, or just draw actual points if you wanted to – I’m happy enough that the guts of it work and will leave it alone and re-use the code when I want the effect sometime…

Source code after the jump if that’s your thing…

Flash File Source Code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

stage.quality=StageQuality.MEDIUM;

varstarVect:Vector.<Star>=newVector.<Star>;

varmotionPaused:Boolean=true;

stage.addEventListener(MouseEvent.CLICK,addStars);

varbanner:MessageBanner=newMessageBanner();

banner.x=stage.stageWidth/2;

banner.y=stage.stageHeight/2;

addChild(banner);

functionaddStars(e:MouseEvent):void

{

// If we're currently paused...

if(motionPaused==true)

{

// Flip the pause flag

motionPaused=false;

// Remove the banner from the stage

removeChild(banner);

for(varloop:int=0;loop<400;loop++)

{

vartempStar:Star=newStar(this.stage);

starVect.push(tempStar);

addChild(starVect[loop]);

}

}

else// If we're currently playing...

{

// Flip the pause flag....

motionPaused=true;

// Put the banner back on the stage

addChild(banner);

// And remove all the stars

while(starVect.length>0)

{

starVect[0].starDestructor();// Unbind the event listener for the star...

removeChild(starVect[0]);// ...then remove it from the stage...

starVect.splice(0,1);// ... and finally from the vector.

}

}// End of else condition

}// End of addStars function

Star Class Source Code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

package

{

import flash.display.Sprite;

import flash.events.Event;

import flash.display.Stage;// Used to pass the main stage to the constructor