Getting Started

Review the Installing Guide for instructions.

Introduction

Excalibur uses a theater-style metaphor to organize your games. There are Actor's which can move around and do things in a currently active Scene, and all of that lives in the Engine container.

Global Namespace vs. Imports

Imports

In this tutorial, we are using "ES Style" imports, but the global ex. namespace can also be used if you are using a standalone script tag.

See docs on how to configure bundlers for ES imports with module loaders and bundlers, there are template repos for parcel v1, parcel v2, vite, webpack, and rollup.

// ES Style Imports
import { Actor } from 'excalibur'

const actor = new Actor()

Script Tag

If you are using a standalone script, the excalibur types will have a ex. in front of them.

Excalibur can be used as a script reference, see standalone script for more info

<html>
  <head> </head>
  <body>
    <!-- Include your script at the end of the body tag -->
    <script src="./path/to/my/excalibur-version.js"></script>
    <script src="game.js"></script>
  </body>
</html>
...
// game.js
// Standalone style 'ex' global exists ambiently from an included script.

const actor = new ex.Actor()

Hello Excalibur: Building Breakout!

In this example we'll build a simple version of the popular game breakout. Breakout is a game where you break bricks at the top of the screen using a ball that bounces off of a player paddle. You must break all the bricks to win and avoid the ball falling off the bottom of the screen.

The whole code example in this guide is on GitHub if you want to skip to the code.

This example creates the game in a single file for simplicity, we recommend splitting you game into separate files to keep your project more manageable.

Basic Engine Start

Create a script in your project, here I’ve named it game.ts. Excalibur games are built off of the Engine container. It is important to start the engine once you are done building your game.

It is important to call game.start() otherwise the game wont start!

// ES style import from excalibur
import { Engine } from 'excalibur'

// Create an instance of the engine.
// I'm specifying that the game be 800 pixels wide by 600 pixels tall.
// If no dimensions are specified the game will fit to the screen.
const game = new Engine({
  width: 800,
  height: 600,
});

// Start the engine to begin the game.
game.start()

Open a browser and view the blank blue screen of goodness.

Creating the paddle with an Actor

Game elements that have a position and are drawn to the screen are called Actor. Actors are the primary way to draw things to the screen.

Actors must be added to a Scene to be drawn and updated.

Think of actors like you would the actors in a play. If you change scenes different actors might be on stage.

Actors must be added to a scene to be drawn or updated! game.add(actor) Will add an actor to the current scene.

Below we are going to create the paddle Actor for our breakout game. Actors can be given a position, width, and height.

// Create an actor with x position of 150px,
// y position of 40px from the bottom of the screen,
// width of 200px, height and a height of 20px
const paddle = new Actor({
  x: 150,
  y: game.drawHeight - 40,
  width: 200,
  height: 20,
  // Let's give it some color with one of the predefined
  // color constants
  color: Color.Chartreuse,
});

// Make sure the paddle can partipate in collisions, by default excalibur actors do not collide with each other
// CollisionType.Fixed is like an object with infinite mass, and cannot be moved, but does participate in collision.
paddle.body.collisionType = CollisionType.Fixed;

// `game.add` is the same as calling
// `game.currentScene.add`
game.add(paddle);

Open up your favorite browser and you should see something like this:

Incomplete breakout screenshot

That’s neat, but this game is way more fun if things move around. Let’s make the paddle follow the mouse around in the x direction. The paddle will be centered on the mouse cursor.

// Add a mouse move listener
game.input.pointers.primary.on("move", (evt) => {
  paddle.pos.x = evt.worldPos.x;
});

Important! Actors have a default anchor of (0.5, 0.5) which means their graphics are positioned in their center (not top-left) by default.

Creating the ball with Actors

What’s breakout without the ball? Excalibur comes pre-built with a physics collision system to help you out with things like balls bouncing off of other objects.

To make the ball, we switch the collider to a circle with the useCircleCollider(radius) helper.

In this case we want to handle the resolution ourselves to emulate the the way breakout works. We use the ex.CollisionType.Passive which will send an event that there has been an intersection but not resolve the positions.

Read more about the different CollisionTypes that excalibur supports.

// Create a ball at pos (100, 300) to start
const ball = new Actor({
  x: 100,
  y: 300,
  // Use a circle collider with radius 10
  radius: 10,
  // Set the color
  color: Color.Red,
});
// Start the serve after a second
const ballSpeed = vec(100, 100);
setTimeout(() => {
  // Set the velocity in pixels per second
  ball.vel = ballSpeed;
}, 1000);

// Set the collision Type to passive
// This means "tell me when I collide with an emitted event, but don't let excalibur do anything automatically"
ball.body.collisionType = CollisionType.Passive;
// Other possible collision types:
// "ex.CollisionType.PreventCollision - this means do not participate in any collision notification at all"
// "ex.CollisionType.Active - this means participate and let excalibur resolve the positions/velocities of actors after collision"
// "ex.CollisionType.Fixed - this means participate, but this object is unmovable"

// Add the ball to the current scene
game.add(ball);

The ball will now bounce off of the paddle, but does not bounce with the side of the screen. To fix that, let’s take advantage of the postupdate event.

// Wire up to the postupdate event
ball.on("postupdate", () => {
  // If the ball collides with the left side
  // of the screen reverse the x velocity
  if (ball.pos.x < ball.width / 2) {
    ball.vel.x = ballSpeed.x;
  }

  // If the ball collides with the right side
  // of the screen reverse the x velocity
  if (ball.pos.x + ball.width / 2 > game.drawWidth) {
    ball.vel.x = ballSpeed.x * -1;
  }

  // If the ball collides with the top
  // of the screen reverse the y velocity
  if (ball.pos.y < ball.height / 2) {
    ball.vel.y = ballSpeed.y;
  }
});

Creating the bricks with Actors

Breakout needs some bricks to break. To do this we calculate our brick layout and add them to the current scene.

// Build Bricks

// Padding between bricks
const padding = 20; // px
const xoffset = 65; // x-offset
const yoffset = 20; // y-offset
const columns = 5;
const rows = 3;

const brickColor = [Color.Violet, Color.Orange, Color.Yellow];

// Individual brick width with padding factored in
const brickWidth = game.drawWidth / columns - padding - padding / columns; // px
const brickHeight = 30; // px
const bricks: Actor[] = [];
for (let j = 0; j < rows; j++) {
  for (let i = 0; i < columns; i++) {
    bricks.push(
      new Actor({
        x: xoffset + i * (brickWidth + padding) + padding,
        y: yoffset + j * (brickHeight + padding) + padding,
        width: brickWidth,
        height: brickHeight,
        color: brickColor[j % brickColor.length],
      })
    );
  }
}

bricks.forEach(function (brick) {
  // Make sure that bricks can participate in collisions
  brick.body.collisionType = CollisionType.Active;

  // Add the brick to the current scene to be drawn
  game.add(brick);
});

When the ball collides with bricks, we want to remove them from the scene. Update the ‘precollision’ handler we previously added:

// On collision remove the brick, bounce the ball
let colliding = false;
ball.on("collisionstart", function (ev) {
  if (bricks.indexOf(ev.other) > -1) {
    // kill removes an actor from the current scene
    // therefore it will no longer be drawn or updated
    ev.other.kill();
  }

  // reverse course after any collision
  // intersections are the direction body A has to move to not be clipping body B
  // `ev.content.mtv` "minimum translation vector" is a vector `normalize()` will make the length of it 1
  // `negate()` flips the direction of the vector
  var intersection = ev.contact.mtv.normalize();

  // Only reverse direction when the collision starts
  // Object could be colliding for multiple frames
  if (!colliding) {
    colliding = true;
    // The largest component of intersection is our axis to flip
    if (Math.abs(intersection.x) > Math.abs(intersection.y)) {
      ball.vel.x *= -1;
    } else {
      ball.vel.y *= -1;
    }
  }
});

ball.on("collisionend", () => {
  // ball has separated from whatever object it was colliding with
  colliding = false;
});

Finally, if the ball leaves the screen, the player loses!

// Loss condition
ball.on("exitviewport", () => {
  alert("You lose!");
});

Final Breakout screenshot

Congratulations! You have just created your first game in Excalibur! You can download this example here https://github.com/excaliburjs/sample-breakout

It's time to get introduced to the engine for more examples or advanced users can browse the API Reference.