Monday, 31 March 2025

Getting Started with Kaboom.js: Build Your First Platformer Game with Gravity, Jumping, and Movement

Are you new to game development and looking for an easy way to get started? This post introduces you to Kaboom.js, a beginner-friendly library for creating games. We'll walk you through a simple platformer game where a character (sprite) can move left, right, and jump.

You'll learn:

·       What gravity is in gaming and how to use it in Kaboom.js.

·       How to add a player sprite, make it interactive, and apply physics.

·       How to create platforms and implement collision detection.

·       The basics of jumping mechanics and smooth player movement.

 

By the end, you'll have a working game and a solid understanding of key Kaboom.js features to build on for future projects. Let’s code!

 

1. Kaplay context

Initialize KAPLAY context. The starting point of all KAPLAY games. It creates a canvas for you to experiment.

const k = kaplay();

You can set the widht and height of canvas by passing width and height properties. 

const k = kaplay({
    width: 1000,
    height: 750
});

2. Gravity in Kaboom.js

Gravity is a force that pulls objects downward, like how things fall on Earth. In Kaboom.js, we set gravity to make objects fall automatically unless something stops them (like a platform).

 

For example, k.setGravity(1000) applies gravity to the game. The number 1000 controls how strong the pull is. Higher numbers mean faster falling.

 

You can refer this video (https://www.youtube.com/watch?v=FfoxdfixgBI) to understand Gravity.

 

3. What is a Sprite?

A sprite is an image that represents a character, object, or element in the game.

 

Example

k.loadSprite("bean", "sprites/bean.png")

 

Above statement loads the image so we can use it in the game.

let player = k.add([
    k.pos(300, 100), 
    k.sprite("bean"), 
    k.body(), 
    k.area()
]);

4. Understanding the body() Method

Think of the body() method as a "physical engine" for an object. It tells Kaboom.js that the object (e.g., a player, a ball, or anything in your game) should behave like a real object in the real world.

 

When you add the body() method to an object, Kaboom.js will treat it as if it's subject to things like:

·       Gravity (objects falling or being pulled downwards),

·       Velocity (how fast an object is moving),

·       Momentum (how an object continues moving once it's in motion),

·       Forces (how an object can be pushed or pulled).

 

Why is the body() method important?

The body() method is crucial because it allows objects to act like physical entities in the game. Without it, your objects would not follow the natural rules of physics, like gravity or movement.

 

For example, if you don't add body() to a player, the player won't fall due to gravity, won't be able to jump, or won't even stop when it hits the ground. It would just stay wherever you place it, without any natural behavior.

 

Example

let player = k.add([
    k.pos(300, 100), 
    k.sprite("bean"), 
    k.body(), 
    k.area()
]);

 

In this example, the player has a body(), which means it will be subject to gravity, can move around, and can jump when you press a key. Without the body(), the player would not experience gravity or jump.

 

5. Understanding the area() Method

The area() method is like a "collision detector" for an object. It creates an invisible area (called a hitbox) around your object, and when another object enters that area, Kaboom.js can detect the interaction.

 

If you think of a player character, the area() method defines the space around the character where it will interact with other objects. For example, when the player touches the ground, an object, or another player, the area() will help detect that interaction and trigger a response.

 

Why is the area() method important?

The area() method is important because it allows objects to collide with each other. Without it, objects would simply pass through each other and wouldn't interact. You need area() to detect things like:

·       When the player lands on the ground (so they stop falling).

·       When the player hits an obstacle (to stop moving or bounce back).

·       When two objects touch (like in a fight or collision).

 

By combining both methods body() and area(), you create interactive objects in your game that move naturally and respond to interactions in the game world.

 

6. Creating an Immovable Platform for Player Landing

In Kaboom.js, the k.body({ isStatic: true }) method is a crucial tool for creating static platforms or ground surfaces. These are essential in games where the player needs a reliable, stationary surface to jump, land, or walk on.

 

Example

k.add([
  k.rect(k.width(), 100),
  k.pos(0, 700),
  k.area(),
  k.outline(3),
  k.color(109, 99, 19), // Brown-like color for the ground
  k.body({ isStatic: true }),
]);

 

What Does isStatic: true Do?

1.   Immovable Object: The rectangle (or any shape) won’t be affected by gravity or other physical forces.

2.   Stays in Place: It remains fixed in its position, regardless of player interaction or collisions.

3.   Stable Platform: Ideal for creating ground, platforms, or walls where dynamic elements like the player or enemies interact.

 

Without isStatic: true, the rectangle would behave like a dynamic object, falling or reacting to forces applied by other objects, which is undesirable for a ground or platform.

 

Follow below step by step procedure to build a complete working application.

 

Step 1: Create a KAPLAY project jumping-bean by executing below command.

 

npx create-kaplay jumping-bean

 

Upon successful execution of above command, you can see a project structure looks like below.


 

 

Step 2: Let’s update src/main.js with below content.

 

main.js

import kaplay from "kaplay"; // Import Kaplay.js library

// Initialize Kaplay.js with game settings
const k = kaplay({
  width: 1000,               // Set game canvas width
  height: 800,               // Set game canvas height
  background: [135, 206, 250], // Light blue background (sky-like)
});

// Set gravity for the game world
// Higher values make objects fall faster
k.setGravity(1000);

// Load player sprite
// The "bean.png" sprite will represent the player character
k.loadSprite("bean", "sprites/bean.png");

// Add the player to the game world
// The player is positioned, given a sprite, physics properties (body), and collision area
let player = k.add([
  k.pos(300, 100),           // Initial position of the player
  k.sprite("bean"),          // Assign the "bean" sprite
  k.body(),                  // Enable physics for the player (affected by gravity)
  k.area(),                  // Enable collision detection
]);

// Add ground (static platform) for the player to land on
// The ground is a wide rectangle, positioned near the bottom of the canvas
k.add([
  k.rect(k.width(), 100),    // Rectangle as wide as the canvas
  k.pos(0, 700),             // Position at the bottom of the canvas
  k.area(),                  // Enable collision detection for the ground
  k.outline(3),              // Add an outline for visibility
  k.color(109, 99, 19),      // Brown-like color for the ground
  k.body({ isStatic: true }),// Make the ground immovable and unaffected by gravity
]);

// Add on-screen instructions for the player
k.add([
  k.text("Use arrow keys to move, space to jump!", { size: 24 }), // Instruction text
  k.pos(200, 10),              // Position text at the top-left corner
  k.color(0, 0, 0),           // Black text color
]);

// Define jump behavior for the player
// Player can jump when on the ground by pressing the space bar
player.onKeyPress("space", () => {
  if (player.isGrounded()) {  // Check if the player is on the ground
    player.jump(400);         // Jump with a force of 400
  }
});

// Define smooth horizontal movement for the player
// Move left when the left arrow key is held down
player.onKeyDown("left", () => {
  player.move(-300, 0);       // Move left with a speed of 300
});

// Move right when the right arrow key is held down
player.onKeyDown("right", () => {
  player.move(300, 0);        // Move right with a speed of 300
});

// Add screen boundaries to prevent the player from moving off the screen
player.onUpdate(() => {
  if (player.pos.x < 0) { 
    player.pos.x = 0;         // Prevent moving off the left edge
  }
  if (player.pos.x > k.width() - player.width) {
    player.pos.x = k.width() - player.width; // Prevent moving off the right edge
  }
});

Step 3: Navigate to the project root directory and execute below commands to run the Application.

 

npm install
npm run dev

Open the url ‘http://localhost:3001/’ in browser. Now you have the game ready to experiment. 


You can see the demo of this game here (https://www.youtube.com/watch?v=T1MzS855vIM).

 

You can download this Application from this link.



Previous                                                    Next                                                    Home

No comments:

Post a Comment