Code a Sonic Infinite Runner Game in JavaScript - JS GameDev Tutorial

3 min read 1 year ago
Published on Aug 29, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, we will guide you through the process of coding an infinite runner game inspired by Sonic using JavaScript. This step-by-step guide is perfect for beginner to intermediate developers looking to enhance their game development skills. By following these instructions, you'll learn how to set up your project, load assets, create game scenes, and implement gameplay mechanics.

Step 1: Project Setup

  1. Create a new project directory on your computer.
  2. Inside this directory, create the following files:
    • index.html
    • style.css
    • game.js
  3. Link your JavaScript and CSS files in the index.html:
    <link rel="stylesheet" href="style.css">
    <script src="game.js" defer></script>
    
  4. Set up a basic HTML structure for your game:
    <body>
        <canvas id="gameCanvas"></canvas>
    </body>
    

Step 2: Loading Assets

  1. Download game assets from the provided GitHub repository.
  2. Place the assets in a folder named public in your project directory.
  3. Use JavaScript to load images and sounds:
    const images = {};
    function loadImage(src) {
        return new Promise((resolve) => {
            const img = new Image();
            img.src = src;
            img.onload = () => resolve(img);
        });
    }
    async function loadAssets() {
        images.sonic = await loadImage('public/sonic.png');
        // Load other assets similarly
    }
    

Step 3: Making The Main Menu Scene

  1. Create a function to draw the main menu:
    function drawMainMenu() {
        // Draw menu background and buttons
    }
    
  2. Set up event listeners to start the game when the player clicks a button.

Step 4: Creating The Sonic Game Object

  1. Define the Sonic character as an object:
    const sonic = {
        x: 50,
        y: 150,
        width: 50,
        height: 50,
        draw() {
            ctx.drawImage(images.sonic, this.x, this.y, this.width, this.height);
        }
    };
    

Step 5: Making The Game Scene

  1. Create the game loop:
    function gameLoop() {
        clearCanvas();
        sonic.draw();
        requestAnimationFrame(gameLoop);
    }
    
  2. Initialize the game scene by calling loadAssets() and starting the game loop.

Step 6: Implementing Sonic Gameplay

  1. Add keyboard controls to move Sonic:
    window.addEventListener('keydown', (event) => {
        if (event.key === 'ArrowRight') {
            sonic.x += 5; // Move Sonic to the right
        }
    });
    
  2. Implement jumping mechanics by adjusting Sonic's y position.

Step 7: Implementing Enemy Logic

  1. Create enemy objects with properties and methods for movement:
    const enemies = [];
    function spawnEnemy() {
        enemies.push({ x: 800, y: 150 }); // Example enemy position
    }
    
  2. Update the game loop to draw enemies and check for collisions with Sonic.

Step 8: Implementing Ring + Score Logic

  1. Create a score variable and display it on the screen:
    let score = 0;
    function drawScore() {
        ctx.fillText(`Score: ${score}`, 10, 20);
    }
    
  2. Implement logic to collect rings and update the score when Sonic touches them.

Step 9: Making The Game Over Scene

  1. Create a function to display the game over screen:
    function drawGameOver() {
        ctx.fillText("Game Over", canvas.width / 2, canvas.height / 2);
    }
    
  2. Set up conditions to transition to the game over scene when Sonic collides with an enemy.

Step 10: How To Build The Game For Distribution

  1. Ensure your game code is clean and well-structured.
  2. Use a tool like Webpack to bundle your files for deployment.
  3. Upload your game to platforms like Itch.io for others to play.

Conclusion

You've successfully created a Sonic-inspired infinite runner game using JavaScript. This tutorial covered project setup, asset loading, scene creation, and gameplay mechanics. You can enhance your game by adding more features like power-ups or additional levels. Explore the provided resources for more in-depth learning and consider sharing your game with the community!