refactor(framework): simplify spawner state management
Consolidate object and data tracking into a single Map in `spawnEffect` to improve clarity and reduce redundant lookups. Also switch to type-only imports for Phaser.
This commit is contained in:
parent
648e801dad
commit
b0e74a5257
|
|
@ -1,5 +1,6 @@
|
|||
import Phaser from 'phaser';
|
||||
import { effect } from '@preact/signals-core';
|
||||
import { effect } from "@preact/signals-core";
|
||||
|
||||
import type Phaser from "phaser";
|
||||
|
||||
type GO = Phaser.GameObjects.GameObject;
|
||||
|
||||
|
|
@ -19,8 +20,7 @@ export interface Spawner<TData, TObject extends GO = GO> {
|
|||
export function spawnEffect<TData, TObject extends GO = GO>(
|
||||
spawner: Spawner<TData, TObject>,
|
||||
): () => void {
|
||||
const objects = new Map<string, TObject>();
|
||||
const spawnData = new Map<string, TData>();
|
||||
const entries = new Map<string, { object: TObject; data: TData }>();
|
||||
|
||||
return effect(() => {
|
||||
const current = new Set<string>();
|
||||
|
|
@ -29,25 +29,23 @@ export function spawnEffect<TData, TObject extends GO = GO>(
|
|||
const key = spawner.getKey(t);
|
||||
current.add(key);
|
||||
|
||||
const existing = objects.get(key);
|
||||
const existing = entries.get(key);
|
||||
if (!existing) {
|
||||
const obj = spawner.onSpawn(t);
|
||||
if (obj) {
|
||||
spawnData.set(key, t);
|
||||
objects.set(key, obj);
|
||||
entries.set(key, { object: obj, data: t });
|
||||
}
|
||||
} else {
|
||||
if(spawnData.get(key) === t) continue;
|
||||
spawner.onUpdate(t, existing);
|
||||
spawnData.set(key, t);
|
||||
if (existing.data === t) continue;
|
||||
spawner.onUpdate(t, existing.object);
|
||||
existing.data = t;
|
||||
}
|
||||
}
|
||||
|
||||
for (const [key, obj] of objects) {
|
||||
for (const [key, entry] of entries) {
|
||||
if (!current.has(key)) {
|
||||
spawner.onDespawn(obj, spawnData.get(key)!);
|
||||
objects.delete(key);
|
||||
spawnData.delete(key);
|
||||
spawner.onDespawn(entry.object, entry.data);
|
||||
entries.delete(key);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in New Issue