KaboomJavaScript 游戏库
Kaboom 是一个 JavaScript 库,可帮助你轻松快速地制作游戏!
可以在 Kaboom Playground 体验一下。
示例
// initialize context kaboom(); // load a sprite called "froggy" loadSprite("froggy", "sprites/froggy.png"); // compose the player game object from multiple components and add it to the game const froggy = add([ sprite("bean"), pos(80, 40), area(), body(), ]); // press space to jump keyPress("space", () => { // this method is provided by the "body" component above froggy.jump(); });
Kaboom 使用了一个强大的组件系统,来组成游戏对象和行为。
// add a game obj to the scene from a list of component const player = add([ // it renders as a sprite sprite("bean"), // it has a position pos(100, 200), // it has a collider area(), // it is a physical body which will respond to physics body(), // it has 8 health health(8), // or give it tags for easier group behaviors "player", "friendly", // plain objects fields are directly assigned to the game obj { dir: vec2(-1, 0), dead: false, speed: 240, }, ]);
描述行为的块状命令式语法:
// .collides() comes from "area" component player.collides("enemy", () => { // .hurt() comes from "health" component player.hurt(1) }); // check fall death player.action(() => { if (player.pos.y >= height()) { destroy(player); gameOver(); } }); // if 'player' collides with any object with tag "enemy", run the callback player.collides("enemy", () => { player.hp -= 1; }); // all objects with tag "enemy" will move towards 'player' every frame action("enemy", (e) => { e.move(player.pos.sub(e.pos).unit().scale(e.speed)); }); // move up 100 pixels per second every frame when "w" key is held down keyDown("w", () => { player.move(0, 100); });
用法
NPM
$ npm install kaboom
import kaboom from "kaboom"; kaboom(); add([ text("oh hi"), pos(80, 40), ]);
也适用于 CommonJS :
const kaboom = require("kaboom");
注意:要把将 Kaboom 与 NPM 结合使用,需要打包器,比如esbuild
或者webpack
。
Browser CDN
kaboom
全局函数:
<script src="https://unpkg.com/kaboom/dist/kaboom.js"></script> <script> kaboom(); </script>
或者跟 es 模块搭配使用:
<script type="module"> import kaboom from "https://unpkg.com/kaboom/dist/kaboom.mjs"; kaboom(); </script>
适用于所有支持 NPM 包的 CDN,例如 jsdelivr、skypack 。
评论