How to create a starfield in 5 lines of code (or less)

I recently ported my simple starfield demo over from actionscript/flixel to haxeflixel with create success and ease.

However, there’s an even easier way with the flixel addons!

Overview

Let’s see what the final result will be like – check it out:

Now that I have your attention, let’s take a quick walk through the steps to get this starfield running:

  • Install flixel addons
  • Add flixel addons to your project – one line of code
  • Add imports to your FlxState – one line of code
  • Create your starfield – 1-3 lines of code

Install flixel addons

Type this:

haxelib install flixel-addons

Afterwards, type

haxelib list

…to see what plugins you already have installed and ready for consumption.

Add flixel addson to your project

Add the following to your Project.xml file (which should be in the root directory of your project folder:

<haxelib name="flixel-addons" />

You’ll see this listed, but commented out by default, under the “libraries” section of your xml file.

Add imports

Add the following to the top of the file where your starfield will be created and used:

import flixel.addons.display.FlxStarField.FlxStarField2D;

Create the starfield!

Now that you’re all set-up, let’s create the starfield. Here’s some simple code to create the starfield and adjust it’s speed:

var starField:FlxStarField2D = new FlxStarField2D(0 /*X*/, 0 /*Y*/, FlxG.width, FlxG.height, 300);
starField.setStarSpeed(1, 80);
		
add(starField);

Put this code somewhere in your create method and feel free to modify the star speed anytime. There is also a similarly named FlxStarField3D.

Find it on github

I posted a super small sample that you can download and use with flixel addons version 1.1.0. Have fun!

Hope that helps!



Share this post


facebooktwittergoogle_plusredditpinterestlinkedinmail

Tags: , , ,

Comments are closed.