UNPKG

the-world-engine

Version:

three.js based, unity like game engine for browser

98 lines (89 loc) 3.08 kB
import { DEG2RAD } from "three/src/math/MathUtils"; import { Vector2, Vector3 } from "three/src/Three"; import { PolygonShape } from "../../../../box2d.ts/build/index"; import { PrefabRef } from "../../../hierarchy_object/PrefabRef"; import { Color } from "../../../render/Color"; import { CssPolygonRenderer2D } from "../../render/CssPolygonRenderer2D"; import { ObjectAttacher2D } from "../ObjectAttacher2D"; import { getOrCreatePhysicsDebugRenderObject } from "../PhysicsDebugRender"; import { Collider2D } from "./Collider2D"; export class PolygonCollider2D extends Collider2D { Va=[ new Vector2(-2, -2), new Vector2(2, -2), new Vector2(2, 2), new Vector2(-2, 2) ]; gl=true; pl=null; rd=null; ml() { if (this.gl) { let e = this.gameObject.getComponent(ObjectAttacher2D); if (!e) e = this.gameObject.addComponent(ObjectAttacher2D); if (this.pl) { this.rd.points = this.Va; } else { const t = getOrCreatePhysicsDebugRenderObject(this.engine); const r = new PrefabRef; this.pl = t.addChildFromBuilder(this.engine.instantiater.buildGameObject(this.gameObject.name + "_debug_polygon").withChild(this.engine.instantiater.buildGameObject("debug_polygon", new Vector3(this.offset.x, this.offset.y, 200)).withComponent(CssPolygonRenderer2D, (e => { e.points = this.Va; e.viewScale = .01; e.color = new Color(0, 0, 0, 0); e.borderWidth = 2; e.borderColor = new Color(1, 1, 0, .3); e.pointerEvents = false; })).getComponent(CssPolygonRenderer2D, r))); this.rd = r.ref; e.target = this.pl; } } } onEnable() { super.onEnable(); this.ml(); } onDisable() { super.onDisable(); if (this.pl) { this.pl.destroy(); this.pl = null; } } _l=[ new PolygonShape ]; createShapes() { const e = this._l[0]; e.Set(this.Va); return this._l; } get points() { return this.Va; } set points(e) { this.Va.length = 0; for (let t = 0; t < e.length; ++t) { this.Va.push(e[t].clone()); } this.updateFixture(); this.ml(); } setShapeToRegularPolygon(e, t) { const r = []; const s = DEG2RAD * 360 / e; for (let i = 0; i < e; ++i) { r.push(new Vector2(t * Math.cos(s * i + Math.PI / 2), t * Math.sin(s * i + Math.PI / 2))); } this.points = r; } get debugDraw() { return this.gl; } set debugDraw(e) { this.gl = e; if (this.enabled && this.gameObject.activeInHierarchy) { if (e) { this.ml(); } else { if (this.pl) { this.pl.destroy(); this.pl = null; } } } } }