Skip to content

Instantly share code, notes, and snippets.

@joellord
Last active February 17, 2021 12:12
Show Gist options
  • Save joellord/a82322b6f5e2dd3f43794a2c0e7eb42f to your computer and use it in GitHub Desktop.
Save joellord/a82322b6f5e2dd3f43794a2c0e7eb42f to your computer and use it in GitHub Desktop.
Accelerometer samples
<html>
<body>
<div class="row">
<div class="col-12">
<h4>Device Orientation Demo</h4>
</div>
</div>
<div class="row">
<div class="col-12 center">
<div id="room" style="text-align: center; width: 95%; height: 300px; border: solid 3px black; border-radius: 25px;">
<div id="ball" style="position: relative; height: 50px; width: 50px; border-radius: 100%; background-color: blue;">&nbsp;</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
const MAX_SPEED = 20; //px/cycle
const FRAME_RATE = 30;
const REDRAW_MS = Math.floor(1000/FRAME_RATE);
const BALL_SIZE = 50;
const ROOM_HEIGHT = document.querySelector("#room").clientHeight;
const ROOM_WIDTH = document.querySelector("#room").clientWidth;
let ballTop = 0;
let ballLeft = 0;
let xSpeed = 0;
let ySpeed = 0;
const redraw = () => {
ballTop = ballTop + xSpeed;
ballLeft = ballLeft + ySpeed;
if (ballTop < 0) ballTop = 0;
if (ballTop > ROOM_HEIGHT - BALL_SIZE) ballTop = ROOM_HEIGHT - BALL_SIZE;
if (ballLeft < 0) ballLeft = 0;
if (ballLeft > ROOM_WIDTH - BALL_SIZE) ballLeft = ROOM_WIDTH - BALL_SIZE;
document.querySelector("#ball").style.top = `${ballTop}px`;
document.querySelector("#ball").style.left = `${ballLeft}px`;
console.log(`(${ballLeft}, ${ballTop})`);
}
window.ondeviceorientation = (event) => {
let x = event.beta;
let y = event.gamma;
if (x > 90) x = 90;
if (x < -90) x = -90;
if (y > 90) y = 90;
if (y < -90) y = -90;
xSpeed = MAX_SPEED * x/90;
ySpeed = MAX_SPEED * y/90;
}
setInterval(redraw, REDRAW_MS);
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment