ecspresso
Version:
A minimal Entity-Component-System library for typescript and javascript.
5 lines (3 loc) • 2.27 kB
JavaScript
var R=((k)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(k,{get:(E,H)=>(typeof require<"u"?require:E)[H]}):k)(function(k){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+k+'" is not supported')});import{definePlugin as q}from"ecspresso";function F(k,E,H=32){return{detector:{range:k,layerFilter:E,maxResults:H}}}function g(k,E){return(k.getComponent(E,"detectedEntities")?.entities.length??0)>0}function C(k,E){return k.distanceSq-E.distanceSq}function x(k){let{systemGroup:E="ai",priority:H=500,phase:P="update"}=k??{},V=new Map,K=new Set,W=[],Z=new WeakMap;return q("detection").withComponentTypes().withEventTypes().withLabels().withGroups().requires().install((_)=>{_.registerDispose("detector",({entityId:X})=>{V.delete(X)}),_.addSystem("detection-scan").setPriority(H).inPhase(P).inGroup(E).addQuery("detectors",{with:["detector","worldTransform"]}).setProcess(({queries:X,ecs:z})=>{let b=z.getResource("spatialIndex");for(let A of X.detectors){let{detector:J,worldTransform:O}=A.components;W.length=0,b.queryRadiusInto(O.x,O.y,J.range,W);let L=[],Q=Z.get(J.layerFilter);if(!Q)Q=new Set(J.layerFilter),Z.set(J.layerFilter,Q);for(let j of W){if(j===A.id)continue;if(!z.getEntity(j))continue;let N=z.getComponent(j,"collisionLayer");if(!N)continue;if(!Q.has(N.layer))continue;let Y=z.getComponent(j,"worldTransform");if(!Y)continue;let D=Y.x-O.x,G=Y.y-O.y;L.push({entityId:j,distanceSq:D*D+G*G})}L.sort(C);let U=L.length>J.maxResults?L.slice(0,J.maxResults):L,$=z.getComponent(A.id,"detectedEntities");if($)$.entities=U,z.markChanged(A.id,"detectedEntities");else z.addComponent(A.id,"detectedEntities",{entities:U});let M=V.get(A.id);K.clear();for(let j of U)K.add(j.entityId);if(M){for(let j of K)if(!M.has(j))z.eventBus.publish("detectionGained",{entityId:A.id,detectedId:j});for(let j of M)if(!K.has(j))z.eventBus.publish("detectionLost",{entityId:A.id,lostId:j});M.clear();for(let j of K)M.add(j)}else{let j=new Set;for(let N of U)j.add(N.entityId),z.eventBus.publish("detectionGained",{entityId:A.id,detectedId:N.entityId});V.set(A.id,j)}}})})}export{g as hasDetectedTargets,F as createDetector,x as createDetectionPlugin};
//# debugId=9C433B1DED88EF8264756E2164756E21
//# sourceMappingURL=detection.js.map