Skip to content

快速开始 ​

早期版本

sapling2d 还在 1.0 之前,API 可能会变。

安装 ​

sh
npm install sapling2d
npm install -D vite vitest typescript

需要 Node.js 20.19 或更高版本。

第一个场景 ​

游戏对象都继承节点类,覆写生命周期方法;Scene 是场景树的根,在 ready() 里用 this.add() 搭建子节点。

ts
import { Node2D, Scene, v } from 'sapling2d'

/** 节点:继承引擎的节点类,覆写生命周期方法 */
class Mover extends Node2D {
  speed = 120 // 像素/秒

  override process(dt: number) {
    this.x += this.speed * dt // Vector2 不可变:用 x / y 快捷属性或重新赋值 position
  }
}

/** 场景:场景树的根。在 ready() 里用 this.add() 搭建子节点,add 返回带类型的节点 */
export class Main extends Scene {
  mover!: Mover

  override ready() {
    this.mover = this.add(new Mover({ name: 'Mover', position: v(100, 200) }))
  }
}

// 浏览器:import { startGame } from 'sapling2d/browser'; await startGame({ main: Main })
// 小游戏:import { startGame } from 'sapling2d/wechat'; startGame({ main: Main })

在浏览器里启动:

ts
// src/main.ts
import { startGame } from 'sapling2d/browser'
import { Main } from './game'

await startGame({ main: Main })
html
<!-- index.html -->
<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
  </head>
  <body>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>
ts
// vite.config.ts
import { defineConfig } from 'vite'
import { sapling } from 'sapling2d/vite'

// sapling():构建时检查 tex() / sfx() / music() 引用的资源文件是否存在
export default defineConfig({ plugins: [sapling()] })

运行 npx vite,打开页面就能看到画面。默认的设计分辨率是 750×1334(竖屏)。

写一个测试 ​

不开浏览器也能运行游戏:createTestGame 在 Node 里无头运行场景树,按帧推进,结果是确定的。

ts
const g = await createTestGame({ main: Main, seed: 1 })
g.step(60) // 推进 60 帧 = 1 秒,结果是确定的
expect(g.scene.mover.x).toBeCloseTo(220)
console.log(g.dump())
// Main (Main) position=(0, 0)
//   Mover (Mover) position=(220, 200)

g.dump() 把场景树打印成文本,每行是 名字 (类名) 属性=值。断言失败时先看它,比猜原因快。详见 无头测试。

用模板起项目 ​

仓库里的 templates/game 是一个完整的游戏骨架:

src/game.ts          游戏本身(和平台无关):场景、节点、gameOptions
src/main.ts          浏览器入口
src/main.wechat.ts   微信小游戏入口
test/                无头测试
public/assets/       贴图、声音、字体:tex('ball.png') 就是 public/assets/ball.png
AGENTS.md            给编程 agent 的说明

复制这个目录后,把 package.json 里 sapling2d 的版本从 workspace:* 改成 npm 上的版本。常用命令:

命令作用
pnpm dev浏览器里开发
pnpm check类型检查 + 测试(Vitest 不做类型检查,两个都要过)
pnpm dev:wechat构建微信小游戏到 dist-wechat/,监听改动
pnpm build:wechat小游戏的发布构建(真机预览和上传用这个)

开发时在浏览器控制台里运行 sapling.tree.dump(),可以看到实时的场景树。

下一步 ​

  • 核心概念:节点树、生命周期、每帧的执行顺序
  • 功能:贴图、信号、输入、物理、相机……
  • 微信小游戏:同一份代码发布成小游戏

MIT 许可证