babylon accelerometer
by Evgeniy Lukovsky
HTML
<!DOCTYPE html>
<html>
<head>
<title>Accelerometer Stabilized 3D Scene</title>
<script src="https://cdn.babylonjs.com/babylon.js"></script>
<style>
body { margin: 0; overflow: hidden; }
canvas { width: 100%; height: 100%; }
</style>
</head>
<body>
<canvas id="renderCanvas"></canvas>
</body>
</html>
JavaScript
const canvas = document.getElementById("renderCanvas")
const engine = new BABYLON.Engine(canvas, true)
function createScene() {
const scene = new BABYLON.Scene(engine)
const camera = new BABYLON.FreeCamera(
"camera1",
new BABYLON.Vector3(0, 5, -10),
scene,
)
camera.setTarget(BABYLON.Vector3.Zero())
camera.attachControl(canvas, true)
const light = new BABYLON.HemisphericLight(
"light1",
new BABYLON.Vector3(0, 1, 0),
scene,
)
// Create some 3D objects
const sphere = BABYLON.MeshBuilder.CreateSphere(
"sphere",
{ diameter: 2 },
scene,
)
const box = BABYLON.MeshBuilder.CreateBox("box", { size: 2 }, scene)
const cylinder = BABYLON.MeshBuilder.CreateCylinder(
"cylinder",
{ height: 3, diameter: 1 },
scene,
)
// Position the objects
sphere.position.x = -3
box.position.x = 3
// Initialize accelerometer variables
let initialAlpha = 0
let initialBeta = 0
// Request access to the device's accelerometer
if (typeof DeviceMotionEvent.requestPermission === "function") {
DeviceMotionEvent.requestPermission()
.then((permissionState) => {
if (permissionState === "granted") {
window.addEventListener("devicemotion", handleMotion)
}
})
.catch(console.error)
} else {
// Handle devices that don't support the permission request API
window.addEventListener("devicemotion", handleMotion)
}
function handleMotion(event) {
if (!initialAlpha) {
initialAlpha = event.alpha
initialBeta = event.beta
}
// Calculate the change in orientation
const deltaAlpha = event.alpha - initialAlpha
const deltaBeta = event.beta - initialBeta
// Rotate the camera to compensate for device movement
camera.rotation.y -= (deltaAlpha * Math.PI) / 180
camera.rotation.x -= (deltaBeta * Math.PI) / 180
}
return scene
}
const scene = createScene()
engine.runRenderLoop(function () {
...