diff options
author | Elizabeth Hunt <elizabeth.hunt@simponic.xyz> | 2023-08-26 17:55:27 -0600 |
---|---|---|
committer | Elizabeth Hunt <elizabeth.hunt@simponic.xyz> | 2023-08-26 17:55:27 -0600 |
commit | 6ce6946a4401d2ee6fa5cb747fab7d4c658a63c8 (patch) | |
tree | e60767dc5295edf379cf421e20171dc418e548b7 /engine/systems/NetworkUpdate.ts | |
parent | 594921352c8d82fe5f1a6201a4d5f9fbd9b719fc (diff) | |
download | jumpstorm-6ce6946a4401d2ee6fa5cb747fab7d4c658a63c8.tar.gz jumpstorm-6ce6946a4401d2ee6fa5cb747fab7d4c658a63c8.zip |
add entity updates over network!
Diffstat (limited to 'engine/systems/NetworkUpdate.ts')
-rw-r--r-- | engine/systems/NetworkUpdate.ts | 40 |
1 files changed, 34 insertions, 6 deletions
diff --git a/engine/systems/NetworkUpdate.ts b/engine/systems/NetworkUpdate.ts index bcfb71e..6d13574 100644 --- a/engine/systems/NetworkUpdate.ts +++ b/engine/systems/NetworkUpdate.ts @@ -1,10 +1,12 @@ import { System, SystemNames } from '.'; import { Game } from '../Game'; -import { ComponentNames, NetworkUpdateable } from '../components'; +import { ComponentNames } from '../components'; import { type MessageQueueProvider, type MessagePublisher, - type MessageProcessor + type MessageProcessor, + MessageType, + EntityUpdateBody } from '../network'; export class NetworkUpdate extends System { @@ -12,6 +14,8 @@ export class NetworkUpdate extends System { private publisher: MessagePublisher; private messageProcessor: MessageProcessor; + private entityUpdateTimers: Map<string, number>; + constructor( queueProvider: MessageQueueProvider, publisher: MessagePublisher, @@ -22,23 +26,47 @@ export class NetworkUpdate extends System { this.queueProvider = queueProvider; this.publisher = publisher; this.messageProcessor = messageProcessor; + + this.entityUpdateTimers = new Map(); } - public update(_dt: number, game: Game) { + public update(dt: number, game: Game) { + // 1. process new messages this.queueProvider .getNewMessages() .forEach((message) => this.messageProcessor.process(message)); this.queueProvider.clearMessages(); + // 2. send entity updates + const updateMessages: EntityUpdateBody[] = []; game.forEachEntityWithComponent( ComponentNames.NetworkUpdateable, (entity) => { - const networkUpdateComponent = entity.getComponent<NetworkUpdateable>( - ComponentNames.NetworkUpdateable - ); + let timer = this.entityUpdateTimers.get(entity.id) ?? dt; + timer -= dt; + this.entityUpdateTimers.set(entity.id, timer); + + if (timer > 0) return; + this.entityUpdateTimers.set(entity.id, this.getNextUpdateTimeMs()); + + if (entity.hasComponent(ComponentNames.NetworkUpdateable)) { + updateMessages.push({ + id: entity.id, + args: entity.serialize() + }); + } } ); + this.publisher.addMessage({ + type: MessageType.UPDATE_ENTITIES, + body: updateMessages + }); + // 3. publish changes this.publisher.publish(); } + + private getNextUpdateTimeMs() { + return Math.random() * 70 + 50; + } } |