Skip to content

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.

1.1 KB
Raw Blame
import {
    defineSystem, Query, Mut, Res, Time, Input,
    CharacterController2D,
} from 'esengine';
import { Player } from '../components';

// Pixel-space gravity (the scene's Canvas sets pixelsPerUnit = 1). Tuned for the
// 18px tiles: a jump clears ~3 tiles and the fall feels snappy.
const GRAVITY = -1200;

export const playerSystem = defineSystem(
    [Query(Mut(CharacterController2D), Player), Res(Time), Res(Input)],
    (players, time, input) => {
        for (const [, cc, player] of players) {
            let moveX = 0;
            if (input.isKeyDown('ArrowLeft') || input.isKeyDown('KeyA')) moveX -= 1;
            if (input.isKeyDown('ArrowRight') || input.isKeyDown('KeyD')) moveX += 1;
            cc.velocity.x = moveX * player.speed;

            cc.velocity.y += GRAVITY * time.fixedDelta;

            const jump = input.isKeyPressed('Space')
                || input.isKeyPressed('ArrowUp')
                || input.isKeyPressed('KeyW');
            if (cc.isOnFloor && jump) cc.velocity.y = player.jumpForce;
        }
    },
    { name: 'PlayerSystem' },
);