This commit is contained in:
Andras Schmelczer 2026-09-14 08:04:19 +01:00
commit c074bc2645
39 changed files with 178 additions and 148 deletions

View file

@ -1,4 +1,17 @@
import { CharacterTeam } from 'shared';
export interface GameEvents { export interface GameEvents {
addPoints(blue: number, red: number): void; addPoints(blue: number, red: number): void;
announce(text: string): void; announce(text: string): void;
} }
export const addPointsForTeam = (
game: GameEvents,
team: CharacterTeam,
points: number,
): void => {
game.addPoints(
team === CharacterTeam.blue ? points : 0,
team === CharacterTeam.red ? points : 0,
);
};

View file

@ -32,14 +32,7 @@ const io = new IoServer(server, {
const gameServer = new GameServer(io, options); const gameServer = new GameServer(io, options);
app.use( app.use(cors({ origin: true, credentials: true }));
cors({
origin: (_, callback) => {
callback(null, true);
},
credentials: true,
}),
);
app.get(serverInformationEndpoint, (_, res) => { app.get(serverInformationEndpoint, (_, res) => {
res.json(gameServer.serverInfo); res.json(gameServer.serverInfo);

View file

@ -13,6 +13,7 @@ import {
clamp01, clamp01,
strengthToCharge, strengthToCharge,
stepCharacterMovement, stepCharacterMovement,
applyForce,
applyLeapImpulse, applyLeapImpulse,
decayMomentum, decayMomentum,
tickPlanetDetachment, tickPlanetDetachment,
@ -27,12 +28,13 @@ import {
rightFootOffset, rightFootOffset,
boundRadius, boundRadius,
} from 'shared'; } from 'shared';
import { addPointsForTeam } from '../game-events';
import { Physical } from '../physics/physical'; import { Physical } from '../physics/physical';
import { CirclePhysical } from './circle-physical'; import { CirclePhysical } from './circle-physical';
import { PhysicalContainer } from '../physics/physical-container'; import { PhysicalContainer } from '../physics/physical-container';
import { BoundingBox } from '../physics/bounding-box'; import { BoundingBox } from '../physics/bounding-box';
import { ProjectilePhysical } from './projectile-physical'; import { ProjectilePhysical } from './projectile-physical';
import { PlanetPhysical, planetsIn } from './planet-physical'; import { PlanetPhysical, planetsNear } from './planet-physical';
const placeholder = new Circle(vec2.create(), 0); const placeholder = new Circle(vec2.create(), 0);
@ -99,8 +101,7 @@ export class CharacterPhysical extends CharacterBase implements Physical {
} }
private readonly movementWorld: CharacterWorld = { private readonly movementWorld: CharacterWorld = {
groundsNear: (center, radius) => groundsNear: (center, radius) => planetsNear(this.container, center, radius),
planetsIn(this.container.findIntersecting(BoundingBox.ofCircle(center, radius))),
stepBody: (body, deltaTimeInSeconds) => { stepBody: (body, deltaTimeInSeconds) => {
const hit = (body as CirclePhysical).stepManually(deltaTimeInSeconds); const hit = (body as CirclePhysical).stepManually(deltaTimeInSeconds);
return hit instanceof PlanetPhysical ? hit : undefined; return hit instanceof PlanetPhysical ? hit : undefined;
@ -139,12 +140,7 @@ export class CharacterPhysical extends CharacterBase implements Physical {
} }
public get boundingBox(): BoundingBox { public get boundingBox(): BoundingBox {
const center = this.center; return this.box.setCircle(this.center, boundRadius);
this.box.xMin = center[0] - boundRadius;
this.box.xMax = center[0] + boundRadius;
this.box.yMin = center[1] - boundRadius;
this.box.yMax = center[1] + boundRadius;
return this.box;
} }
public get gameObject(): this { public get gameObject(): this {
@ -309,11 +305,9 @@ export class CharacterPhysical extends CharacterBase implements Physical {
this.remoteCall('onDie'); this.remoteCall('onDie');
if (killedInCombat) { if (killedInCombat) {
const points = settings.playerKillPoint; const opposingTeam =
this.container.game.addPoints( this.team === CharacterTeam.blue ? CharacterTeam.red : CharacterTeam.blue;
this.team === CharacterTeam.blue ? 0 : points, addPointsForTeam(this.container.game, opposingTeam, settings.playerKillPoint);
this.team === CharacterTeam.red ? 0 : points,
);
} }
} }
@ -427,7 +421,7 @@ export class CharacterPhysical extends CharacterBase implements Physical {
let grounded = false; let grounded = false;
for (const part of this.parts) { for (const part of this.parts) {
vec2.copy(part.velocity, this.bodyVelocity); vec2.copy(part.velocity, this.bodyVelocity);
part.applyForce(sumGravity(planets, part.center), deltaTime); applyForce(part, sumGravity(planets, part.center), deltaTime);
if (part.stepManually(deltaTime) instanceof PlanetPhysical) { if (part.stepManually(deltaTime) instanceof PlanetPhysical) {
grounded = true; grounded = true;
} }

View file

@ -1,5 +1,5 @@
import { vec2 } from 'gl-matrix'; import { vec2 } from 'gl-matrix';
import { applyForce, Circle, GameObject, resolveCircleMovement } from 'shared'; import { Circle, GameObject, resolveCircleMovement } from 'shared';
import { BoundingBox } from '../physics/bounding-box'; import { BoundingBox } from '../physics/bounding-box';
import { PhysicalContainer } from '../physics/physical-container'; import { PhysicalContainer } from '../physics/physical-container';
import { Physical } from '../physics/physical'; import { Physical } from '../physics/physical';
@ -22,11 +22,7 @@ export class CirclePhysical extends Circle implements Physical {
} }
public get boundingBox(): BoundingBox { public get boundingBox(): BoundingBox {
this.box.xMin = this.center[0] - this.radius; return this.box.setCircle(this.center, this.radius);
this.box.xMax = this.center[0] + this.radius;
this.box.yMin = this.center[1] - this.radius;
this.box.yMax = this.center[1] + this.radius;
return this.box;
} }
public get gameObject(): GameObject { public get gameObject(): GameObject {
@ -37,10 +33,6 @@ export class CirclePhysical extends Circle implements Physical {
this.owner.onCollision?.(other); this.owner.onCollision?.(other);
} }
public applyForce(force: vec2, timeInSeconds: number) {
applyForce(this, force, timeInSeconds);
}
public stepManually( public stepManually(
deltaTimeInSeconds: number, deltaTimeInSeconds: number,
possibleIntersectors?: Array<Physical>, possibleIntersectors?: Array<Physical>,

View file

@ -10,15 +10,23 @@ import {
PropertyUpdatesForObject, PropertyUpdatesForObject,
UpdatePropertyCommand, UpdatePropertyCommand,
} from 'shared'; } from 'shared';
import { GameEvents } from '../game-events'; import { addPointsForTeam, GameEvents } from '../game-events';
import { BoundingBox } from '../physics/bounding-box'; import { BoundingBox } from '../physics/bounding-box';
import { Physical } from '../physics/physical'; import { Physical } from '../physics/physical';
import { PhysicalContainer } from '../physics/physical-container';
import { LampPhysical } from './lamp-physical'; import { LampPhysical } from './lamp-physical';
import type { CharacterPhysical } from './character-physical'; import type { CharacterPhysical } from './character-physical';
export const planetsIn = (objects: Array<Physical>): Array<PlanetPhysical> => export const planetsIn = (objects: Array<Physical>): Array<PlanetPhysical> =>
objects.filter((o): o is PlanetPhysical => o instanceof PlanetPhysical); objects.filter((o): o is PlanetPhysical => o instanceof PlanetPhysical);
export const planetsNear = (
container: PhysicalContainer,
center: vec2,
radius: number,
): Array<PlanetPhysical> =>
planetsIn(container.findIntersecting(BoundingBox.ofCircle(center, radius)));
export class PlanetPhysical extends PlanetBase implements Physical { export class PlanetPhysical extends PlanetBase implements Physical {
public readonly boundingBox: BoundingBox; public readonly boundingBox: BoundingBox;
public readonly sizePointMultiplier: number; public readonly sizePointMultiplier: number;
@ -80,11 +88,7 @@ export class PlanetPhysical extends PlanetBase implements Physical {
} }
private awardToOwner(base: number) { private awardToOwner(base: number) {
const value = Math.round(base * this.sizePointMultiplier); addPointsForTeam(this.game, this.team, Math.round(base * this.sizePointMultiplier));
this.game.addPoints(
this.team === CharacterTeam.blue ? value : 0,
this.team === CharacterTeam.red ? value : 0,
);
} }
private resolveCapture(deltaTime: number) { private resolveCapture(deltaTime: number) {

View file

@ -84,10 +84,11 @@ export class ProjectilePhysical extends ProjectileBase implements Physical {
} }
public onCollision(other: GameObject) { public onCollision(other: GameObject) {
if ( if (other instanceof CharacterPhysical && other.team === this.team) {
!(other instanceof CharacterPhysical && other.team === this.team) && return;
this.bounceCount++ === settings.projectileMaxBounceCount }
) { this.bounceCount++;
if (this.bounceCount > settings.projectileMaxBounceCount) {
this.destroy(); this.destroy();
} }
} }

View file

@ -17,6 +17,14 @@ export class BoundingBox {
); );
} }
public setCircle(center: vec2, radius: number): BoundingBox {
this.xMin = center[0] - radius;
this.xMax = center[0] + radius;
this.yMin = center[1] - radius;
this.yMax = center[1] + radius;
return this;
}
public intersects(other: BoundingBox): boolean { public intersects(other: BoundingBox): boolean {
return ( return (
this.xMin < other.xMax && this.xMin < other.xMax &&

View file

@ -1,13 +1,10 @@
import { vec2 } from 'gl-matrix'; import { GameObject, Sdf } from 'shared';
import { GameObject } from 'shared';
import { BoundingBox } from './bounding-box'; import { BoundingBox } from './bounding-box';
export interface Physical { export interface Physical extends Sdf {
readonly canCollide: boolean;
readonly boundingBox: BoundingBox; readonly boundingBox: BoundingBox;
readonly gameObject: GameObject; readonly gameObject: GameObject;
distance(target: vec2): number;
step?(deltaTimeInSeconds: number): void; step?(deltaTimeInSeconds: number): void;
onCollision?(other: GameObject): void; onCollision?(other: GameObject): void;
} }

View file

@ -1,5 +1,12 @@
import { vec2 } from 'gl-matrix'; import { vec2 } from 'gl-matrix';
import { PlayerInformation, settings, Random, CharacterTeam, Id } from 'shared'; import {
PlayerInformation,
settings,
Random,
CharacterTeam,
Id,
evaluateSdf,
} from 'shared';
import { PhysicalContainer } from '../physics/physical-container'; import { PhysicalContainer } from '../physics/physical-container';
import { BoundingBox } from '../physics/bounding-box'; import { BoundingBox } from '../physics/bounding-box';
import { PlayerContainer } from './player-container'; import { PlayerContainer } from './player-container';
@ -321,10 +328,7 @@ export class NPC extends PlayerBase {
let traveled = tuning.lineOfSightStartOffset; let traveled = tuning.lineOfSightStartOffset;
const position = vec2.scaleAndAdd(vec2.create(), this.center, direction, traveled); const position = vec2.scaleAndAdd(vec2.create(), this.center, direction, traveled);
while (traveled < totalDistance) { while (traveled < totalDistance) {
let sdf = Infinity; const sdf = evaluateSdf(position, planets);
for (const planet of planets) {
sdf = Math.min(sdf, planet.distance(position));
}
if (sdf < tuning.lineOfSightClearance) { if (sdf < tuning.lineOfSightClearance) {
return false; return false;
} }

View file

@ -12,7 +12,7 @@ import {
import { PhysicalContainer } from '../physics/physical-container'; import { PhysicalContainer } from '../physics/physical-container';
import { BoundingBox } from '../physics/bounding-box'; import { BoundingBox } from '../physics/bounding-box';
import { CharacterPhysical } from '../objects/character-physical'; import { CharacterPhysical } from '../objects/character-physical';
import { PlanetPhysical, planetsIn } from '../objects/planet-physical'; import { PlanetPhysical, planetsNear } from '../objects/planet-physical';
import { PlayerContainer } from './player-container'; import { PlayerContainer } from './player-container';
const maximumNameLength = 40; const maximumNameLength = 40;
@ -65,7 +65,9 @@ export abstract class PlayerBase extends CommandReceiver {
return this.character; return this.character;
} }
public abstract step(deltaTimeInSeconds: number): void; public step(deltaTimeInSeconds: number) {
this.stepLifecycle(deltaTimeInSeconds);
}
protected stepLifecycle(deltaTimeInSeconds: number): CharacterPhysical | undefined { protected stepLifecycle(deltaTimeInSeconds: number): CharacterPhysical | undefined {
if (this.character) { if (this.character) {
@ -89,10 +91,10 @@ export abstract class PlayerBase extends CommandReceiver {
} }
private findSpawnCenter(): vec2 { private findSpawnCenter(): vec2 {
const planets = planetsIn( const planets = planetsNear(
this.objectContainer.findIntersecting( this.objectContainer,
BoundingBox.ofCircle(vec2.create(), settings.worldRadius * 2), vec2.create(),
), settings.worldRadius * 2,
); );
const friendly = planets.filter((p) => p.team === this.team); const friendly = planets.filter((p) => p.team === this.team);

View file

@ -36,9 +36,7 @@ export class PlayerContainer {
); );
for (let i = 0; i < newNpcCount; i++) { for (let i = 0; i < newNpcCount; i++) {
const name = `🤖 ${Random.choose(settings.npcNames)}`; const name = `🤖 ${Random.choose(settings.npcNames)}`;
this.npcs.push( this.npcs.push(new NPC({ name }, this, this.objects, this.getTeamOfNextNpc()));
new NPC({ name }, this, this.objects, this.getTeamOfNextPlayer(true)),
);
} }
} }
@ -102,8 +100,15 @@ export class PlayerContainer {
this._players.forEach((p) => p.sendQueuedCommandsToClient()); this._players.forEach((p) => p.sendQueuedCommandsToClient());
} }
private getTeamOfNextPlayer(isNpc = false): CharacterTeam { private getTeamOfNextPlayer(): CharacterTeam {
const players = isNpc ? this.players : this._players; return this.teamOfNext(this._players);
}
private getTeamOfNextNpc(): CharacterTeam {
return this.teamOfNext(this.players);
}
private teamOfNext(players: Array<PlayerBase>): CharacterTeam {
const blueCount = players.filter((p) => p.team === CharacterTeam.blue).length; const blueCount = players.filter((p) => p.team === CharacterTeam.blue).length;
const redCount = players.filter((p) => p.team === CharacterTeam.red).length; const redCount = players.filter((p) => p.team === CharacterTeam.red).length;

View file

@ -42,9 +42,9 @@ const minimumAspectRatio = 0.2;
const maximumAspectRatio = 8; const maximumAspectRatio = 8;
const sheddableWhenBackedUp: ReadonlyArray<string> = [ const sheddableWhenBackedUp: ReadonlyArray<string> = [
PropertyUpdatesForObjects.type, PropertyUpdatesForObjects.name,
UpdateMinimap.type, UpdateMinimap.name,
InputAcknowledgement.type, InputAcknowledgement.name,
]; ];
export class Player extends PlayerBase { export class Player extends PlayerBase {
@ -68,7 +68,7 @@ export class Player extends PlayerBase {
// Input is untrusted: one non-finite value reaching the simulation leaves a character that never dies. // Input is untrusted: one non-finite value reaching the simulation leaves a character that never dies.
protected commandExecutors: CommandExecutors = { protected commandExecutors: CommandExecutors = {
[SetAspectRatioActionCommand.type]: (v: SetAspectRatioActionCommand) => { [SetAspectRatioActionCommand.name]: (v: SetAspectRatioActionCommand) => {
this.aspectRatio = finiteInRange( this.aspectRatio = finiteInRange(
v.aspectRatio, v.aspectRatio,
minimumAspectRatio, minimumAspectRatio,
@ -76,7 +76,7 @@ export class Player extends PlayerBase {
this.aspectRatio, this.aspectRatio,
); );
}, },
[MoveActionCommand.type]: (c: MoveActionCommand) => { [MoveActionCommand.name]: (c: MoveActionCommand) => {
const direction = finiteVec2(c.direction, 1); const direction = finiteVec2(c.direction, 1);
if (!direction) { if (!direction) {
return; return;
@ -84,7 +84,7 @@ export class Player extends PlayerBase {
this.observeClientTime(c.clientTimeMs); this.observeClientTime(c.clientTimeMs);
this.character?.setMoveDirection(direction); this.character?.setMoveDirection(direction);
}, },
[PrimaryActionCommand.type]: (c: PrimaryActionCommand) => { [PrimaryActionCommand.name]: (c: PrimaryActionCommand) => {
const position = finiteVec2(c.position, settings.maxClientPositionMagnitude); const position = finiteVec2(c.position, settings.maxClientPositionMagnitude);
if (!position) { if (!position) {
return; return;
@ -92,7 +92,7 @@ export class Player extends PlayerBase {
this.observeClientTime(c.clientTimeMs); this.observeClientTime(c.clientTimeMs);
this.character?.shootTowards(position, finiteInRange(c.charge, 0, 1, 0)); this.character?.shootTowards(position, finiteInRange(c.charge, 0, 1, 0));
}, },
[LeapActionCommand.type]: (c: LeapActionCommand) => { [LeapActionCommand.name]: (c: LeapActionCommand) => {
if (!isFiniteNumber(c.clientTimeMs)) { if (!isFiniteNumber(c.clientTimeMs)) {
return; return;
} }
@ -100,7 +100,7 @@ export class Player extends PlayerBase {
this.observeClientTime(c.clientTimeMs); this.observeClientTime(c.clientTimeMs);
this.character?.leap(); this.character?.leap();
}, },
[ClientHeartbeatCommand.type]: (c: ClientHeartbeatCommand) => [ClientHeartbeatCommand.name]: (c: ClientHeartbeatCommand) =>
this.observeClientTime(c.clientTimeMs), this.observeClientTime(c.clientTimeMs),
}; };
@ -150,10 +150,6 @@ export class Player extends PlayerBase {
this.winnerTeam = winnerTeam; this.winnerTeam = winnerTeam;
} }
public step(deltaTimeInSeconds: number) {
this.stepLifecycle(deltaTimeInSeconds);
}
public queueCommandSend(command: Command) { public queueCommandSend(command: Command) {
this.commandsToBeSent.push(command); this.commandsToBeSent.push(command);
} }
@ -273,7 +269,7 @@ export class Player extends PlayerBase {
// Only state the next snapshot regenerates may be dropped; create/delete are one-shot. // Only state the next snapshot regenerates may be dropped; create/delete are one-shot.
if (this.bufferedBytes > settings.maxBufferedBytesPerClient) { if (this.bufferedBytes > settings.maxBufferedBytesPerClient) {
this.commandsToBeSent = this.commandsToBeSent.filter( this.commandsToBeSent = this.commandsToBeSent.filter(
(c) => !sheddableWhenBackedUp.includes(c.type), (c) => !sheddableWhenBackedUp.includes(c.constructor.name),
); );
} }
if (this.commandsToBeSent.length === 0) { if (this.commandsToBeSent.length === 0) {

View file

@ -1,5 +1,5 @@
import { chargeHeldSince } from 'shared'; import { chargeHeldSince } from 'shared';
import { pointer } from './helper/pointer'; import { getDisplayPosition } from './helper/pointer';
let element: HTMLElement | undefined; let element: HTMLElement | undefined;
let heldSince = 0; let heldSince = 0;
@ -42,7 +42,7 @@ function updateChargeIndicator() {
element.classList.toggle('full', charge >= 1); element.classList.toggle('full', charge >= 1);
if (isFollowingPointer) { if (isFollowingPointer) {
const cursor = pointer.displayPosition; const cursor = getDisplayPosition();
if (cursor) { if (cursor) {
element.style.left = `${cursor[0]}px`; element.style.left = `${cursor[0]}px`;
element.style.top = `${cursor[1]}px`; element.style.top = `${cursor[1]}px`;

View file

@ -10,7 +10,7 @@ import {
localCharacterPredictor, localCharacterPredictor,
} from '../helper/prediction/local-character-predictor'; } from '../helper/prediction/local-character-predictor';
export abstract class InputGenerator { export class InputGenerator {
constructor(protected readonly onCommand: (command: Command) => void) {} constructor(protected readonly onCommand: (command: Command) => void) {}
protected sendMove(direction: vec2) { protected sendMove(direction: vec2) {

View file

@ -1,10 +1,11 @@
import { vec2 } from 'gl-matrix'; import { vec2 } from 'gl-matrix';
import type { Command } from 'shared';
import { InputGenerator } from './input-generator'; import { InputGenerator } from './input-generator';
export class KeyboardListener extends InputGenerator { export class KeyboardListener extends InputGenerator {
private keysDown: Set<string> = new Set(); private keysDown: Set<string> = new Set();
constructor(onCommand: ConstructorParameters<typeof InputGenerator>[0]) { constructor(onCommand: (command: Command) => void) {
super(onCommand); super(onCommand);
addEventListener('keydown', this.keyDownListener); addEventListener('keydown', this.keyDownListener);
addEventListener('keyup', this.keyUpListener); addEventListener('keyup', this.keyUpListener);

View file

@ -1,8 +1,9 @@
import { vec2 } from 'gl-matrix'; import { vec2 } from 'gl-matrix';
import { chargeHeldSince, Command } from 'shared'; import { chargeHeldSince } from 'shared';
import { Game } from '../game'; import type { Command } from 'shared';
import type { Game } from '../game';
import { ChargeIndicator } from '../charge-indicator'; import { ChargeIndicator } from '../charge-indicator';
import { pointer } from '../helper/pointer'; import { setDisplayPosition } from '../helper/pointer';
import { InputGenerator } from './input-generator'; import { InputGenerator } from './input-generator';
export class MouseListener extends InputGenerator { export class MouseListener extends InputGenerator {
@ -22,7 +23,7 @@ export class MouseListener extends InputGenerator {
} }
private mouseMoveListener = (event: MouseEvent) => { private mouseMoveListener = (event: MouseEvent) => {
pointer.displayPosition = vec2.fromValues(event.clientX, event.clientY); setDisplayPosition(vec2.fromValues(event.clientX, event.clientY));
}; };
private mouseDownListener = (event: MouseEvent) => { private mouseDownListener = (event: MouseEvent) => {

View file

@ -1,7 +1,9 @@
import { vec2 } from 'gl-matrix'; import { vec2 } from 'gl-matrix';
import { chargeHeldSince, Command, settings } from 'shared'; import { chargeHeldSince, settings } from 'shared';
import { Game } from '../game'; import type { Command } from 'shared';
import type { Game } from '../game';
import { ChargeIndicator } from '../charge-indicator'; import { ChargeIndicator } from '../charge-indicator';
import { centeredTransform } from '../helper/centered-transform';
import { InputGenerator } from './input-generator'; import { InputGenerator } from './input-generator';
const deadZone = 8; const deadZone = 8;
@ -104,11 +106,14 @@ export class TouchListener extends InputGenerator {
this.primaryDownAt = null; this.primaryDownAt = null;
ChargeIndicator.end(); ChargeIndicator.end();
this.overlay.appendChild(this.joystick); this.overlay.appendChild(this.joystick);
this.joystick.style.transform = `translateX(${this.touchStartPosition[0]}px) translateY(${this.touchStartPosition[1]}px) translateX(-50%) translateY(-50%)`; this.joystick.style.transform = centeredTransform(
this.touchStartPosition[0],
this.touchStartPosition[1],
);
} }
vec2.scale(delta, delta, Math.min(1, joystickMaxLength / deltaLength)); vec2.scale(delta, delta, Math.min(1, joystickMaxLength / deltaLength));
this.joystickButton.style.transform = `translateX(${delta[0]}px) translateY(${delta[1]}px) translateX(-50%) translateY(-50%)`; this.joystickButton.style.transform = centeredTransform(delta[0], delta[1]);
if (deltaLength > deadZone) { if (deltaLength > deadZone) {
vec2.set(delta, delta[0], -delta[1]); vec2.set(delta, delta[0], -delta[1]);

View file

@ -1,5 +1,5 @@
import { settings } from 'shared'; import { settings } from 'shared';
import { pointer } from './helper/pointer'; import { getDisplayPosition } from './helper/pointer';
let root: HTMLElement | undefined; let root: HTMLElement | undefined;
let killfeed: HTMLElement | undefined; let killfeed: HTMLElement | undefined;
@ -20,7 +20,7 @@ function ensureRoot(): { root: HTMLElement; killfeed: HTMLElement } {
} }
function focusPoint(): { x: number; y: number } { function focusPoint(): { x: number; y: number } {
const cursor = pointer.displayPosition; const cursor = getDisplayPosition();
if (cursor) { if (cursor) {
return { x: cursor[0], y: cursor[1] }; return { x: cursor[0], y: cursor[1] };
} }

View file

@ -34,6 +34,7 @@ import parser from 'socket.io-msgpack-parser';
import { CharacterShape } from './shapes/character-shape'; import { CharacterShape } from './shapes/character-shape';
import { PlanetShape } from './shapes/planet-shape'; import { PlanetShape } from './shapes/planet-shape';
import { serverTimeline } from './helper/server-timeline'; import { serverTimeline } from './helper/server-timeline';
import { centeredTransform } from './helper/centered-transform';
import { import {
localCharacterPredictor, localCharacterPredictor,
setFrameTimeMs, setFrameTimeMs,
@ -79,21 +80,21 @@ export class Game extends CommandReceiver {
private framesSinceLastLayoutUpdate = 0; private framesSinceLastLayoutUpdate = 0;
protected commandExecutors: CommandExecutors = { protected commandExecutors: CommandExecutors = {
[ServerAnnouncement.type]: (c: ServerAnnouncement) => { [ServerAnnouncement.name]: (c: ServerAnnouncement) => {
this.lastAnnouncementText = c.text; this.lastAnnouncementText = c.text;
this.timeSinceLastAnnouncement = 0; this.timeSinceLastAnnouncement = 0;
}, },
[UpdateGameState.type]: (c: UpdateGameState) => (this.lastGameState = c), [UpdateGameState.name]: (c: UpdateGameState) => (this.lastGameState = c),
[InputAcknowledgement.type]: (c: InputAcknowledgement) => [InputAcknowledgement.name]: (c: InputAcknowledgement) =>
localCharacterPredictor.acknowledge( localCharacterPredictor.acknowledge(
c.clientTimeMs, c.clientTimeMs,
c.movement, c.movement,
c.lastLeapClientTimeMs, c.lastLeapClientTimeMs,
c.ackAgeMs, c.ackAgeMs,
), ),
[GameEndCommand.type]: () => (this.isEnding = true), [GameEndCommand.name]: () => (this.isEnding = true),
[UpdateMinimap.type]: (c: UpdateMinimap) => (this.lastMinimap = c), [UpdateMinimap.name]: (c: UpdateMinimap) => (this.lastMinimap = c),
[GameStartCommand.type]: () => this.initialize(), [GameStartCommand.name]: () => this.initialize(),
}; };
constructor( constructor(
@ -220,6 +221,7 @@ export class Game extends CommandReceiver {
public async start(): Promise<void> { public async start(): Promise<void> {
this.initialize(); this.initialize();
this.resolveStarted();
const noiseTexture = await renderNoise([256, 256], 2, 1); const noiseTexture = await renderNoise([256, 256], 2, 1);
await runAnimation( await runAnimation(
@ -311,7 +313,6 @@ export class Game extends CommandReceiver {
deltaTime: DOMHighResTimeStamp, deltaTime: DOMHighResTimeStamp,
): boolean { ): boolean {
this.renderer = renderer; this.renderer = renderer;
this.resolveStarted();
// The frame timestamp, not performance.now(): dispatch jitter would land in the replay window. // The frame timestamp, not performance.now(): dispatch jitter would land in the replay window.
setFrameTimeMs(currentTime); setFrameTimeMs(currentTime);
deltaTime /= 1000; deltaTime /= 1000;
@ -408,6 +409,10 @@ export class Game extends CommandReceiver {
deltaX = (deltaY * dx) / dy; deltaX = (deltaY * dx) / dy;
} }
this.keystoneArrow.style.transform = `translateX(${width / 2 + deltaX}px) translateY(${height / 2 + deltaY}px) translateX(-50%) translateY(-50%) rotate(${angle + Math.PI / 2}rad)`; this.keystoneArrow.style.transform = centeredTransform(
width / 2 + deltaX,
height / 2 + deltaY,
` rotate(${angle + Math.PI / 2}rad)`,
);
} }
} }

View file

@ -0,0 +1,2 @@
export const centeredTransform = (x: number, y: number, extra = ''): string =>
`translateX(${x}px) translateY(${y}px) translateX(-50%) translateY(-50%)${extra}`;

Some files were not shown because too many files have changed in this diff Show more