Now we are going to create the Pong paddle. Create a new file in the source folder and name it Paddle.hx . Now we have an empty file — how do we write Haxe code in it? You can always refer to the cheat sheet from the website, which will come in handy in the long run:
http://haxeflixel.com/documentation/cheat-sheet/
Copy the template code from the cheat sheet page for FlxSprite class, and rename the class to Paddle , as shown below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package; import flixel.FlxSprite; import flixel.FlxG; class Paddle extends FlxSprite { public function new() { super(); } override public function update():Void { super.update(); } override public function destroy():Void { super.destroy(); } } |
Important: The class name must be the same as the file name. In the case above, if the class is named Paddle , then the filename would be Paddle.hx .
When a Paddle is created, we want it to do the following things:
- Create a rectangle of arbitrary size (Width, Height) and color.
- Position it at an arbitrary location (X,Y)
- Add the paddle to the screen
So let’s first modify new() function to the following code:
1 2 3 4 5 6 |
public function new(X:Float, Y:Float) { super(X, Y); makeGraphic(3, 5, 0xFFFFFFFF); // width, height, color } |
If you’re wondering why the template function new() did not have the X and Y values — it’s because they’re optional and default to zero (as written in the API here: http://api.haxeflixel.com/flixel/FlxSprite.html). So, if we want to use our own values, we’d have to manually insert them as the function parameters.
Note that when objects are created in HaxeFlixel, they do not appear on the screen yet — you will need to add the objects by using add() . The main screen is controlled by the FlxState class — in our case, by default, the MenuState .
Now let’s go back to MenuState.hx and add the following code in the create() function — where everything is initially created when the screen appears:
1 2 3 4 5 6 7 |
override public function create():Void { super.create(); var paddle:Paddle = new Paddle(10, 50); add(paddle); } |
In the code above, we create a new paddle and set the X/Y offset values of (10, 50), then we add it to the screen. Note that the starting position (0,0) is on the top-left of the screen.
Now let’s build a game to make sure there’s no errors. While you’re in the MyFirstGamePong folder, type the following command to build your game:
1 |
lime test neko |
In a nutshell, you’ll be building a test version of a game (which will allow debugging) and you’re targeting the neko platform — a virtual application that can be emulated on both Windows and OSX. The reason we’re not building to the native Windows or OSX version is that neko builds are a lot faster.
If everything went well, you should get the following:
Congratulations, you have a paddle on the screen. In our next post, we will make the paddle movable, and within the boundaries of the screen.