DOCS

How to restrict the camera to an entity’s bounding box?

In order to set boundaries to the user navigation (for instance, staying inside a room), you can restrict the camera’s position to a bounding box.

The idea is:

  • get the Bounding Box (ie: AABB) of the bounding entity (eg: the scene_ref to the room).
  • on each frame, check if the camera is within the bounding box
  • if the camera is outside, travel towards the center of the bounding box until the camera is within the bounds.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
export const boundCameraToEntity = async (entityId: string) => {
const entity = (await SDK3DVerse.engineAPI.findEntitiesByEUID(entityId))[0];
if (!entity) {
console.error("Entity not found");
return;
}
const viewport = SDK3DVerse.engineAPI.cameraAPI.getViewports()[0];
const local_aabb = entity.getComponent("local_aabb");
const { min, max, center } = SDK3DVerse.utils.computeAABB(local_aabb, entity.getGlobalMatrix());
let isTraveling = false;
SDK3DVerse.notifier.on("onFramePreRender", async () => {
const globalTransform = viewport.getTransform();
const position = globalTransform.position;
let isOutsideAABB = false;
for (let i = 0; i < 3; i++) {
if (position[i] < min[i] || position[i] > max[i]) {
isOutsideAABB = true;
}
}
if (isOutsideAABB && !isTraveling) {
isTraveling = true;
SDK3DVerse.disableInputs();
viewport.travel(center, globalTransform.orientation, 10);
} else if (!isOutsideAABB && isTraveling) {
viewport.stopTravel();
SDK3DVerse.enableInputs();
isTraveling = false;
}
});
};
Previous
How to achieve a glass-like effect on a window pane?