@melonjs/rapier3d-adapter 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/LICENSE +21 -0
- package/README.md +341 -2
- package/build/Rapier3dAdapter.d.ts +395 -0
- package/build/Rapier3dAdapter.d.ts.map +1 -0
- package/build/Simulation.d.ts +35 -0
- package/build/Simulation.d.ts.map +1 -0
- package/build/bodies/Motion.d.ts +64 -0
- package/build/bodies/Motion.d.ts.map +1 -0
- package/build/bodies/RuntimeOverrides.d.ts +16 -0
- package/build/bodies/RuntimeOverrides.d.ts.map +1 -0
- package/build/bodies/helpers.d.ts +30 -0
- package/build/bodies/helpers.d.ts.map +1 -0
- package/build/bodies/pose.d.ts +34 -0
- package/build/bodies/pose.d.ts.map +1 -0
- package/build/colliders/CollisionFilters.d.ts +60 -0
- package/build/colliders/CollisionFilters.d.ts.map +1 -0
- package/build/colliders/footprint.d.ts +22 -0
- package/build/colliders/footprint.d.ts.map +1 -0
- package/build/colliders/shapes.d.ts +18 -0
- package/build/colliders/shapes.d.ts.map +1 -0
- package/build/colliders/types.d.ts +48 -0
- package/build/colliders/types.d.ts.map +1 -0
- package/build/contacts/ContactDispatcher.d.ts +80 -0
- package/build/contacts/ContactDispatcher.d.ts.map +1 -0
- package/build/index.d.ts +9 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +1938 -0
- package/build/index.js.map +7 -0
- package/build/joints/Joints.d.ts +51 -0
- package/build/joints/Joints.d.ts.map +1 -0
- package/build/loader.d.ts +20 -0
- package/build/loader.d.ts.map +1 -0
- package/build/math/units.d.ts +44 -0
- package/build/math/units.d.ts.map +1 -0
- package/build/queries/queries.d.ts +40 -0
- package/build/queries/queries.d.ts.map +1 -0
- package/build/types.d.ts +77 -0
- package/build/types.d.ts.map +1 -0
- package/package.json +71 -5
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 1.0.0 - _2026-11-17_
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
- A melonJS physics adapter for Rapier 3D, compiled to WebAssembly: bodies that move and turn in three dimensions, written back onto a `Mesh`, `Sprite3d` or `GLTFModel` ([#1846](https://github.com/melonjs/melonJS/issues/1846))
|
|
7
|
+
- `Box3d`, `Sphere`, `Capsule3d`, `ConvexHull3d` and `TriangleMesh3d` colliders; a 2D shape is refused with the reason
|
|
8
|
+
- The 3D form of the adapter API: `Vector3d` velocities, forces, impulses and positions, `getRotation` / `setRotation`, `getVelocity3d`, `getAngularVelocity3d`, exact `raycast3d` and `querySphere`
|
|
9
|
+
- Joints through `world.addJoint()`, with 3D anchors and axes, joining the bodies as they stand however each is turned; Rapier's own features through `adapter.rapier` and `adapter.world`
|
|
10
|
+
- `isSleeping()`: whether Rapier has put a body to rest, to tell when a shot or a stack has settled
|
|
11
|
+
- `updateShape()` replaces a body's colliders and keeps the body: its pose, velocities, joints, what was set on it at run time and the handle on `renderable.body`
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (C) 2011 - 2026 Olivier Biot (AltByte Pte Ltd)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,342 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @melonjs/rapier3d-adapter
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+

|
|
4
|
+
|
|
5
|
+
[](https://github.com/melonjs/melonJS/blob/master/LICENSE)
|
|
6
|
+
[](https://www.npmjs.com/package/@melonjs/rapier3d-adapter)
|
|
7
|
+
|
|
8
|
+
A [Rapier](https://rapier.rs) 3D physics adapter for melonJS: rigid bodies that move, tumble and stack in three dimensions, for a game drawn with `Camera3d`. Rapier is a rigid-body engine written in Rust and compiled to WebAssembly, with continuous collision detection per body, joints and a character controller.
|
|
9
|
+
|
|
10
|
+
It implements the same `PhysicsAdapter` interface as the other adapters, in its 3D form: bodies are declared with a `bodyDef` made of the 3D shapes, the collision hooks are the same, and the portable calls take a `Vector3d` where a 2D game passes a `Vector2d`. Each frame, a body's position is written to its renderable's `pos` and `depth`, and its turn to its `currentTransform`, so a `Mesh`, a `Sprite3d` or a `GLTFModel` tumbles as it is simulated.
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install @melonjs/rapier3d-adapter
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
[`@dimforge/rapier3d-compat`](https://www.npmjs.com/package/@dimforge/rapier3d-compat) is a regular dependency of the adapter, installed with it: Rapier's build with its WebAssembly embedded in the JavaScript, which works with any bundler, a CDN or plain ES modules. The only peer dependency is `melonjs` 20.16 or later, the first with the 3D shapes.
|
|
19
|
+
|
|
20
|
+
## Usage
|
|
21
|
+
|
|
22
|
+
Create the adapter with `Rapier3dAdapter.create()` and pass it as the `physic` option, with a 3D camera:
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { Rapier3dAdapter } from "@melonjs/rapier3d-adapter";
|
|
26
|
+
import { Application, Box3d, Camera3d, Mesh, video } from "melonjs";
|
|
27
|
+
|
|
28
|
+
const app = new Application(800, 600, {
|
|
29
|
+
parent: "screen",
|
|
30
|
+
renderer: video.WEBGL,
|
|
31
|
+
cameraClass: Camera3d,
|
|
32
|
+
physic: await Rapier3dAdapter.create(),
|
|
33
|
+
});
|
|
34
|
+
await app.init();
|
|
35
|
+
|
|
36
|
+
const crate = new Mesh(0, 0, { model: "crate", texture: "crate", width: 64, height: 64 });
|
|
37
|
+
crate.pos.set(0, -200);
|
|
38
|
+
crate.bodyDef = { type: "dynamic", shapes: [new Box3d(0, 0, 0, 64, 64, 64)] };
|
|
39
|
+
// give the depth when adding it: left out, the container numbers it
|
|
40
|
+
app.world.addChild(crate, 0);
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Shapes are in the renderable's space, relative to its `pos` (and `depth`), which is where the body sits. The engine's 3D convention holds: Y grows downward, +Z goes into the screen.
|
|
44
|
+
|
|
45
|
+
### Loading Rapier
|
|
46
|
+
|
|
47
|
+
As on every melonJS adapter:
|
|
48
|
+
|
|
49
|
+
- `Rapier3dAdapter.load()` downloads and compiles Rapier, and resolves when it is ready. Every call returns the same promise; a failed load rejects, and the next call tries again.
|
|
50
|
+
- `Rapier3dAdapter.create(options)` waits for `load()`, then constructs the adapter.
|
|
51
|
+
- `Rapier3dAdapter.loaded` is `true` once `load()` has finished.
|
|
52
|
+
|
|
53
|
+
Rapier is imported with `import()`, so bundlers put it (about 4.3 MB, 1.6 MB compressed) in a chunk of its own, downloaded when `load()` is first called. There are two ways to wait for it.
|
|
54
|
+
|
|
55
|
+
#### 1. Before the game starts: `create()`
|
|
56
|
+
|
|
57
|
+
The shortest: await the adapter in the `Application` settings, as on every adapter.
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { Application, Camera3d, loader } from "melonjs";
|
|
61
|
+
import { Rapier3dAdapter } from "@melonjs/rapier3d-adapter";
|
|
62
|
+
|
|
63
|
+
const app = new Application(800, 600, {
|
|
64
|
+
parent: "screen",
|
|
65
|
+
cameraClass: Camera3d,
|
|
66
|
+
physic: await Rapier3dAdapter.create({ gravity: { x: 0, y: 980, z: 0 } }),
|
|
67
|
+
});
|
|
68
|
+
await app.init();
|
|
69
|
+
await loader.preload(assets);
|
|
70
|
+
// build the scene from here
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
The page stays blank while Rapier downloads and compiles: the loading screen only starts with `loader.preload`, after it. Right for a prototype, a test, or a game whose players have Rapier cached.
|
|
74
|
+
|
|
75
|
+
#### 2. Behind the loading screen: the preloader
|
|
76
|
+
|
|
77
|
+
Rapier is the largest download a game with it has, so load it with the game's other assets, where the loading screen counts it. Teach the loader an asset type for it with `loader.setParser`, list it in the preload, and switch the world to Rapier once the preload is done:
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
import { Application, Camera3d, loader } from "melonjs";
|
|
81
|
+
import { Rapier3dAdapter } from "@melonjs/rapier3d-adapter";
|
|
82
|
+
|
|
83
|
+
// once: registering the same type twice logs a warning
|
|
84
|
+
loader.setParser("rapier3d", (_asset, onload, onerror) => {
|
|
85
|
+
Rapier3dAdapter.load().then(() => onload(), onerror);
|
|
86
|
+
return 1; // one asset, for the loading screen's progress
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
// no `physic` here: the built-in physics runs until the switch below
|
|
90
|
+
const app = new Application(800, 600, { parent: "screen", cameraClass: Camera3d });
|
|
91
|
+
await app.init();
|
|
92
|
+
|
|
93
|
+
await loader.preload([
|
|
94
|
+
{ name: "rapier3d", type: "rapier3d", src: "" },
|
|
95
|
+
...assets,
|
|
96
|
+
]);
|
|
97
|
+
app.world.setAdapter(new Rapier3dAdapter({ gravity: { x: 0, y: 980, z: 0 } }));
|
|
98
|
+
// build the scene from here
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Rapier downloads in parallel with the models and textures, the loading screen shows it from the first frame, and a failed download fails the preload like any other asset. `world.setAdapter()` (melonJS 20.14 and later) rebuilds any body made before it from its `bodyDef`, so the order is safe either way; building the scene after it is simply cheaper. The [Slingshot](https://melonjs.github.io/melonJS/examples/#/slingshot) example loads this way.
|
|
102
|
+
|
|
103
|
+
#### Will this stay asynchronous?
|
|
104
|
+
|
|
105
|
+
The WebAssembly ESM integration proposal lets JavaScript import a compiled module without awaiting it (source phase imports, `import source mod from "./engine.wasm"`), supported in some engines already. It takes the `await` out of the code, not the download: a static import is fetched and compiled before the game's own code runs, where no loading screen can show it. Rapier's `-compat` build, which this adapter uses, embeds its WebAssembly and starts it asynchronously. Should a later build be ready at import, `load()` resolves at once, as it already does on the built-in, matter and planck adapters, and both ways above work unchanged.
|
|
106
|
+
|
|
107
|
+
### Options
|
|
108
|
+
|
|
109
|
+
All optional; this is the call with each at its default:
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
physic: await Rapier3dAdapter.create({
|
|
113
|
+
gravity: { x: 0, y: 320, z: 0 }, // pixels per second², ≈ 10 m/s² pulling down
|
|
114
|
+
pixelsPerMeter: 32, // a 32-pixel cube is one meter, and weighs 1 kg
|
|
115
|
+
subSteps: 1,
|
|
116
|
+
}),
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
#### `gravity`
|
|
120
|
+
|
|
121
|
+
In pixels per second², with an optional `z`. It is read at every step: `app.world.adapter.gravity.set(0, 0, 320)` pulls along Z from the next one (a body already asleep stays asleep until something wakes it).
|
|
122
|
+
|
|
123
|
+
#### `pixelsPerMeter`
|
|
124
|
+
|
|
125
|
+
Rapier is tuned for objects about a meter across, so the adapter works in meters and converts everything at the boundary (positions, velocities, gravity, forces, queries): every value you pass is in pixels. Raising it makes every body smaller in meters, so lighter, and the same force moves it further; motion under gravity alone looks the same in pixels. It must be a positive number.
|
|
126
|
+
|
|
127
|
+
#### `subSteps`
|
|
128
|
+
|
|
129
|
+
Rapier steps per engine frame, each of `dt / subSteps` seconds: more accurate fast contacts and tall stacks, at about that many times the physics cost. Values below 1 are clamped to 1.
|
|
130
|
+
|
|
131
|
+
## Shapes
|
|
132
|
+
|
|
133
|
+
| melonJS shape | Rapier collider | notes |
|
|
134
|
+
|---|---|---|
|
|
135
|
+
| `Box3d` | cuboid | exact |
|
|
136
|
+
| `Sphere` | ball | exact |
|
|
137
|
+
| `Capsule3d` | capsule | upright along Y: the shape for a character |
|
|
138
|
+
| `ConvexHull3d` | convex polyhedron | the hull of its points: a moving prop |
|
|
139
|
+
| `TriangleMesh3d` | triangle mesh | exact, hollow: terrain and level geometry, on a static or kinematic body |
|
|
140
|
+
| `Rect`, `Ellipse`, `Polygon`, `Line`, `Point` | refused | throws: a 2D shape has no depth |
|
|
141
|
+
|
|
142
|
+
Build them from a model as it is drawn, through its transform, scale and handedness:
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
level.bodyDef = { type: "static", shapes: [TriangleMesh3d.fromMesh(level)] };
|
|
146
|
+
rock.bodyDef = { type: "dynamic", shapes: [ConvexHull3d.fromMesh(rock)] };
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
A shape can carry `collisionType`, `collisionMask`, `isTrigger` (a sensor) and `isActive` (`false` builds no collider), which override the body's. A `ConvexHull3d` whose points all lie in one plane has no hull: it becomes their bounding box. A triangle mesh has no volume, so it gives a dynamic body no mass.
|
|
150
|
+
|
|
151
|
+
`adapter.getBodyShapes(renderable)` returns the shapes as given, before the body turns; `getBodyAABB` the XY footprint of the colliders as the body is turned now (exact for a box, a sphere and a capsule; a hull's or a mesh's bounding box, turned).
|
|
152
|
+
|
|
153
|
+
`adapter.updateShape(renderable, shapes)` replaces the colliders and keeps the body: its position, turn and velocities, its joints, everything set on it at run time, and the handle on `renderable.body`. The pairs touching it end and start again, and its mass becomes that of the new shapes. A shape the adapter cannot build throws before anything is changed.
|
|
154
|
+
|
|
155
|
+
## The 3D API
|
|
156
|
+
|
|
157
|
+
The portable calls take a `Vector3d`, and the 2D forms keep working, in the plane of the body:
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
const adapter = app.world.adapter as Rapier3dAdapter;
|
|
161
|
+
|
|
162
|
+
adapter.setVelocity(ball, new Vector3d(0, -200, 400)); // px/s on each axis
|
|
163
|
+
adapter.setVelocity(ball, new Vector2d(50, 0)); // sets x and y, keeps the z velocity
|
|
164
|
+
adapter.applyImpulse(ball, new Vector3d(0, 0, 64), hitPoint); // off-centre, it spins the body
|
|
165
|
+
adapter.applyForce(ship, new Vector3d(0, 0, 10)); // for this frame
|
|
166
|
+
adapter.applyTorque(top, new Vector3d(0, 5, 0)); // a number turns about Z
|
|
167
|
+
adapter.setPosition(crate, new Vector3d(0, 0, 200)); // a Vector2d keeps the depth
|
|
168
|
+
|
|
169
|
+
adapter.getVelocity3d(ball); // Vector3d, px/s
|
|
170
|
+
adapter.getRotation(crate); // Quaternion, from the pose it was made in
|
|
171
|
+
adapter.setRotation(crate, q); // turns the drawn model too, at once
|
|
172
|
+
adapter.getAngularVelocity3d(crate); // rad/s about each axis
|
|
173
|
+
adapter.setAngularVelocity(crate, new Vector3d(0, 2, 0)); // a number sets the spin about Z only
|
|
174
|
+
adapter.setAngle(crate, rad); // a turn about Z; getAngle() reads the turn about Z
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
`renderable.body` is the Rapier `RigidBody`, with the portable melonJS helpers added to it, as on the 2D Rapier adapter:
|
|
178
|
+
|
|
179
|
+
```ts
|
|
180
|
+
body.setVelocity(x, y, z?) // pixels per second; without z, the depth velocity is kept
|
|
181
|
+
body.getVelocity(out?) / body.getVelocity3d(out?)
|
|
182
|
+
body.applyForce(x, y, pointX?, pointY?) // for this frame, in the plane of the body
|
|
183
|
+
body.applyImpulse(x, y, z?) // an instant change of velocity: Δv = J / mass
|
|
184
|
+
body.setAngle(rad) / body.getAngle() // the turn about Z
|
|
185
|
+
body.setAngularVelocity(w) / body.getAngularVelocity() // radians per second, about Z
|
|
186
|
+
body.applyTorque(t) // for this frame, about Z
|
|
187
|
+
body.setStatic(isStatic?)
|
|
188
|
+
body.setSensor(isSensor?)
|
|
189
|
+
body.setGravityScale(scale)
|
|
190
|
+
body.setMass(kg) // scales every shape's density
|
|
191
|
+
body.setBounce(restitution)
|
|
192
|
+
body.collisionType / body.collisionMask // read the first shape's values, write every shape's
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
The adapter has the same operations as `adapter.X(renderable, ...)`, except `setMass` and `setBounce`, and also `setFrictionAir`, `setMaxVelocity({ x, y, z? })` / `getMaxVelocity`, `setCollisionType` and `setCollisionMask`. Type the body as `Rapier3dAdapter.Body` to reach Rapier's own methods (`enableCcd`, `linvel`, `sleep`, …), which work in meters.
|
|
196
|
+
|
|
197
|
+
**Units.** Velocities are in pixels per second and angular velocities in radians per second. `applyForce` accelerates a body by `force / mass` px/s², and `applyImpulse` changes its velocity by `impulse / mass` px/s; a 32-pixel cube at the default density weighs 1 kg at the default scale. A torque is in Rapier's own unit (N·m, not scaled by `pixelsPerMeter`), as on the 2D Rapier adapter. A force or torque lasts for the frame it is applied in, across every sub-step, so apply it every frame for a sustained push.
|
|
198
|
+
|
|
199
|
+
**How the turn is drawn.** The body's turn is applied on top of the `currentTransform` the renderable had when its body was made, so a model turned or scaled to its rest pose keeps it. A `Mesh` (and a `Sprite3d`) turns in its model's Y-up space, which the adapter accounts for; a `GLTFModel` and any other renderable turn in the engine's space. Moving the renderable with `pos` directly is undone at the next step; use `setPosition` and `setRotation`.
|
|
200
|
+
|
|
201
|
+
**Code for any adapter** can test `adapter.capabilities.bodies3d` before using the 3D readers, which 2D adapters leave out:
|
|
202
|
+
|
|
203
|
+
```ts
|
|
204
|
+
const v = adapter.getVelocity3d?.(ball) ?? adapter.getVelocity(ball);
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
## Collision events
|
|
208
|
+
|
|
209
|
+
The same hooks as on every adapter:
|
|
210
|
+
|
|
211
|
+
```ts
|
|
212
|
+
class Pet extends Mesh {
|
|
213
|
+
onCollisionStart(response, other) { /* the first touch */ }
|
|
214
|
+
onCollisionActive(response, other) { /* every frame while touching */ }
|
|
215
|
+
onCollisionEnd(response, other) { /* separated, or the other body was removed */ }
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
`response.normal` is `{ x, y, z }`, the unit direction this renderable must move to separate, and `response.depth` the overlap in pixels; both are zero for a sensor contact and in `onCollisionEnd`. `response.pair` is `{ collider1, collider2 }`, the two Rapier collider handles. The shape-level hooks (`onShapeCollisionStart`, …) name each pair of shapes, with the z of the normal in `normalZ`. A renderable with no `onCollisionActive` gets `onCollision` instead, once a frame.
|
|
220
|
+
|
|
221
|
+
A hook can remove a body, its own or the other one, or change its shapes with `updateShape()`. Every renderable that heard a contact start hears it end, after the start: the one whose body is taken out at once, the other when the hooks of that contact are done. A renderable whose body is gone hears nothing more.
|
|
222
|
+
|
|
223
|
+
`adapter.isGrounded(renderable)` is true while a contact pushes the body up (against Y), on a surface up to about 84° from level.
|
|
224
|
+
|
|
225
|
+
## Queries
|
|
226
|
+
|
|
227
|
+
```ts
|
|
228
|
+
adapter.raycast3d(from: Vector3d, to: Vector3d) → RaycastHit3d | null
|
|
229
|
+
adapter.querySphere(center: Vector3d, radius) / querySphere(sphere: Sphere) → Renderable[]
|
|
230
|
+
adapter.queryAABB(rect: Rect) → Renderable[]
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
- `raycast3d` returns the first collider along the segment, as `{ renderable, point, normal, fraction }`, against the exact shapes: the hit point in pixels, the unit surface normal there, and how far along the segment it is (0 to 1). A body the ray starts inside is skipped, so a body casting from its own centre does not hit itself. Sensors are hit like any other body.
|
|
234
|
+
- `querySphere` returns every renderable whose colliders overlap the sphere, exactly, once each.
|
|
235
|
+
- `queryAABB` returns what lies over a rectangle in XY, at any depth, once each: by each collider's box as the body is turned, the one `getBodyAABB` reports.
|
|
236
|
+
|
|
237
|
+
There is no 2D `raycast` (`capabilities.raycasts` is `false`): a 3D world is queried with `raycast3d`. Rapier indexes a body for these queries when its world steps, so a body is found from the frame after it is added, or moved with `setPosition`.
|
|
238
|
+
|
|
239
|
+
## Body definitions
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
this.bodyDef = {
|
|
243
|
+
type: "dynamic", // "static" | "dynamic" | "kinematic"
|
|
244
|
+
shapes: [ /* see above */ ],
|
|
245
|
+
collisionType?: number, // default PLAYER_OBJECT (0x0001)
|
|
246
|
+
collisionMask?: number, // default ALL_OBJECT
|
|
247
|
+
isSensor?: boolean,
|
|
248
|
+
density?: number, // kg/m³, default 1
|
|
249
|
+
friction?: number, // default 0.2
|
|
250
|
+
restitution?: number, // bounce, default 0
|
|
251
|
+
frictionAir?: number, // damping per second, of movement and rotation; { x, y } is averaged
|
|
252
|
+
gravityScale?: number, // default 1
|
|
253
|
+
fixedRotation?: boolean, // default false: the body turns
|
|
254
|
+
maxVelocity?: { x, y, z? }, // px/s per axis; z left out leaves depth uncapped
|
|
255
|
+
};
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
A `kinematic` body moves by its velocity and ignores gravity. Collision types and masks filter on all 32 bits, as on the 2D Rapier adapter.
|
|
259
|
+
|
|
260
|
+
## Joints
|
|
261
|
+
|
|
262
|
+
`app.world.addJoint()` makes the four portable joints, in 3D:
|
|
263
|
+
|
|
264
|
+
| `type` | Rapier joint | settings |
|
|
265
|
+
|---|---|---|
|
|
266
|
+
| `"hinge"` | revolute | `axis`, default Z (as a 2D hinge turns); `limits` in radians |
|
|
267
|
+
| `"rope"` | rope | `maxLength` in pixels, default the distance when made |
|
|
268
|
+
| `"weld"` | fixed | welded as they stand |
|
|
269
|
+
| `"slider"` | prismatic | `axis`, default X; `limits` in pixels along it |
|
|
270
|
+
|
|
271
|
+
Anchors take an optional `z`, in each renderable's own space, relative to its `pos`; the axis too, in `a`'s own space.
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
app.world.addJoint({
|
|
275
|
+
type: "hinge",
|
|
276
|
+
a: frame,
|
|
277
|
+
b: door,
|
|
278
|
+
anchorB: { x: -40, y: 0, z: 0 },
|
|
279
|
+
axis: { x: 0, y: 1, z: 0 }, // a door turns about the vertical
|
|
280
|
+
limits: { min: 0, max: Math.PI / 2 },
|
|
281
|
+
});
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
- **Pixels in, meters inside.** Anchors, lengths and slider limits are in pixels; the adapter converts them with `pixelsPerMeter`.
|
|
285
|
+
- **Default anchors hold the bodies where they are.** `anchorB` defaults to `b`'s position, and `anchorA` to the point of `a` under it; a rope joins the two positions.
|
|
286
|
+
- **Bodies are joined as they stand**, however each is turned: a weld and a slider keep the turn between them, and a hinge leaves them only the turn about its axis. A hinge's `limits` are `b`'s angle about the axis minus `a`'s, so make the joint with the two turned alike (or apart about the axis only) when it has limits.
|
|
287
|
+
- **Limits are soft.** A body moving fast can pass a hinge or slider limit by a few pixels for a frame before Rapier pushes it back.
|
|
288
|
+
- **The world keeps the joint.** It is removed when either body leaves the world, and built again by `world.setAdapter()`. `updateShape()` keeps the body, so it keeps its joints too, `joint.native` included.
|
|
289
|
+
- **Motors and the rest of Rapier's joint settings** are on the Rapier joint itself, `joint.native` (a `RevoluteImpulseJoint`, …). That code is Rapier-only, and the setting is lost when `setAdapter()` builds the joint again.
|
|
290
|
+
|
|
291
|
+
## Rapier features
|
|
292
|
+
|
|
293
|
+
`adapter.rapier` is the Rapier module and `adapter.world` the Rapier world, for what the portable interface does not cover. Code that uses them is Rapier-only; test `app.world.physic === "rapier3d"` to branch.
|
|
294
|
+
|
|
295
|
+
```ts
|
|
296
|
+
const { rapier, world } = app.world.adapter as Rapier3dAdapter;
|
|
297
|
+
|
|
298
|
+
// continuous collision detection, for a fast body that must not pass through a thin one
|
|
299
|
+
(projectile.body as Rapier3dAdapter.Body).enableCcd(true);
|
|
300
|
+
|
|
301
|
+
// a ball-and-socket joint, for a chain or a ragdoll (in meters, body-local)
|
|
302
|
+
world.createImpulseJoint(
|
|
303
|
+
rapier.JointData.spherical({ x: 0, y: 0.5, z: 0 }, { x: 0, y: -0.5, z: 0 }),
|
|
304
|
+
upper.body as Rapier3dAdapter.Body,
|
|
305
|
+
lower.body as Rapier3dAdapter.Body,
|
|
306
|
+
true,
|
|
307
|
+
);
|
|
308
|
+
|
|
309
|
+
// Rapier's kinematic character controller, with a 1 cm skin
|
|
310
|
+
const controller = world.createCharacterController(0.01);
|
|
311
|
+
controller.computeColliderMovement(
|
|
312
|
+
(hero.body as Rapier3dAdapter.Body).collider(0),
|
|
313
|
+
{ x: 0.1, y: 0.2, z: 0 },
|
|
314
|
+
);
|
|
315
|
+
const move = controller.computedMovement(); // meters: apply it to a kinematic body
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
Bodies sleep when they come to rest and wake on contact, or when the adapter moves, turns or pushes them; `body.sleep()` and `body.wakeUp()` force it. `adapter.isSleeping(renderable)` says whether a body is asleep, the way to tell a shot or a stack has settled; it is `false` for a fixed or kinematic body. A sleeping body's renderable is not written to, nor a static one's.
|
|
319
|
+
|
|
320
|
+
Rapier's objects live in WebAssembly memory, which the garbage collector does not reclaim. The adapter frees them in `destroy()`, which `world.setAdapter()` calls on the adapter it replaces; from then on its queries find nothing, and a body handle kept from it must not be used. Free a joint or a character controller you created yourself through `adapter.world` with `world.removeImpulseJoint()` / `world.removeCharacterController()`; the joints `app.world.addJoint()` made are freed for you.
|
|
321
|
+
|
|
322
|
+
## Coming from the 2D Rapier adapter
|
|
323
|
+
|
|
324
|
+
The options, the loading (`load()` / `create()` / `loaded`), the `bodyDef` fields, the hooks, the body helpers and the units are the same. What differs:
|
|
325
|
+
|
|
326
|
+
- **Shapes have depth.** `Box3d`, `Sphere`, `Capsule3d`, `ConvexHull3d` and `TriangleMesh3d`; a `Rect` or an `Ellipse` is refused with the shape to use instead.
|
|
327
|
+
- **The body sits at the renderable's `pos` and `depth`**, and shapes are relative to it, whatever the anchor point. The 2D adapter puts the body at the centre of its first shape.
|
|
328
|
+
- **Three axes.** `gravity` is a `Vector3d`; a call given a `Vector3d` acts on all three axes, and one given a `Vector2d`, a scalar angle or a scalar spin acts in the plane of the body, about Z. `getRotation` / `setRotation`, `getVelocity3d` and `getAngularVelocity3d` read and write the rest.
|
|
329
|
+
- **`raycast3d` and `querySphere`** in place of `raycast`.
|
|
330
|
+
- **`getBodyShapes` returns the shapes as given**, where the 2D adapter returns them posed; the pose is `pos`, `depth` and `getRotation`.
|
|
331
|
+
- **`updateShape()` keeps the body** (see [Shapes](#shapes)), where the 2D adapter builds a new one.
|
|
332
|
+
- **`physicLabel` is `"rapier3d"`**, and `capabilities.bodies3d` is `true`.
|
|
333
|
+
- **Hinges and sliders take an `axis`** with a `z`, and anchors a `z`.
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
## Examples
|
|
337
|
+
|
|
338
|
+
The [Slingshot](https://melonjs.github.io/melonJS/examples/#/slingshot) example launches animals at towers of blocks that topple and tumble.
|
|
339
|
+
|
|
340
|
+
## License
|
|
341
|
+
|
|
342
|
+
MIT. Rapier itself is distributed under the Apache 2.0 license.
|