- Documentation
- Bibliothèque d'expériences
- Vélo posé au sol
Vélo posé au sol Suivi du monde
Le vélo comme objet 3D : touchez le sol pour le poser en taille réelle, puis appuyez sur Éclater.
Code
Le code de cette expérience, séparé en fichiers comme vous les garderiez : HTML, CSS et JavaScript. La page en ligne les garde dans un seul fichier ; copiez chaque partie dans son fichier et la page marche pareil.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>Bicycle on the floor (A-Frame)</title>
<!-- The bicycle as a 3D object, written with A-Frame tags: tap the floor to place it at real size, then press Explode. WebXR AR: Chrome on an Android phone with ARCore. -->
<script src="/node_modules/aframe/dist/aframe-v1.8.0.min.js"></script>
<script src="/packages/sdk-aframe/dist/index.umd.cjs"></script>
<script src="/packages/sdk-tracker-world/dist/index.umd.cjs"></script>
<script src="page.js"></script>
<link rel="stylesheet" href="page.css" />
</head>
<body>
<!--
The whole experience is this scene. tracker: world puts content on the real floor, in meters.
A button "Start AR" appears (WebXR starts from a tap). Move the phone slowly until the ring shows, then tap.
-->
<a-scene
tempusxr="tracker: world; anchors: spot; debug: false"
renderer="alpha: true"
gltf-model="dracoDecoderPath: /node_modules/three/examples/jsm/libs/draco/"
vr-mode-ui="enabled: false"
>
<a-camera look-controls="enabled: false" wasd-controls="enabled: false"></a-camera>
<a-light type="ambient" intensity="1.2"></a-light>
<a-light type="directional" position="0.5 1 1" intensity="1.5"></a-light>
<a-entity tempusxr-anchor="index: 0">
<a-entity
id="bike"
gltf-model="/examples/bike/bike.glb"
bike-explode="size: 1.7"
></a-entity>
</a-entity>
<a-entity tempusxr-reticle>
<a-ring
rotation="-90 0 0"
radius-inner="0.06"
radius-outer="0.075"
color="#ffffff"
></a-ring>
</a-entity>
<!-- Inside the scene: this is what stays on screen over the camera in an AR session. -->
<button id="explode" type="button">Explode</button>
</a-scene>
</body>
</html>
body {
margin: 0;
}
#explode {
display: none;
position: absolute;
z-index: 10;
left: 50%;
bottom: 6%;
transform: translateX(-50%);
padding: 14px 28px;
border: 0;
border-radius: 999px;
background: #fff;
color: #111;
font:
600 16px system-ui,
sans-serif;
}
// What the tags cannot say: fit the model to 1.7 m on the floor, and play its exploded view.
AFRAME.registerComponent('bike-explode', {
schema: { size: { default: 1.7 }, clip: { default: 'Explosion View' } },
init() {
this.exploded = false;
this.el.addEventListener('model-loaded', () => {
const THREE = AFRAME.THREE;
const root = this.el.getObject3D('mesh');
root.updateMatrixWorld(true);
const box = new THREE.Box3().setFromObject(root);
const dims = box.getSize(new THREE.Vector3());
const scale = this.data.size / Math.max(dims.x, dims.y, dims.z);
const centre = box.getCenter(new THREE.Vector3());
root.position.set(-centre.x * scale, -box.min.y * scale, -centre.z * scale);
root.scale.setScalar(scale);
this.mixer = new THREE.AnimationMixer(root);
const clip = THREE.AnimationClip.findByName(root.animations, this.data.clip);
this.action = this.mixer.clipAction(clip);
this.action.setLoop(THREE.LoopOnce, 1);
this.action.clampWhenFinished = true;
});
},
// Forward takes the bicycle apart, backward puts it together.
toggle() {
if (!this.action) return;
this.exploded = !this.exploded;
this.action.paused = false;
this.action.timeScale = this.exploded ? 1 : -1;
this.action.play();
},
tick(time, delta) {
this.mixer?.update(delta / 1000);
},
});
import { addTestToggle } from '/examples/test-mode.js';
import { launchIfNoAr } from '/examples/launch-ar.js';
void launchIfNoAr();
addTestToggle(document.body, { floating: true });
const scene = document.querySelector('a-scene');
const button = document.getElementById('explode');
scene.addEventListener('tempusxr-ready', () => (button.style.display = 'block'));
button.addEventListener('click', () =>
document.getElementById('bike').components['bike-explode'].toggle(),
);
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>Bicycle on the floor (Three.js)</title>
<!-- The bicycle as a 3D object, written in Three.js: tap the floor to place it at real size, then press Explode. WebXR AR: Chrome on an Android phone with ARCore. -->
<script type="importmap">
{
"imports": {
"three": "/node_modules/three/build/three.module.js",
"three/addons/": "/node_modules/three/examples/jsm/",
"@tempusxr/sdk-core": "/packages/sdk-core/dist/index.js",
"@tempusxr/sdk-three": "/packages/sdk-three/dist/index.js",
"@tempusxr/sdk-tracker-world": "/packages/sdk-tracker-world/dist/index.js"
}
}
</script>
<link rel="stylesheet" href="page.css" />
</head>
<body>
<div id="ar">
<!-- Inside the container: this is what stays on screen over the camera in an AR session. -->
<button id="explode" class="big" type="button">Explode</button>
</div>
<button id="start" class="big" type="button">Start AR</button>
<script type="module" src="page.js"></script>
</body>
</html>
html,
body {
margin: 0;
height: 100%;
background: #111;
font:
14px/1.4 system-ui,
sans-serif;
color: #fff;
}
.big {
position: fixed;
z-index: 6;
left: 50%;
bottom: 12%;
transform: translateX(-50%);
padding: 14px 28px;
border: 0;
border-radius: 999px;
background: #fff;
color: #111;
font:
600 16px system-ui,
sans-serif;
}
#explode {
display: none;
bottom: 6%;
pointer-events: auto;
}
import * as THREE from 'three';
import { create } from '@tempusxr/sdk-three';
import { WebXRProvider } from '@tempusxr/sdk-core';
import { addTestToggle } from '/examples/test-mode.js';
import { launchIfNoAr } from '/examples/launch-ar.js';
void launchIfNoAr();
import '@tempusxr/sdk-tracker-world';
const container = document.getElementById('ar');
const ar = create({
container,
camera: new WebXRProvider({ domOverlay: container }),
});
window.__ar = ar;
addTestToggle(document.body, { floating: true });
// The floor: a tap puts the anchor where the ring is.
const tracker = await ar.use('world', {
anchors: [{ id: 'spot', placement: 'tap', surface: 'floor' }],
});
const lights = new THREE.Group();
lights.add(new THREE.AmbientLight(0xffffff, 1.2));
const sun = new THREE.DirectionalLight(0xffffff, 1.5);
sun.position.set(0.5, 1, 1);
lights.add(sun);
ar.scene.add(lights);
const ring = new THREE.Mesh(
new THREE.RingGeometry(0.06, 0.075, 48).rotateX(-Math.PI / 2),
new THREE.MeshBasicMaterial({ color: 0xffffff, side: THREE.DoubleSide }),
);
ar.attach(tracker.reticle, ring);
/** Scales `root` so its longest side is `size` meters and puts its feet on y = 0, centered. */
function fit(root, size) {
root.updateMatrixWorld(true);
const box = new THREE.Box3().setFromObject(root);
const dims = box.getSize(new THREE.Vector3());
const scale = size / Math.max(dims.x, dims.y, dims.z);
const centre = box.getCenter(new THREE.Vector3());
root.position.set(-centre.x * scale, -box.min.y * scale, -centre.z * scale);
root.scale.setScalar(scale);
}
// The model loads while the person reads the page: the Start button does not wait for it.
let explode = null;
void (async () => {
const [{ GLTFLoader }, { DRACOLoader }] = await Promise.all([
import('three/addons/loaders/GLTFLoader.js'),
import('three/addons/loaders/DRACOLoader.js'),
]);
const draco = new DRACOLoader().setDecoderPath(
'/node_modules/three/examples/jsm/libs/draco/',
);
const gltf = await new GLTFLoader()
.setDRACOLoader(draco)
.loadAsync('/examples/bike/bike.glb');
fit(gltf.scene, 1.7);
const holder = new THREE.Group();
holder.add(gltf.scene);
ar.attach(tracker.anchors[0], holder);
// The exploded view is an animation of the model: play it forward, or backward to put it together.
const mixer = new THREE.AnimationMixer(gltf.scene);
const clip = THREE.AnimationClip.findByName(gltf.animations, 'Explosion View');
const action = mixer.clipAction(clip);
action.setLoop(THREE.LoopOnce, 1);
action.clampWhenFinished = true;
const clock = new THREE.Clock();
ar.afterRender(() => mixer.update(clock.getDelta()));
let exploded = false;
explode = () => {
exploded = !exploded;
action.paused = false;
action.timeScale = exploded ? 1 : -1;
action.play();
};
})().catch((error) => console.error('The bicycle could not be loaded:', error));
document.getElementById('explode').addEventListener('click', () => explode?.());
// WebXR starts from a tap. Move the phone slowly until the ring shows on the floor, then tap.
document.getElementById('start').addEventListener('click', async (event) => {
event.currentTarget.remove();
await ar.start();
document.getElementById('explode').style.display = 'block';
});
{
"version": 1,
"id": "bike-object",
"name": "Bike as a 3D object on the floor",
"tracker": {
"kind": "world",
"anchors": [{ "id": "spot", "placement": "tap", "surface": "floor" }]
},
"assets": [{ "id": "bike", "type": "model", "src": "bike.glb", "compression": ["draco"] }],
"nodes": [
{
"id": "bike-node",
"asset": "bike",
"anchor": "spot",
"size": 1.7,
"animation": { "clip": "Explosion View", "autoplay": false, "loop": false }
}
],
"controls": [{ "id": "explode", "type": "button", "label": "Explode" }],
"behaviors": [{ "on": "press", "control": "explode", "do": "toggle", "node": "bike-node" }]
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>Tempusxr scene</title>
<!-- A scene file, opened the way the Viewer opens it. Open ?scene=your.json to try another one. -->
<script type="importmap">
{
"imports": {
"three": "/node_modules/three/build/three.module.js",
"three/addons/": "/node_modules/three/examples/jsm/",
"@tempusxr/scene": "/packages/scene/dist/index.js",
"@tempusxr/sdk-core": "/packages/sdk-core/dist/index.js",
"@tempusxr/sdk-three": "/packages/sdk-three/dist/index.js",
"@tempusxr/sdk-tracker-image": "/packages/sdk-tracker-image/dist/index.js",
"@tempusxr/sdk-tracker-world": "/packages/sdk-tracker-world/dist/index.js",
"@tempusxr/sdk-capture": "/packages/sdk-capture/dist/index.js",
"@tempusxr/ui": "/packages/ui/dist/index.js"
}
}
</script>
<link rel="stylesheet" href="page.css" />
</head>
<body>
<div id="ar"></div>
<div id="gate">
<div id="status">Loading...</div>
<button id="start" type="button" disabled>Start</button>
<div id="qr" hidden><span>Scan to open on your phone</span></div>
<div id="error"></div>
</div>
<script type="module" src="page.js"></script>
</body>
</html>
html,
body {
margin: 0;
height: 100%;
background: #111;
color: #fff;
font:
16px/1.5 system-ui,
sans-serif;
}
#gate {
position: fixed;
inset: 0;
z-index: 20;
display: grid;
place-content: center;
gap: 14px;
padding: 24px;
text-align: center;
background: #111;
}
#gate[hidden] {
display: none;
}
#start {
padding: 14px 32px;
border: 0;
border-radius: 999px;
background: #fecb02;
color: #1b1b1b;
font: inherit;
font-weight: 700;
}
#start:disabled {
opacity: 0.4;
}
#qr {
display: grid;
justify-items: center;
gap: 6px;
color: #a49cb1;
font-size: 14px;
}
#qr[hidden] {
display: none;
}
#qr svg {
width: 168px;
height: 168px;
border-radius: 10px;
}
#error {
color: #ff7b6b;
white-space: pre-wrap;
}
import { loadScene } from '@tempusxr/sdk-three';
import '@tempusxr/sdk-tracker-image';
import '@tempusxr/sdk-tracker-world';
import { qrSvg } from '@tempusxr/ui';
import { addTestToggle } from '/examples/test-mode.js';
import { launchOnIphone } from '/examples/launch-ar.js';
addTestToggle(document.getElementById('gate'));
const status = document.getElementById('status');
const start = document.getElementById('start');
const sceneUrl = new URLSearchParams(location.search).get('scene') || 'scene.json';
const events = (window.__events = []);
// On a computer, show the QR code of this page, so a phone can scan it from the screen.
if (matchMedia('(pointer: fine)').matches) {
const box = document.getElementById('qr');
box.insertAdjacentHTML('afterbegin', qrSvg(location.href, { ecc: 'Q' }));
box.hidden = false;
}
try {
const experience = await loadScene(sceneUrl, {
container: '#ar',
onProgress: ({ loaded, total }) => (status.textContent = `Loading ${loaded} / ${total}`),
onEvent: (event) => events.push(event),
// Models with KTX2 textures need the Basis transcoder files.
decoders: {
basisPath: '/node_modules/three/examples/jsm/libs/basis/',
dracoPath: '/node_modules/three/examples/jsm/libs/draco/',
},
// ?analytics sends opened, found, tap and time events to the dev server, which prints them.
...(new URLSearchParams(location.search).has('analytics')
? { analytics: { endpoint: '/__analytics' } }
: {}),
});
window.__experience = experience;
// ?capture adds the photo and video shutter. Videos hold the sound of the scene and of the room
// (the phone asks for the microphone the first time).
if (new URLSearchParams(location.search).has('capture')) {
const { enableCapture } = await import('@tempusxr/sdk-capture');
window.__capture = enableCapture(experience, { microphone: true });
}
status.textContent = experience.scene.meta?.title ?? 'Ready';
start.disabled = false;
// The tap is what lets the phone play sound and video later.
start.addEventListener('click', async () => {
document.getElementById('gate').hidden = true;
await experience.start();
});
} catch (error) {
// A world scene on an iPhone: Safari has no WebXR, so Variant Launch opens it in an App Clip.
if (error.code === 'unsupported' && launchOnIphone()) status.textContent = 'Opening AR...';
else status.textContent = 'This experience could not be opened.';
const lines = [`${error.code ?? 'error'}: ${error.message}`];
for (const issue of error.issues ?? []) lines.push(`${issue.code} ${issue.path}`);
document.getElementById('error').textContent = lines.join('\n');
window.__loadError = { code: error.code, file: error.file, issues: error.issues };
}