So far we have a paddle on the left, that can be moved with the UP and DOWN keys.
What if we want to add a second player? We can just make a quick modification to the MenuState.hx :
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 |
package; import flixel.FlxG; import flixel.FlxSprite; import flixel.FlxState; import flixel.text.FlxText; import flixel.ui.FlxButton; import flixel.util.FlxMath; /** * A FlxState which can be used for the game's menu. */ class MenuState extends FlxState { // class variables var paddle:Paddle; var paddle2:Paddle; /** * Function that is called up when to state is created to set it up. */ override public function create():Void { super.create(); paddle = new Paddle(10, 50); add(paddle); paddle2 = new Paddle(600, 50); add(paddle2); } /** * Function that is called when this state is destroyed - you might want to * consider setting all objects this state uses to null to help garbage collection. */ override public function destroy():Void { super.destroy(); } /** * Function that is called once every frame. */ override public function update():Void { super.update(); if (FlxG.keys.pressed.UP) { // move paddle up paddle.y -= 5; } if (FlxG.keys.pressed.DOWN) { // move paddle down paddle.y += 5; } if (paddle.y < 0) { paddle.y = 0; } if (paddle.y > FlxG.stage.stageHeight - paddle.height) { paddle.y = FlxG.stage.stageHeight - paddle.height; } } } |
Oops, for the left paddle, we’re controlling it using UP and DOWN keys. What about the right paddle? Let’s modify the code a little…
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 |
override public function update():Void { super.update(); if (FlxG.keys.pressed.W) { // move paddle up paddle.y -= 5; } if (FlxG.keys.pressed.S) { // move paddle down paddle.y += 5; } if (FlxG.keys.pressed.UP) { // move paddle up paddle2.y -= 5; } if (FlxG.keys.pressed.DOWN) { // move paddle down paddle2.y += 5; } if (paddle.y < 0) { paddle.y = 0; } if (paddle.y > FlxG.stage.stageHeight - paddle.height) { paddle.y = FlxG.stage.stageHeight - paddle.height; } if (paddle2.y < 0) { paddle2.y = 0; } if (paddle2.y > FlxG.stage.stageHeight - paddle2.height) { paddle2.y = FlxG.stage.stageHeight - paddle2.height; } } |
Now we have two paddles on the screen! Note that the code is not optimised — it’s not adhering to the DRY (Don’t Repeat Yourself) methodology, but for now it’s excusable because we’re still learning.
Now if you test the game, you will see two paddles which can be moved by the W/S and UP/DOWN keys.
Now that we have two paddles, we will need the ball. In our next post, we shall create the Pong ball, inclusive of the logic to keep the ball within the screen boundaries and for the ball to bounce off the Paddles.