joy

joy is a JavaScript library that helps you easily develop 2D games.

Usage

First, create an index.html file as follows:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="https://cdn.jsdelivr.net/npm/joylib@latest"></script>
  </head>
  <body>
    <script src="game.js"></script>
  </body>
</html>

Then, create a file named game.js and write your game code:

var go = $({ image: 'assets/dog.png' });
go.on('update', function (deltaTime) {
  go.rotation += deltaTime * 100; // The dog spins around.
});

Next, run a local server to access index.html, or upload both index.html and game.js to the internet and access them.

# Running a local server

# If Python is installed
python3 -m http.server 8000

# If Node.js is installed
npx serve .

Example on the Internet

Using the $ Function

$ is the central function of joy, containing all its features. You can use it for everything from creating game objects to accessing global variables like $.gameWidth.

The basic options for creating a game object are:

var go = $({
  image: 'assets/dog.png', // Image for the object
  x: 100, // X coordinate
  y: 200, // Y coordinate
  scale: 2, // Scale factor (you can also set scaleX, scaleY separately)
  rotation: 90, // Rotation angle (pivotX, pivotY set the rotation pivot)
  alpha: 0.5, // Transparency
  drawOrder: 123, // Draw order; larger values are rendered in front
});

// You can change options later as well:
go.x = 300;

joy allows you to assign colliders to game objects to apply physics.

There are three types of colliders:

You can set these colliders and physics options as follows:

var go = $({
  collider: { type: 'circle', x: 1, y: 2, radius: 5 }, // Collider
  isStatic: true, // Static body
  isSensor: true, // Sensor-only body (detects collisions but doesn’t react physically)
  velocityX: 10, // Velocity along the X-axis
  velocityY: 20, // Velocity along the Y-axis
  fixedRotation: true, // Prevent rotation from physics
});

You can then check for collisions like this:

var player = $({ /* physics settings */ });
var enemy = $({ /* physics settings */ });

$.on('collisionStart', (go1, go2) => {
  if (go1 == player && go2 == enemy) {
    console.log('Collision detected!');
  }
});

Game Object Methods

Global Variables / Functions

Building Larger Games

For larger games, using a single game.js file can be limiting.

In JavaScript, you can split your code into multiple .js files and use export and import to share functionality.

You can then use tools like esbuild to bundle multiple .js files into a single one.

License

MIT

Questions & Feedback

If you have any questions or suggestions for improvement, feel free to leave them on GitHub Issues.