Skip to content

Commit

Permalink
fix: remove lags on low frame rate
Browse files Browse the repository at this point in the history
  • Loading branch information
sapomaro committed Jul 30, 2023
1 parent 7f973c8 commit d90acb3
Showing 1 changed file with 28 additions and 7 deletions.
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 d90acb3

Please sign in to comment.