A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
import {
defineSystem, Query, Mut, Res, ResMut, Commands,
Input, Text, UIVisual, Transform, Sprite,
} from 'esengine';
import {
Player, Hull, ScoreDisplay, HealthHeart, HullBarMask,
GameOverScreen, Enemy, Bullet, Explosion,
} from '../components';
import { GameState, PLAYER_START_Y, HULL_BAR_WIDTH } from '../resources';
export const hudSystem = defineSystem(
[
Res(GameState), Query(Mut(Text), ScoreDisplay), Query(Hull, Player),
Query(Mut(UIVisual), HealthHeart), Query(Mut(Sprite), HullBarMask),
],
(state, scoreQuery, playerQuery, heartQuery, barMaskQuery) => {
for (const [_entity, text] of scoreQuery) {
text.content = `SCORE: ${state.score}`;
}
for (const [_entity, health] of playerQuery) {
// The bar's reading is the MASK's width: the fill keeps its own size and is
// cut to this, so the artwork never stretches with the number.
const fraction = health.maxValue > 0
? Math.max(0, Math.min(1, health.value / health.maxValue))
: 0;
for (const [_mEntity, maskSprite] of barMaskQuery) {
maskSprite.size = { x: HULL_BAR_WIDTH * fraction, y: maskSprite.size.y };
}
let heartIndex = 0;
for (const [_hEntity, visual] of heartQuery) {
visual.color = heartIndex < health.value
? { r: 1, g: 1, b: 1, a: 1 }
: { r: 0.3, g: 0.3, b: 0.3, a: 0.4 };
heartIndex++;
}
}
},
{ name: 'HUDSystem' }
);
export const gameOverSystem = defineSystem(
[
Res(Input), ResMut(GameState), Commands(),
Query(Mut(Transform), Mut(Hull), Player),
Query(Mut(Text), GameOverScreen),
Query(Enemy),
Query(Bullet),
Query(Explosion),
],
(input, stateMut, cmds, playerQuery, gameOverQuery, enemyQuery, bulletQuery, explosionQuery) => {
const state = stateMut.get();
for (const [_entity, _transform, health] of playerQuery) {
if (health.value <= 0 && !state.gameOver) {
state.gameOver = true;
for (const [_goEntity, text] of gameOverQuery) {
text.content = `GAME OVER\nSCORE: ${state.score}\nPress R to restart`;
}
}
}
if (state.gameOver && input.isKeyPressed('KeyR')) {
state.score = 0;
state.gameOver = false;
state.spawnTimer = 0;
state.difficulty = 1;
state.shootCooldown = 0;
for (const [_entity, transform, health] of playerQuery) {
health.value = health.maxValue;
transform.position.x = 0;
transform.position.y = PLAYER_START_Y;
}
for (const [_goEntity, text] of gameOverQuery) {
text.content = '';
}
for (const [entity] of enemyQuery) {
cmds.despawn(entity);
}
for (const [entity] of bulletQuery) {
cmds.despawn(entity);
}
for (const [entity] of explosionQuery) {
cmds.despawn(entity);
}
}
},
{ name: 'GameOverSystem' }
);