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;
|
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>(
|
export function spawnEffect<TData, TObject extends GO = GO>(
|
||||||
spawner: Spawner<TData, TObject>,
|
spawner: Spawner<TData, TObject>,
|
||||||
): () => void {
|
): () => void {
|
||||||
const objects = new Map<string, TObject>();
|
const entries = new Map<string, { object: TObject; data: TData }>();
|
||||||
const spawnData = new Map<string, TData>();
|
|
||||||
|
|
||||||
return effect(() => {
|
return effect(() => {
|
||||||
const current = new Set<string>();
|
const current = new Set<string>();
|
||||||
|
|
@ -29,25 +29,23 @@ export function spawnEffect<TData, TObject extends GO = GO>(
|
||||||
const key = spawner.getKey(t);
|
const key = spawner.getKey(t);
|
||||||
current.add(key);
|
current.add(key);
|
||||||
|
|
||||||
const existing = objects.get(key);
|
const existing = entries.get(key);
|
||||||
if (!existing) {
|
if (!existing) {
|
||||||
const obj = spawner.onSpawn(t);
|
const obj = spawner.onSpawn(t);
|
||||||
if (obj) {
|
if (obj) {
|
||||||
spawnData.set(key, t);
|
entries.set(key, { object: obj, data: t });
|
||||||
objects.set(key, obj);
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if(spawnData.get(key) === t) continue;
|
if (existing.data === t) continue;
|
||||||
spawner.onUpdate(t, existing);
|
spawner.onUpdate(t, existing.object);
|
||||||
spawnData.set(key, t);
|
existing.data = t;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const [key, obj] of objects) {
|
for (const [key, entry] of entries) {
|
||||||
if (!current.has(key)) {
|
if (!current.has(key)) {
|
||||||
spawner.onDespawn(obj, spawnData.get(key)!);
|
spawner.onDespawn(entry.object, entry.data);
|
||||||
objects.delete(key);
|
entries.delete(key);
|
||||||
spawnData.delete(key);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue