Docs
These are the real BerryJS pieces. A game does not have to use all of them.
Start Game Actor Camera Sprites Overlap
Getting started
npm create berryjs my-game
cd my-game
npm install
npm run dev
Edit scenes/GameScene.js. Pictures go in public/assets so dev and build can both find them.
Adding BerryJS to a project you already have? Install the engine with npm install berryjs-engine and use it with a bundler such as Vite.
Installation
npm install berryjs-engine only downloads the engine. npm create berryjs creates the whole game folder for you.
import { Game, Scene, Actor, Sprite, loadImage, Sound } from "berryjs-engine"
Game
Game owns the canvas, the loop, the keyboard, and the camera. fullscreen: true uses the window size. remove waits until the update finishes, so the next actor is not skipped.
const game = new Game({
width: 800,
height: 600,
fullscreen: false,
background: "#111111"
})
game.setScene(scene)
game.start()
Scene
start can be async. update gets delta time in seconds. draw is for text such as a score. end runs when the scene is left.
export class MenuScene extends Scene {
update() {
if (this.game.keyboard.isDown("Enter")) {
this.game.setScene(this.game.gameScene)
}
}
draw(ctx) {
ctx.fillStyle = "white"
ctx.fillText("Press Enter", 80, 80)
}
}
Actor
An actor is a box. color draws a rectangle when there is no sprite. oneWay still needs solid, and it only blocks a landing from above. grounded becomes true on that landing.
const floor = new Actor(0, 420, 800, 48)
floor.solid = true
floor.color = "#3ddc84"
const ledge = new Actor(200, 280, 160, 16)
ledge.solid = true
ledge.oneWay = true
if (this.grounded && this.game.keyboard.isDown("Space")) {
this.vy = -420
this.grounded = false
}
Key codes are ArrowLeft, ArrowRight, Space, ShiftLeft, and ShiftRight. There is no key named Shift.
Camera
this.game.camera.follow(player)
this.game.camera.setBounds(0, 0, 1600, 600)
this.game.camera.follow(null)
follow(null) is the fixed camera. null in setBounds means that side does not stop the camera. On a fullscreen game, place the floor from game.height, not from a fixed 500.
Sprites
const image = await loadImage("/assets/player-sheet.png")
player.setSprite(new Sprite(image, image.width / 5, image.height / 4))
player.sprite.setAnimation(1, 5)
player.flipX = true
setAnimation(row, frameCount, start) picks a row. start is the first column and defaults to 0. The same call again does not restart the row. flipX mirrors the picture.
Overlap, tags, and sound
coin.tag = "coin"
onOverlap(other) {
if (other.tag !== "coin") return
this.score += 1
this.game.remove(other)
}
const jump = new Sound("/sounds/jump.wav")
jump.play()
onOverlap also sees the floor for that frame, so check the tag. Score is your own variable. The engine does not play a sound unless you call play.