Creation of a platform game using FlashPunk – step 2

Read all posts about "" game

Let’s add some new features to the FlashPunk platformer prototype we discussed last week.

This time we’ll add sprite maps and double jump. Uh… and this time I will be using Flash Builder 4 rather than Flash Professional CS5.5

Sprite maps

Sprite maps or sprite sheets are single images which includes all the frames needed to display a character.

This picture should give you an idea of what I am talking about:

On the left of the image, we can see all the frames of Princess Zelda animation. FlashPunk can import and use such sprite maps to animate Entities.

Remember: ripping sprite maps is not legal as it infringes copyright. That’s why I am using this awesome sprite map:

This absolutely fantastic sprite map features two images: one for the player going left, and one for the player going right. There’s not that much to draw as the main concept can be explained just with this couple of frames.

The code

There’s nothing much to change from the previous step, so we just need to add a line to the main class flashpunk:

package {
	import net.flashpunk.Engine;
	import net.flashpunk.FP;
	[SWF(width="640",height="480",frameRate="60")]
	public class flashpunk extends Engine {
		public function flashpunk() {
			super(640,480,60,false);
		}
		override public function init():void {
			FP.screen.color = 0x222233;
			FP.world=new theWorld();
		}
	}
}

At line 4 I am declaring export options as I can’t set them from the Flash IDE (remember I am using Flash Builder 4).

The interesting part comes with thePlayer class:

package {
	import net.flashpunk.Entity;
	import net.flashpunk.FP;
	import net.flashpunk.graphics.Image;
	import net.flashpunk.graphics.Spritemap;
	import net.flashpunk.utils.Input;
	import net.flashpunk.utils.Key;
	public class thePlayer extends Entity {
		private var power:Number=0.2;
		private var jumpPower:Number=10;
		private var hFriction:Number=0.95;
		private var vFriction:Number=0.99;
		private var xSpeed:Number=0;
		private var ySpeed:Number=0;
		private var gravity:Number=0.3;
		private var isJumping:Boolean=false;
		private var doubleJump:Boolean=false;
		[Embed(source='assets/player.png')]
		private const PLAYER:Class;
		private var playerSprite:Spritemap = new Spritemap(PLAYER,13,26);
		public function thePlayer() {
			setHitbox(13,26);
			x=305;
			y=225;
			playerSprite.add("goingLeft",[0],1,false);
			playerSprite.add("goingRight",[1],1,false);
			graphic=playerSprite;
		}
		override public function update():void {
			var pressed:Boolean=false;
			if (Input.check(Key.LEFT)) {
				xSpeed-=power;
				pressed=true;
			}
			if (Input.check(Key.RIGHT)) {
				xSpeed+=power;
				pressed=true;
			}
			if(!Input.check(Key.UP) && isJumping){
				doubleJump=true;
			}
			if(Input.check(Key.UP) && doubleJump && isJumping){
				ySpeed=-jumpPower;
				isJumping=false;
				doubleJump=false;
			}
			if (collide("wall",x,y+1)) {
				ySpeed=0;
				isJumping=false;
				if (Input.check(Key.UP)) {
					ySpeed=-jumpPower;
					isJumping=true;
				}
			} else {
				ySpeed+=gravity;
			}
			if (Math.abs(xSpeed)<1&&! pressed) {
				xSpeed=0;
			}
			xSpeed*=hFriction;
			ySpeed*=vFriction;
			moveBy(xSpeed,ySpeed,"wall");
			if(xSpeed>0){
				playerSprite.play("goingRight");
			}
			if(xSpeed<0){
				playerSprite.play("goingLeft");
			}
		}
		override public function moveCollideX(e:Entity):void {
			xSpeed = 0;
		}
		override public function moveCollideY(e:Entity):void {
			ySpeed = 0;
		}
	}
}

Let's see what's interesting in it:

Lines 2-7: import required classes. Look at line 5 which imports Spritemap class used to handle sprite maps.

Lines 16-17: variables to see if the player is jumping and if it can perform a double jump.

Line 20: defines a new sprite map on the PLAYER class (image). Look at the arguments: we have the source, and the tile width and height, both in pixels. This way our player.png image is divided into tiles of 13x26 pixels. As in an array, the first tile has index 0, the second has index 1, and so on.

Lines 25-26: add method adds an animation to the sprite map. The arguments are the name (a string), the frames (in this case each animation has only one frame), the frame rate (which is not important in this case as we only have one frame), and a Boolean variable to tell FlashPunk if the animation should loop (not important in this case).

We have successfully defined goingLeft and goingRight animations.

I'll skip all the double jump feature as it's only an if-then-else and has nothing to do with FlashPunk.

Look at line 62 how the player is moved with moveBy method using xSpeed and ySpeed as horizontal and vertical offsets and checking for collisions with wall group.

This single line replaces the whole moving routine I showed you in previous step and has been told me by Chevy Ray Johnston (FlashPunk's author) itself so you can trust this way of moving entities!

Lines 63-68: show the proper animation according to player horizontal movement.

Lines 70-75: overriding moveCollideX and moveCollideY functions allows me to do something when the player hits a wall while moving horizontally or vertically. In my case, I set the speed to zero.

And this is the result:

Move the player with arrow keys and see how it changes appearance as it moves left or right. To perform a double jump, press UP arrow while the player is already jumping.

Download the source code, ready to be imported into Flash Builder 4, libraries and assets included.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

215 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stairs
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers