@willyuum/pixi-gameobject-system
Version:
77 lines (76 loc) • 2.48 kB
JavaScript
import { Container } from "pixi.js";
import { internal_ComponentManager } from "./ComponentManager";
/**
* GameObject class is a container for components and visual components.
* This class will help to keep game and rendering logic separate
* but still accessible to each other.
*
* Each GameObject will need a holder so if it had visual components,
* it can be added to the stage and be rendered.
*/
export class GameObject {
name;
components = [];
viewComponents = [];
holder;
constructor(name, parent) {
this.name = name;
this.holder = new Container();
this.holder.label = name;
parent.addChild(this.holder);
}
addComponent(component) {
this.components.push(component);
component.gameObject = this;
internal_ComponentManager.addComponent(component);
return component;
}
getComponent(componentClass) {
return this.components.find(c => c instanceof componentClass);
}
removeComponent(component) {
const index = this.components.indexOf(component);
if (index !== -1) {
this.components.splice(index, 1);
component.enabled = false;
return true;
}
return false;
}
addVisualComponent(viewComponent) {
this.viewComponents.push(viewComponent);
this.holder.addChild(viewComponent);
return viewComponent;
}
getVisualComponent(componentClass) {
return this.viewComponents.find(vc => vc instanceof componentClass);
}
removeVisualComponent(viewComponent) {
const index = this.viewComponents.indexOf(viewComponent);
if (index !== -1) {
this.viewComponents.splice(index, 1);
}
}
destroy() {
// Destroy all visual components
for (const view of this.viewComponents) {
if (view.parent) {
view.parent.removeChild(view);
}
view.destroy({ children: true });
}
this.viewComponents.length = 0;
// Destroy all components
for (const component of this.components) {
component.destroy();
}
this.components.length = 0;
// Remove and destroy the holder
if (this.holder.parent) {
this.holder.parent.removeChild(this.holder);
}
this.holder.destroy({ children: true });
// Break references to allow GC
this.holder = null;
}
}