Actionscript Tutorial: Starry Night

This is a very basic Actionscript tutorial that will show you how to make a sky full of twinkling stars. Everything for this tutorial will be done in Actionscript, using Actionscript 3.0. It is targeted at novices, but hopefully pros and newbies alike can get something from it. Make a wish on the first star you see and maybe your dreams will come true.

The first star I see tonight

First we need to make our black sky. This is going to be a black rectangle that covers the entire area of the Stage. We'll draw this using a Sprite, which is a type of object that can hold graphics, such as black rectangles. Here is how simple it is to make night.

bg = new Sprite();
bg.graphics.beginFill(0);
bg.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
addChild(bg);

The last line adds the bg Sprite to the Stage. This is what triggers the Flash player to actually render the object. Until you put this line in, bg is invisible.

Next we are going to need to draw a star. The stars are just tiny circles, so there isn't too much to drawing them. Make the star by creating a new Sprite, drawing a white circle in it with a 2 pixel radius, positioning it, then adding it to the Stage so it will be displayed. I've made the positioning random so every time you run it, your star will be in a different place. The following Actionscript is all we need to dynamically draw our star.

var star:Sprite = new Sprite();
star.graphics.beginFill(0xFFFFFF);
star.graphics.drawCircle(0, 0, 2);
star.x = Math.random() * stage.stageWidth;
star.y = Math.random() * stage.stageHeight;
addChild(star);

In all of the following examples, you can click on the image to regenerate it.

Here is the resulting dynamically created star.

The Milky Way

One star is nice and all, but what we really want is a whole sky full of stars. The Universe has bajillions of stars, but for this tutorial we'll just make 100. The nice thing about doing this in Actionscript is that we can make 200 stars just as easily. All you need to do is change one number in the code.

To make lots of stars, we put the star creation in a for loop and run it as many times as we want stars. It may surprise you just how easy it is to make lots of stars now that we know how to make just one. Here's the code with just two extra lines.

for (var i:Number = 0; i<100; ++i) {
    var star:Sprite = new Sprite();
    star.graphics.beginFill(0xFFFFFF);
    star.graphics.drawCircle(0, 0, 2);
    star.x = Math.random() * stage.stageWidth;
    star.y = Math.random() * stage.stageHeight;
    addChild(star);
}

And you've got a starry sky.

Now they say variety is the spice of life, but all of these stars are exactly the same, just in a different location. What we want to do now is make them all different sizes. I am going to vary mine between a radius of 0.25 and 1.5, but you can feel free to make yours whatever size you want. Changing the size of the stars to be random is again, very easy. We just need to change one line of code.

for (var i:Number = 0; i<100; ++i) {
    var star:Sprite = new Sprite();
    star.graphics.beginFill(0xFFFFFF);
    star.graphics.drawCircle(0, 0, ((Math.random() * 1.25) + 0.25));
    star.x = Math.random() * stage.stageWidth;
    star.y = Math.random() * stage.stageHeight;
    addChild(star);
}

Twinkle, twinkle little star

To make this starry sky even better, you can add a little twinkle effect. I've been playing around with this quite a bit to try and get just the right effect. You want them to flicker, but not too much. It is a sweet spot between not being able to notice the twinkle, to it being way too obvious and annoying.

The effect is by adding an ENTER_FRAME event handler to each star Sprite. The ENTER_FRAME event handler is a function that is called every frame of your movie. To make the stars twinkle I randomly change their their alpha and size very subtly. Also, I keep the value within a certain limit so that the stars don't disappear on me. Play around with the effect on your own to find your sweet spot.

public function Twinkle(event:Event):void {
    // get the current star to tweak
    var _self:Sprite = Sprite(event.currentTarget);

    // change the alpha and size of the star
    _self.alpha += Math.random() * 0.02 - 0.01;
    _self.scaleX = _self.alpha * 0.5 + 0.5;
    _self.scaleY = _self.alpha * 0.5 + 0.5;

    // do some bounds checking
    if (_self.alpha < 0.5) _self.alpha = 0.5;
    if (_self.alpha > 1) _self.alpha = 1;
}

To infinity and beyond

You can use this wherever you want to throw some stars into a scene. If you don't want the stars, or the night sky to cover the entire stage, simply change the bounds from the stage.stageWidth and stage.stageHeight to whatever you want them to be. Or put other elements on top of this, like mountains, or a cityscape or whatever you feel like. The possibilities are as numberless as the stars (sorry, that was really pathetic).

Feel free to download the full source files used to make this. Included is a bonus full screen enabled version. Now that's exciting!

And that's the end of our tutorial. Hope you enjoyed your stay. Feel free to leave any comments or questions you have. Thanks!

This entry was posted in actionscript, Flash, Flex, Tutorials and tagged , , , , , , , . Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Mark

    Hey,

    I’m quite new to actionscript… i managed to get up to the stage of making them twinkle, but get an error “The Public attribute can only be used inside a package…”
    How can i use your twinkle effect from within a flashfile?
    Please excuse my new-ness, but it took me a while to get this going. Was getting errors from the first line until i added var bg; to the very first line.

    This effect is perfect for what i’m after and no other online look any good. Would really appreciate your help
    Thanks
    Mark

  • http://orangeSPLoTCH.com mattc

    I believe there are two ways to fix the error you are getting. Either you can put a package wrapper around your code, or simply remove the public keyword from the beginning of the function. Shoot me an email if you continue to have problems.

  • Cagkan

    Hello,

    This is exactly what i am looking for. Thanx for nice tutorial. But i do not know what the action script is and how can i use it. Sorry but i am very new to flash things. When i put codes in a time line it gives errors. Can you help me how to do it?

    • http://orangeSPLoTCH.com mattc

      Glad you enjoyed the tutorial. If you can shoot me an email with the errors you are getting, I’ll see if I can help out.

  • http://www.tp-portfolio.com TP

    ok, I thought this was going to be easy, but I’m having problems with the code. This is the error I am getting. 1120: Access of undefined property bg. Please help.

  • http://orangeSPLoTCH.com mattc

    Before you can use a variable, such as bg, you must declare it. In this case you’ll need to add the following code before bg is used:
    var bg:Sprite

    Please refer to the source files to see the full actionscript that I used to create the stars. If you still have problems or questions, feel free to email me.

  • Hussain

    Works like a treat, ive been trying to do this for a while now. I could give u a hug :-)

  • Tom

    1037:Packages Cannot be nested
    for Fullscreen as file.

    Adove Flash cs3

    It is not nested, why is the compiler confused

  • Tom

    Got by the nested by using
    import FullscreenStarryNight;
    var FullscreenStarryNight:FullscreenStarryNight = new FullscreenStarryNight();

    Now compiler complains 1180 call to a possibly undefined method Star

  • Tom

    Cured 1180 error by setting off strictmode.
    The real offending code is
    var curStar:Star;

    ERROR 1046: Tye Was not found, or was not a comile time constant.

    Since the script does not work with version 3 I am rewriting it from scratch, will repost it for your readers should they want one that works with current technology

  • http://orangeSPLoTCH.com mattc

    @Tom: This code was written to be compiled as is using the Flex compiler. To use it in Flash you’ll need to delete the ‘package {‘ from the beginning and the closing ‘}‘ from the end. When you put the code directly into a Flash file it automatically (and secretly) puts a package wrapper around it for you. That’s why you were getting the initial 1037 error.

    As for the Star error, it looks like the compiler is not able to locate the Star.as file. You’ll need to make sure the file is in a location that the Flash compiler can find it. I apologize as I don’t know exactly where you can put it off-hand. Usually if it is in the same directory as the file you are creating, it is able to find it. Feel free to contact me offline if you continue to have issues with it. I’d love to get a Flash 3 .fla download for others to use if you happen to put one together.

    Thanks.

  • Cy

    Very cool! Thanks for posting this tutorial!

  • http://www.pickatutorial.com Raja Jee

    Thanks for such a useful tutorial.