The basics of infinite terrain generation for a horizontal endless runner

Read all posts about "" game

When we deal with endless runner games, where the player runs along a terrain, we can see two main concepts applied in the generation of the terrain:

The first concept wants you to create various pre-built prefabs and just randomly merge them together to create an endless environment. This is the case of Spelunky, which although is not a horizontal endless runner it’s the perfect example of what I mean.

The second concept, the one I prefer, consist in generating an endless environment from scratch, with no prefabs.

Let’s jump straight to the point and see what I built:

Do you like it? We have a series of randomly generated slopes painted over graphic objects scrolling from right to left, and reusing them once they leave the stage to the left side.

Slopes vary in width and height and are generated by a series of points interpolated by the cosine function, which is the simplest interpolation you can use to create slopes without using straight lines.

You can achieve better results by using cubic interpolation or Bezier curves but it’s not in the scope of this tutorial.

Before e talk about better ways to generate terrains, we need to make the terrain walkable by a ball/a cart/whatever, and we will require physics in order to do it.

At the moment, enjoy the simplest randomly generated terrain ever, with room for customization:

var game;

var gameOptions = {
    startTerrainHeight: 0.5,
    amplitude: 200,
    slopeLength: [100, 350],
    slicesAmount: 2,
    slopesPerSlice: 5,
    terrainSpeed: 200
}
window.onload = function() {
    let gameConfig = {
        type: Phaser.AUTO,
        backgroundColor: 0x75d5e3,
        scale: {
            mode: Phaser.Scale.FIT,
            autoCenter: Phaser.Scale.CENTER_BOTH,
            parent: "thegame",
            width: 750,
            height: 1334
        },
        scene: playGame
    }
    game = new Phaser.Game(gameConfig);
    window.focus();
}
class playGame extends Phaser.Scene{
    constructor(){
        super("PlayGame");
    }
    create(){
        this.slopeGraphics = [];
        this.sliceStart = new Phaser.Math.Vector2(0, Math.random());
        for(let i = 0; i < gameOptions.slicesAmount; i++){
            this.slopeGraphics[i] = this.add.graphics();
            this.sliceStart = this.drawTerrain(this.slopeGraphics[i], this.sliceStart);
        }
    }
    drawTerrain(graphics, sliceStart){
        let slopePoints = [];
        let slopes = 0;
        let slopeStart = 0;
        let slopeStartHeight = sliceStart.y;
        let currentSlopeLength = Phaser.Math.Between(gameOptions.slopeLength[0], gameOptions.slopeLength[1]);
        let slopeEnd = slopeStart + currentSlopeLength;
        let slopeEndHeight = Math.random();
        let currentPoint = 0;
        while(slopes < gameOptions.slopesPerSlice){
            if(currentPoint == slopeEnd){
                slopes ++;
                slopeStartHeight = slopeEndHeight;
                slopeEndHeight = Math.random();
                var y = game.config.height * gameOptions.startTerrainHeight + slopeStartHeight * gameOptions.amplitude;
                slopeStart = currentPoint;
                currentSlopeLength = Phaser.Math.Between(gameOptions.slopeLength[0], gameOptions.slopeLength[1]);
                slopeEnd += currentSlopeLength;
            }
            else{
                var y = (game.config.height * gameOptions.startTerrainHeight) + this.interpolate(slopeStartHeight, slopeEndHeight, (currentPoint - slopeStart) / (slopeEnd - slopeStart)) * gameOptions.amplitude;
            }
            slopePoints.push(new Phaser.Math.Vector2(currentPoint, y))
            currentPoint ++;
        }
        graphics.x = sliceStart.x;
        graphics.clear();
        graphics.moveTo(0, game.config.height);
        graphics.fillStyle(0x654b35);
        graphics.beginPath();
        slopePoints.forEach(function(point){
            graphics.lineTo(point.x, point.y);
        })
        graphics.lineTo(currentPoint, game.config.height);
        graphics.lineTo(0, game.config.height);
        graphics.closePath();
        graphics.fillPath();
        graphics.lineStyle(16, 0x6b9b1e);
        graphics.beginPath();
        slopePoints.forEach(function(point){
            graphics.lineTo(point.x, point.y);
        })
        graphics.strokePath();
        graphics.width = (currentPoint - 1) * -1;
        return new Phaser.Math.Vector2(graphics.x + currentPoint - 1, slopeStartHeight);
    }
    interpolate(vFrom, vTo, delta){
        let interpolation = (1 - Math.cos(delta * Math.PI)) * 0.5;
        return vFrom * (1 - interpolation) + vTo * interpolation;
    }
    update(t, dt){
        let offset = dt / 1000 * gameOptions.terrainSpeed;
        this.sliceStart.x -= offset;
        this.slopeGraphics.forEach(function(item){
            item.x -= offset;
            if(item.x < item.width){
                this.sliceStart = this.drawTerrain(item, this.sliceStart)
            }
        }.bind(this))
    }
}

The code is not commented yet, and not optimized. You may experience some lag if you turn this stuff into a landscape game, due to the large amount of points you need to generate.

Also, no physics makes this script quite useless as a game example, but this is the starting point to create a fully featured physics game with an endless scrolling environment, randomly generated.

Download the source code and wait for next step. The keyword will be: discretize.

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

214 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
// 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