DEV Community

Cover image for TCJSGame: A Complete JavaScript Game Engine Reference Guide
Kehinde Owolabi
Kehinde Owolabi

Posted on

TCJSGame: A Complete JavaScript Game Engine Reference Guide

TCJSGame: A Complete JavaScript Game Engine Reference Guide

TCJSGame Banner

Introduction to TCJSGame

TCJSGame (Terra Codes JavaScript Game) is a lightweight, easy-to-use JavaScript game engine designed for creating 2D games with HTML5 Canvas. It provides a component-based architecture, physics simulation, tilemap support, and various utilities that make game development accessible for beginners while still powerful enough for more experienced developers.

In this comprehensive guide, we'll explore all aspects of TCJSGame with detailed examples and explanations.

Table of Contents

  1. Setup and Initialization
  2. Display Class
  3. Component Class
  4. Movement Utilities
  5. Camera System
  6. TileMap System
  7. Input Handling
  8. Complete Game Example

Setup and Initialization

To get started with TCJSGame, you need to include the engine in your HTML file:

<!DOCTYPE html>
<html>
<head>
    <title>My TCJSGame</title>
    <style>
        body { margin: 0; overflow: hidden; background: #333; }
        canvas { border: 2px solid white; margin: 20px auto; display: block; }
    </style>
</head>
<body>
    <script>
        // Paste the entire TCJSGame code here
        // Or include it from an external file
    </script>
    <script>
        // Your game code will go here
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Display Class

The Display class is the core of TCJSGame, managing the canvas, game loop, and rendering.

Creating a Display Instance

// Create a display instance
const display = new Display();

// Start the game with custom dimensions
display.start(800, 600); // Width, height

// Customize the display
display.backgroundColor("navy");
display.borderColor("white");
display.borderSize("2px");
display.borderStyle("solid");

// Or use gradients for backgrounds
display.lgradient("bottom", "#87CEEB", "#E0F7FA"); // Linear gradient
display.rgradient("blue", "darkblue"); // Radial gradient
Enter fullscreen mode Exit fullscreen mode

Scene Management

TCJSGame supports multiple scenes for organizing different game states:

// Create components for different scenes
const menuBackground = new Component(800, 600, "darkblue", 0, 0, "rect");
const gameBackground = new Component(800, 600, "lightblue", 0, 0, "rect");

// Add components to specific scenes
display.add(menuBackground, 0); // Scene 0 (menu)
display.add(gameBackground, 1); // Scene 1 (game)

// Switch between scenes
display.scene = 0; // Show menu
// Later in code...
display.scene = 1; // Show game
Enter fullscreen mode Exit fullscreen mode

Component Class

The Component class represents game objects with properties for rendering, physics, and interaction.

Creating Components

// Create different types of components
const player = new Component(50, 50, "red", 100, 100, "rect");
const platform = new Component(200, 30, "green", 300, 400, "rect");
const enemy = new Component(40, 40, "enemy.png", 500, 300, "image");
const scoreText = new Component(20, 20, "white", 20, 20, "text");
scoreText.text = "Score: 0";

// Add physics to components
player.physics = true;
player.gravity = 0.5;
player.bounce = 0.3;

// Add components to display
display.add(player);
display.add(platform);
display.add(enemy);
display.add(scoreText);
Enter fullscreen mode Exit fullscreen mode

Component Properties and Methods

// Positioning and movement
player.x = 100; // Set X position
player.y = 200; // Set Y position
player.speedX = 2; // Horizontal speed
player.speedY = -5; // Vertical speed (negative for upward)

// Rotation
player.angle = 45 * Math.PI / 180; // Rotate 45 degrees
player.changeAngle = true; // Enable rotation rendering

// Visibility control
player.hide(); // Make component invisible
player.show(); // Make component visible again

// Collision detection
if (player.crashWith(platform)) {
    console.log("Collision detected!");
}

// Click detection
if (player.clicked()) {
    console.log("Player was clicked!");
}
Enter fullscreen mode Exit fullscreen mode

Movement Utilities

TCJSGame provides a comprehensive set of movement functions through the move object.

Basic Movement

// Direct movement
move.setX(player, 300); // Set exact X position
move.setY(player, 200); // Set exact Y position
move.teleport(player, 400, 300); // Teleport to position

// Physics-based movement
move.backward(player, 2); // Move with physics

// Circular movement
move.circle(player, 2); // Rotate at 2 degrees per frame
Enter fullscreen mode Exit fullscreen mode

Advanced Movement

// Smooth gliding to positions
move.glideX(player, 2, 400); // Glide to X=400 over 2 seconds
move.glideY(player, 1.5, 300); // Glide to Y=300 over 1.5 seconds
move.glideTo(player, 2, 400, 300); // Glide to position (400,300)

// Projectile motion
move.project(player, 10, 45, 0.1); // Velocity, angle, gravity

// Point toward a target
move.pointTo(player, enemy.x, enemy.y); // Rotate to face enemy

// Acceleration and deceleration
move.accelerate(player, 0.1, 0, 5); // Accelerate X with max speed 5
move.decelerate(player, 0.2, 0); // Decelerate X
Enter fullscreen mode Exit fullscreen mode

Boundary Control

// Keep within canvas bounds
move.bound(player);

// Keep within custom bounds
move.boundTo(player, 0, 700, 0, 500); // left, right, top, bottom

// Position at screen edges
move.position(player, "center"); // Center of screen
move.position(player, "top", 20); // 20px from top
move.position(player, "bottom", 10); // 10px from bottom
move.position(player, "left", 30); // 30px from left
move.position(player, "right", 40); // 40px from right
Enter fullscreen mode Exit fullscreen mode

Camera System

The Camera class allows for scrolling worlds and following players.

// Initialize camera with world dimensions
display.camera = new Camera(0, 0, 2000, 2000);

// Follow a component
display.camera.follow(player, false); // Direct follow
display.camera.follow(player, true); // Smooth follow

// Camera properties
display.camera.x = 500; // Set camera position manually
display.camera.y = 300;
display.camera.worldWidth = 3000; // Expand world size
display.camera.worldHeight = 3000;
Enter fullscreen mode Exit fullscreen mode

TileMap System

TCJSGame includes a powerful tilemap system for creating grid-based levels.

Creating a Tilemap

// Define tile types
const tiles = [
  new Component(0, 0, "green", 0, 0, "rect"),  // Ground (index 1)
  new Component(0, 0, "gray", 0, 0, "rect"),   // Wall (index 2)
  new Component(0, 0, "blue", 0, 0, "rect")    // Water (index 3)
];

// Create map layout (2D array)
const mapLayout = [
  [2, 2, 2, 2, 2, 2, 2, 2],
  [2, 1, 1, 1, 1, 1, 1, 2],
  [2, 1, 1, 3, 3, 1, 1, 2],
  [2, 1, 1, 3, 3, 1, 1, 2],
  [2, 1, 1, 1, 1, 1, 1, 2],
  [2, 2, 2, 2, 2, 2, 2, 2]
];

// Setup and display tilemap
display.tile = tiles;
display.map = mapLayout;
display.tileMap();
display.tileFace.show();
Enter fullscreen mode Exit fullscreen mode

Tilemap Interactions

// Check collisions with tiles
if (display.tileFace.crashWith(player)) {
    // Handle collision
}

// Check collisions with specific tile types
if (display.tileFace.crashWith(player, 2)) { // Wall collisions
    player.speedX = 0;
    player.speedY = 0;
}

if (display.tileFace.crashWith(player, 3)) { // Water collisions
    player.speedX *= 0.5; // Slow down in water
    player.speedY *= 0.5;
}

// Get specific tiles
const groundTiles = display.tileFace.tiles(1); // All ground tiles
const specificTile = display.tileFace.rTile(3, 2); // Tile at column 3, row 2

// Modify tilemap at runtime
display.tileFace.add(1, 3, 2); // Add ground at position (3,2)
display.tileFace.remove(4, 3); // Remove tile at position (4,3)
Enter fullscreen mode Exit fullscreen mode

Input Handling

TCJSGame provides built-in input handling for keyboard, mouse, and touch.

Keyboard Input

function update() {
    // Arrow key movement
    if (display.keys[37]) { // Left arrow
        player.speedX = -5;
    }
    if (display.keys[39]) { // Right arrow
        player.speedX = 5;
    }
    if (display.keys[38]) { // Up arrow
        player.speedY = -5;
    }
    if (display.keys[40]) { // Down arrow
        player.speedY = 5;
    }

    // Spacebar for jump
    if (display.keys[32] && player.gravitySpeed === 0) {
        player.speedY = -12;
    }

    // Decelerate when no key pressed
    if (!display.keys[37] && !display.keys[39]) {
        move.decelerate(player, 0.5, 0);
    }
}
Enter fullscreen mode Exit fullscreen mode

Mouse and Touch Input

function update() {
    // Update mouse position
    Mouse.x = mouse.x;
    Mouse.y = mouse.y;

    // Check for clicks/taps on components
    if (display.x !== false && player.clicked()) {
        player.color = "yellow"; // Change color when clicked
    }

    // Drag objects with mouse/touch
    if (mouse.down) {
        move.glideTo(player, 0.5, mouse.x + display.camera.x, mouse.y + display.camera.y);
    }
}
Enter fullscreen mode Exit fullscreen mode

Complete Game Example

Let's create a simple platformer game using TCJSGame:

// Initialize display
const display = new Display();
display.start(800, 600, document.body);
display.lgradient("bottom", "#87CEEB", "#E0F7FA");

// Create player
const player = new Component(30, 30, "red", 100, 100, "rect");
player.physics = true;
player.gravity = 0.5;
player.bounce = 0.3;
display.add(player);

// Create platforms
const platforms = [];
for (let i = 0; i < 5; i++) {
    const platform = new Component(150, 20, "green", i * 200, 400 + (i % 2) * 100, "rect");
    platform.physics = true;
    display.add(platform);
    platforms.push(platform);
}

// Create coins
const coins = [];
for (let i = 0; i < 10; i++) {
    const coin = new Component(15, 15, "gold", Math.random() * 700 + 50, Math.random() * 300 + 50, "rect");
    display.add(coin);
    coins.push(coin);
}

// Setup camera
display.camera.worldWidth = 1600;
display.camera.worldHeight = 1200;
display.camera.follow(player, true);

// Game state
let score = 0;
const scoreText = new Component(20, 20, "white", 20, 20, "text");
scoreText.text = "Score: 0";
display.add(scoreText);

// Update function
function update() {
    // Keyboard controls
    if (display.keys[37]) player.speedX = -5; // Left
    if (display.keys[39]) player.speedX = 5;  // Right
    if (display.keys[38] && player.gravitySpeed === 0) player.speedY = -12; // Jump

    // Check collisions with platforms
    platforms.forEach(platform => {
        if (player.crashWith(platform)) {
            player.hitBottom();
        }
    });

    // Collect coins
    coins.forEach((coin, index) => {
        if (coin && player.crashWith(coin)) {
            score += 10;
            scoreText.text = `Score: ${score}`;

            // Create a visual effect
            const effect = new Component(0, 0, "yellow", coin.x, coin.y, "text");
            effect.text = "+10";
            display.add(effect, 1); // Add to scene 1

            // Remove coin temporarily
            coins[index] = null;
            coin.hide();

            // Respawn coin after delay
            setTimeout(() => {
                coin.x = Math.random() * 700 + 50;
                coin.y = Math.random() * 300 + 50;
                coins[index] = coin;
                coin.show();
            }, 2000);
        }
    });

    // Keep player in world bounds
    move.boundTo(player, 0, display.camera.worldWidth - player.width, 
                0, display.camera.worldHeight - player.height);
}

// Start the game
display.start();
Enter fullscreen mode Exit fullscreen mode

Advanced Techniques

Sprite Animation

While TCJSGame doesn't have built-in sprite animation, you can implement it:

class AnimatedSprite {
    constructor(imageSrc, frameWidth, frameHeight, frameCount, frameSpeed) {
        this.image = new Image();
        this.image.src = imageSrc;
        this.frameWidth = frameWidth;
        this.frameHeight = frameHeight;
        this.frameCount = frameCount;
        this.frameSpeed = frameSpeed;
        this.currentFrame = 0;
        this.frameTimer = 0;
        this.component = new Component(frameWidth, frameHeight, "", 0, 0, "image");
        this.component.image = this.image;
    }

    update() {
        this.frameTimer++;
        if (this.frameTimer >= this.frameSpeed) {
            this.frameTimer = 0;
            this.currentFrame = (this.currentFrame + 1) % this.frameCount;
        }
    }

    draw(ctx, x, y) {
        ctx.drawImage(
            this.image,
            this.currentFrame * this.frameWidth,
            0,
            this.frameWidth,
            this.frameHeight,
            x,
            y,
            this.frameWidth,
            this.frameHeight
        );
    }
}

// Usage
const playerSprite = new AnimatedSprite("player.png", 32, 32, 4, 10);
playerSprite.component.x = 100;
playerSprite.component.y = 100;
display.add(playerSprite.component);

function update() {
    playerSprite.update();
    // Other game logic...
}
Enter fullscreen mode Exit fullscreen mode

Particle Systems

Create simple particle effects:

class ParticleSystem {
    constructor(x, y, color, count, size, speed, life) {
        this.particles = [];
        for (let i = 0; i < count; i++) {
            const particle = new Component(size, size, color, x, y, "rect");
            particle.speedX = (Math.random() - 0.5) * speed;
            particle.speedY = (Math.random() - 0.5) * speed;
            particle.life = life;
            display.add(particle);
            this.particles.push(particle);
        }
    }

    update() {
        this.particles.forEach((particle, index) => {
            particle.life--;
            particle.x += particle.speedX;
            particle.y += particle.speedY;

            if (particle.life <= 0) {
                particle.hide();
                this.particles.splice(index, 1);
            }
        });
    }
}

// Usage
function createExplosion(x, y) {
    new ParticleSystem(x, y, "orange", 20, 5, 10, 30);
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

TCJSGame is a versatile and accessible JavaScript game engine that provides all the essential tools for creating 2D games. With its component-based architecture, physics system, tilemap support, and intuitive API, it's an excellent choice for both beginners and experienced developers looking to create web-based games quickly.

This reference guide covers the core features of TCJSGame, but the engine's simplicity makes it easy to extend and customize for your specific needs. Whether you're creating a simple platformer, a puzzle game, or an interactive experience, TCJSGame provides a solid foundation to build upon.

Happy coding!

Top comments (0)