UNPKG

the-world-engine

Version:

three.js based, unity like game engine for browser

78 lines (75 loc) 1.93 kB
import { BodyType } from "../../../box2d.ts/build/index"; import { FixtureGroup } from "./FixtureGroup"; import { PhysicsMaterial2D } from "./PhysicsMaterial2D"; export class PhysicsObject2D { gameObject; body; At; Ki=null; Qi=null; Ui=[]; constructor(i, t, s) { this.gameObject = i; this.body = t; this.At = s; t.SetUserData(this); } addRigidBody(i) { if (this.Qi) throw new Error("RigidBody already exists"); this.Qi = i; return this; } removeRigidBody() { this.Qi = null; this.body.SetType(BodyType.b2_kinematicBody); this.body.SetBullet(false); this.body.SetEnabled(true); this.Wi(); } addCollider(i) { this.Ui.push(i); return new FixtureGroup(this.body, this); } removeCollider(i, t) { const s = this.Ui.indexOf(i); if (s === -1) throw new Error("Collider not found"); this.Ui.splice(s, 1); t.clear(); this.Wi(); } Wi() { if (this.Ui.length === 0 && this.Qi === null) { this.body.GetWorld().DestroyBody(this.body); this.At(); } } setSharedPhysicsMaterial(i) { if (i) { if (!this.Ki) { this.Ki = new PhysicsMaterial2D(i.friction, i.bounciness); this.Ki.onChanged.addListener(this.Xi); } else { this.Ki.copy(i); } } else { this.Ki?.onChanged.removeListener(this.Xi); this.Ki = null; } this.Xi(); } Xi=() => { const i = this.Ui; for (let t = 0; t < i.length; ++t) { i[t].updateFixturesMaterialInfo(); } }; get sharedMaterial() { return this.Ki; } get rigidbody() { return this.Qi; } get colliders() { return this.Ui; } }