The com.codename1.gaming.platformer package is a complete engine for side-scrolling platformers. It has a character controller with slopes and one-way floors, a list of abilities such as jump, wall jump, dash and swim, level pieces such as coins, doors, springs and enemies, and a view that draws it all in 2D or in 2.5D. This chapter builds up a game one piece at a time. Each section has a diagram, and the last part tours four finished games that use the engine.

The level code on the left and the running game on the right

The classes live in two packages:

  • com.codename1.gaming.platformer is the simulation: the world, the tiles, the actors, the abilities, the pieces, recording and replay.

  • com.codename1.gaming.platformer.view draws the simulation and reads input: PlatformView, the camera, the art, the importers and the input mappers.

The simulation and the view

The engine is split in two halves, and the split is the most important idea in this chapter.

The simulation package on the left and the view package on the right with input state and events between them

The simulation knows nothing about the screen. It never reads a clock, never uses float or double and never calls Math.random. Three rules make it deterministic:

  • Fixed point. Every position and speed is an int in 16.16 fixed point. Fx.ONE is one pixel, Fx.of converts whole pixels and Fx.mul and Fx.div multiply and divide. Integer math gives the same answer on every CPU, while floating point can differ in the last bit.

  • A fixed tick. PlatformWorld.step advances the world by exactly one tick, and a second is always 60 ticks.

  • A seeded random source. Anything random, such as a generated level, draws from the world’s Rng, which starts from a seed you pass in.

int speed = Fx.ratio(3, 2);        // 1.5 pixels a tick
int pos = Fx.of(64);               // 64 pixels
pos += Fx.mul(speed, Fx.of(10));   // ten ticks later: 79 pixels
int pixels = Fx.floor(pos);

The simulation classes are marked @SharedWithBackend. The server compiles the same source, so it can replay a recorded run and get the same result as the phone. That’s what makes the leaderboards and ghosts later in this chapter trustworthy.

The view, PlatformView, steps the world 60 times a second from the player’s input and draws it at whatever rate the display runs. It interpolates between the last two ticks, so motion stays smooth on a 120 Hz screen.

What happens in one tick

PlatformWorld.step(inputs) runs the same stages in the same order every tick:

The six stages of one tick from moving platforms to the goal check

You can drive the world without any view at all. This is how tests, the server and the level solver use it:

PlatformWorld world = level.createWorld(42L);
for (int t = 0; t < 120; t++) {
    // Two seconds of holding right, with a jump on tick 30.
    int bits = Input.RIGHT;
    if (t == 30) {
        bits |= Input.JUMP;
    }
    world.step(bits);
}
int x = Fx.floor(world.getPlayer().getBody().x);
long fingerprint = world.hash();

hash() folds the whole world state into one long. Two worlds with the same hash after the same ticks are in the same state, which makes a quick check in a test.

A level is JSON

A level is plain JSON, read by LevelData.parse. The tiles are rows of characters, so a person, an editor or a language model can write one. This is the smallest playable level, shown in a PlatformView with the built-in ProceduralArt:

String json = "{\"name\":\"First steps\",\"tileSize\":16,"
        + "\"tiles\":["
        + "\"#..............#\","
        + "\"#.........====.#\","
        + "\"#.....H........#\","
        + "\"#.....H..../####\","
        + "\"################\"],"
        + "\"spawn\":[1,3],\"goal\":[14,2,1,1],"
        + "\"abilities\":[\"move\",\"ladder\",\"jump\",\"dash\"]}";
LevelData level = LevelData.parse(json);
PlatformWorld world = level.createWorld(42L);

Form form = new Form("First steps", new BorderLayout());
PlatformView view = new PlatformView(world, new ProceduralArt(level.getTileSize()));
view.setVisibleRows(12);
form.add(BorderLayout.CENTER, view);
form.show();
view.start();
Level JSON parsed into LevelData and turned into a PlatformWorld

Positions and sizes are in tiles. spawn is where the hero starts, goal is the rectangle that finishes the level, abilities lists the hero’s abilities and tuning changes their numbers (see LevelData.applyTuning). platforms adds moving platforms with a path, a speed and a pause, and entities places everything else.

createWorld(seed) can be called many times. Each call gives a fresh world in its start state, which is how a retry, a replay and a ghost each get their own copy.

The tile grid

Each character in tiles is one cell of the TileGrid:

Each tile character drawn as the cell it creates

The constants are on Tile: SOLID, ONE_WAY, SLOPE_UP, SLOPE_DOWN, the four 22.5 degree slope halves, LADDER, HAZARD and WATER. Water and hazards have no collision. Water is a volume the swim ability uses, and a hazard hurts whatever touches it.

How collision works

Each actor owns a Body, a box that moves through the grid. It’s not a physics body. Each tick it’s given a velocity and moves along X, then along Y, and scans only the cells its moving edge crosses. A fast box can’t skip over a thin wall, and a box resting on the floor doesn’t jitter.

Three panels showing the X sweep then the Y sweep with slope snap and the one-way rule

After a move the body reports its contacts: isGrounded(), a ceiling and a wall on either side. The abilities read those contacts. A wall contact is what the wall jump looks for, and grounded is what the jump looks for.

Levels from the game builder

The com.codename1.gaming.level package already has a level model, GameLevel, and the game builder saves it. It isn’t the platformer’s LevelData, and the difference is deliberate. A GameLevel is authoring data for any kind of game: tile layers, elements placed at decimal positions, and a GameWorld that streams regions in and out, all turned into sprites or models. LevelData feeds a simulation that the server replays tick for tick. It holds whole tiles that carry collision meaning, and fixed-point numbers, and it never touches an image. A base class shared by the two would hold neither the sprites nor the decimal positions, so the two are connected by a conversion, not by inheritance.

GameLevelImport performs that conversion once, when the level loads. You name which painted assets are solid ground, one-way platforms or ladders, and which elements are the spawn, the goal, coins or enemies:

Map<String, Character> tiles = new HashMap<String, Character>();
tiles.put("grass", Character.valueOf('#'));
tiles.put("plank", Character.valueOf('='));
Map<String, String> entities = new HashMap<String, String>();
entities.put("start", "spawn");
entities.put("coin", "coin");
PlatformWorld world = GameLevelImport.toLevelData(level, tiles, entities).createWorld(seed);

Assets missing from both maps are decoration. They stay in the GameLevel for drawing and never reach the simulation.

Actors and abilities

An Actor is a body plus an ordered list of abilities. The hero is an actor and so is every enemy. An ability is a small class that reads the input bits and changes the body’s velocity or state. The stock ones are created by name through Abilities.create: move, jump, crouch, ladder, walljump, dash, jetpack, glide, swim, fly, look, weapon, sword and grip.

The twelve hero abilities in their default processing order

Order matters because each ability sees what the earlier ones did this tick. Actor.tick calls earlyProcess on every ability, then process on every ability, then applies gravity and moves the body, then calls lateProcess. An ability can claim the movement state with claimState so a later one doesn’t overwrite it.

The jump that feels right

JumpAbility has the forgiveness players expect from a good platformer:

  • Coyote time. A jump still works for coyoteTicks after the hero walks off a ledge.

  • Buffered jumps. A press up to bufferTicks before landing jumps on the landing tick.

  • Variable height. Releasing the button while rising cuts the jump short.

  • Multi-jump. maxJumps above 1 allows double jumps.

  • Drop through. Down and jump on a one-way platform falls through it.

Two timelines of ticks showing the coyote window after a ledge and the buffer window before landing

Writing your own ability

An ability extends Ability and implements process. This one makes the hero fall at a slower rate while UP is held:

/** Holding UP while airborne halves gravity: a simple float. */
public static class FloatAbility extends Ability {
    @Override
    public void process(Actor c, PlatformWorld world) {
        if (!c.getBody().isGrounded() && c.held(Input.UP) && c.getBody().vy > 0) {
            c.getBody().vy -= Fx.ratio(1, 8);
        }
    }
}
world.getPlayer().addAbility(new FloatAbility());

Keep an ability deterministic: use Fx for numbers, the world’s Rng for chance and no clock. If the ability keeps state across ticks, override hashState so hash() includes it.

Level pieces

Everything that’s not a tile or an actor is a LevelEntity. The level file places them in entities by type:

  • Pickups (Pickup): coin, gem, heart, life, key and powerup, which turns on an ability for the hero.

  • Doors and gates: a Door opens with a named key. A Gate opens when its channel is on.

  • Switches (Switch): a lever or a plate turns a channel on, and gates listen to that channel.

  • Springs (Spring): bounce the hero up with a given power.

  • Crumbling blocks (CrumbleBlock): fall a short delay after the hero stands on them and come back later.

  • Crates (PushBlock): pushed along the floor and can hold a plate down.

  • Checkpoints (Checkpoint): move the respawn point.

  • Moving platforms (MovingPlatform): follow waypoints and carry riders.

  • Enemies: actors with an AIBrain.

A type the engine doesn’t know goes to your EntityFactory, passed to createWorld(seed, factory). Hollowdeep adds its relics this way.

Enemies with AIBrain

An enemy doesn’t move itself. Its AIBrain presses buttons. Each tick the current state’s action produces Input bits, and those bits run through the same abilities and collision as the hero, so enemies are as deterministic as the player.

A patrol state and a chase state joined by distance checks
Actor slime = new Actor("slime", Fx.of(64), Fx.of(16), Fx.of(12), Fx.of(10));
AIBrain brain = new AIBrain();
AIBrain.State patrol = brain.addState("patrol", new AIBrain.Patrol());
AIBrain.State chase = brain.addState("chase", new AIBrain.Chase(true));
patrol.addTransition(new AIBrain.TargetWithin(Fx.of(96), true), chase);
chase.addTransition(new AIBrain.Not(new AIBrain.TargetWithin(Fx.of(160), false)), patrol);
slime.setBrain(brain);
world.addActor(slime);

Input, replay and verification

Input is ten bits per tick: Input.LEFT, RIGHT, UP, DOWN, JUMP, RUN, DASH, FIRE, ACTIVATE and ALT. Since the world is deterministic, a whole run is just those bits, one int per tick. An InputLog stores them and encode() turns them into compact text.

A run recorded as an InputLog then uploaded and replayed on the server

To record, set an InputSource on the view that logs what it passes on:

final InputLog log = new InputLog();
view.setInputSource(new PlatformView.InputSource() {
    @Override
    public int[] next(PlatformWorld world, int local) {
        log.add(local);
        return new int[] {local};
    }
});
// ...when the level ends, upload this text with the score:
String upload = log.encode();

On the server, Replay.run plays the log against the same level and seed and reports what happened. Accept a score only when it matches:

LevelData level = LevelData.parse(levelJson);
InputLog log = InputLog.decode(upload, 60 * 60 * 15);
Replay.Result r = Replay.run(level, seed, log);
boolean genuine = r.isComplete() && r.getTicks() == claimedTicks;

The same log drives a ghost. addGhost runs a second copy of the world from a recorded input and draws its hero faded over the live game:

InputLog best = InputLog.decode(bestRun, 60 * 60 * 15);
view.addGhost(level.createWorld(seed), best.toArray(), 110);
A phone racing a faded ghost of the best run

Proving a level can be finished

Solver searches for an input log that reaches the goal. It keeps an archive of places the hero has reached, each with the shortest input that got there, and keeps exploring from the places nearest the goal. Run it on every shipped level in a test, on a level a player made before it’s published, or to record a demo for the menu.

Solver solver = new Solver(level, 42L, 7L);
solver.setMaxTicks(60 * 120);
InputLog run = solver.solve(2000000L);
if (run == null) {
    int[] closest = solver.getClosest();
    Display.getInstance().setProperty("closest", closest[0] + "," + closest[1]);
}

The four gallery games ship demo runs found this way, and their tour test plays every demo to the end. A level edit that breaks a demo fails the test.

Drawing the world

PlatformView is a GameView that plays a world on screen. It bakes tiles into chunk images, follows the hero with GameCamera’s follow mode and turns each tick’s `WorldEvent into particles, sounds and screen shake through Feedback. A PlatformArt supplies every image. ProceduralArt draws placeholder art so a level runs before any art exists, and ActorAnimator picks the sprite animation for each movement state.

Backdrops scroll at a fraction of the camera’s speed for parallax. setDepth(true) draws the same world with a perspective camera: solid tiles become extruded blocks and actors stand up as billboards.

view.addBackground(clouds, 0.2f, 0);    // far: moves at a fifth of the camera
view.addBackground(hills, 0.5f, 40);    // nearer: half speed
view.getCamera().setDeadZone(48, 32);
view.getCamera().setLookAhead(0.2);
view.setDepth(true);                    // the same world, drawn in 2.5D
view.setDepthLook(40f, 0.25f, 1.5f);
Parallax layers at three factors next to the perspective depth camera

The simulation doesn’t know which mode is on. The same level, the same rules and the same replay work in both:

The same level drawn flat and in 2.5D

Importing art and levels

You don’t have to draw everything in code. Three importers read files from tools many 2D artists already use:

Sprite sheets and Tiled maps and glTF models each passing through an importer into the engine
  • SheetImport.read reads an Aseprite sprite sheet (a PNG and its JSON). Name each tag after a state such as idle, run or jump and the animations hook up without code.

  • TiledImport.toLevelJson turns a map from the Tiled editor into level JSON.

  • PlatformModels replaces sprites with skinned glTF models in 2.5D.

Display d = Display.getInstance();
Image sheetImage = Image.createImage(d.getResourceAsStream(null, "/hero.png"));
String sheetJson = Util.readToString(d.getResourceAsStream(null, "/hero.json"));
SheetImport hero = SheetImport.read(sheetImage, sheetJson);
// A PlatformArt answers sheet(actor) with hero.getSheet()
// and animator(actor) with hero.getAnimator().

String tmj = Util.readToString(d.getResourceAsStream(null, "/map.tmj"));
LevelData level = LevelData.parse(TiledImport.toLevelJson(tmj));
A hero sprite sheet imported from Aseprite
A level drawn in Tiled running in the engine
A glTF knight model standing in a 2.5D level

Touch, keyboard and gamepad

PlatformView reads input through an InputMapper, which maps keys and gamepad buttons to Input bits. On a touch screen, the TouchControls of GameView add an on-screen stick and buttons. For two players on one device, give each a mapper and let the camera frame both:

InputMapper p1 = InputMapper.forPlayer(0);
InputMapper p2 = InputMapper.forPlayer(1);
p1.setAlwaysRun(true);
view.setPlayerMappers(p1, p2);
view.setFrameAllPlayers(true);

scripts/platformer-gallery holds four games built on this engine. They share the simulation, the camera, the renderer and the tools. What changes between them is their level data and a few game classes. Each runs on a phone, a tablet, a desktop window and the web.

Hollowdeep is an exploration game: a connected map of rooms, relics added through an EntityFactory and counted in GameRules, a gate that opens when its sentry is shot, swimming, ladders and a minimap.

Hollowdeep with its room map and the hero in a flooded cave

Skyline Sprint is an endless runner for a phone held upright. The city is built from a seed, input is one button, and the run ends on the first hit.

Skyline Sprint running on a phone in portrait

Cliffside is the 2.5D game. setDepth turns its tile level into blocks, setDepthTextures puts the tile art on them, and PlatformModels swaps the hero for a glTF knight.

Cliffside on a tablet with a 3D knight and the gamepad overlay

Crate Duo is a two-player puzzle: "players": 2 in the level, one InputMapper per player, crates that hold plates down and a goal that needs both players at the flag.

To build a full game with menus, a level editor, leaderboards and a backend, start from Ledge. Ledge: Making the platformer your own walks through it.

A Ledge level in play