Skip to content

Commit

Permalink
fix: remove game lags on low frame rate (#110)
Browse files Browse the repository at this point in the history
  • Loading branch information
sapomaro authored Aug 5, 2023
1 parent 7f973c8 commit 9b2115b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 8 deletions.
2 changes: 1 addition & 1 deletion packages/client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"dev": "vite --host 0.0.0.0",
"build:ssr": "tsc && vite build --config ssr.config.ts",
"build:client": "tsc && vite build --config vite.config.ts",
"build": "yarn build:ssr && yarn build:client",
Expand Down
35 changes: 28 additions & 7 deletions packages/client/src/game/services/Loop/Loop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,19 @@ import { EntityEvent } from '../../entities/Entity/typings';
import { type LoopDelays, type LoopIntervals } from './typings';

export class Loop {
/** Минимальное время игрового цикла в миллисекундах */
loopTimeMs = 16;
/** Количество игровых циклов, которые могут быть выполнены за раз в случае задержек */
maxConsecutiveLoops = 4;
/** Счётчик игровых циклов */
loopCount = 0;
/** Список внутриигровых таймаутов */
loopDelays: LoopDelays = {};
/** Список внутриигровых интервалов */
loopIntervals: LoopIntervals = {};
/** Список динамических игровых сущностей */
loopEntities: Set<Tank | Projectile> = new Set();
/** Запущен ли данный сервис */
active = false;
lastTimestamp = 0;

Expand All @@ -28,6 +36,7 @@ export class Loop {

start() {
this.active = true;
this.lastTimestamp = 0;
this.loop();
}

Expand All @@ -53,23 +62,35 @@ export class Loop {
this.loopEntities = new Set();
}

tick() {
++this.loopCount;
this.checkLoopDelays();
this.checkLoopIntervals();
for (const entity of this.loopEntities) {
entity.update();
if (entity.shouldBeDestroyed) {
this.loopEntities.delete(entity);
}
}
}

loop(timestamp = 0) {
if (!this.active) {
return;
}

if (timestamp) {
const timeDifference = timestamp - this.lastTimestamp;

if (timeDifference >= this.loopTimeMs) {
++this.loopCount;
this.checkLoopDelays();
this.checkLoopIntervals();
for (const entity of this.loopEntities) {
entity.update();
if (entity.shouldBeDestroyed) {
this.loopEntities.delete(entity);
if (this.lastTimestamp !== 0) {
const ticksCount = Math.min(Math.round(timeDifference / this.loopTimeMs), this.maxConsecutiveLoops);

for (let i = ticksCount; i > 0; --i) {
this.tick();
}
}

this.lastTimestamp = timestamp;
}
}
Expand Down

0 comments on commit 9b2115b

Please sign in to comment.