Skip to content

Commit 9805f50

Browse files
Chau TranChau Tran
Chau Tran
authored and
Chau Tran
committed
feat(cannon): migrate ray
1 parent a4f0e43 commit 9805f50

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

libs/cannon/services/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
export * from './body';
22
export * from './constraint';
3+
export * from './ray';
34
export * from './spring';

libs/cannon/services/src/ray.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { Injector, effect, inject, runInInjectionContext, untracked } from '@angular/core';
2+
import { RayMode, RayOptions, RayhitEvent } from '@pmndrs/cannon-worker-api';
3+
import { NgtAnyRecord, assertInjectionContext, makeId } from 'angular-three';
4+
import { NGTC_PHYSICS_API } from 'angular-three-cannon';
5+
6+
export interface NgtcRayOptions {
7+
options: () => RayOptions;
8+
callback: (e: RayhitEvent) => void;
9+
injector?: Injector;
10+
deps?: () => NgtAnyRecord;
11+
}
12+
13+
export function injectRaycastClosest(opts: NgtcRayOptions) {
14+
return injectRay('Closest', opts);
15+
}
16+
17+
export function injectRaycastAny(opts: NgtcRayOptions) {
18+
return injectRay('Any', opts);
19+
}
20+
21+
export function useRaycastAll(opts: NgtcRayOptions) {
22+
return injectRay('All', opts);
23+
}
24+
25+
function injectRay(mode: RayMode, { options, callback, deps = () => ({}), injector }: NgtcRayOptions) {
26+
injector = assertInjectionContext(injectRay, injector);
27+
return runInInjectionContext(injector, () => {
28+
const physicsApi = inject(NGTC_PHYSICS_API);
29+
const { worker, events } = physicsApi();
30+
const uuid = makeId();
31+
32+
effect((onCleanup) => {
33+
deps();
34+
events[uuid] = { rayhit: callback };
35+
worker.addRay({ props: { ...untracked(options), mode }, uuid });
36+
onCleanup(() => {
37+
worker.removeRay({ uuid });
38+
delete events[uuid];
39+
});
40+
});
41+
});
42+
}

0 commit comments

Comments
 (0)