Skip to content

Instantly share code, notes, and snippets.

@rozek
Created January 14, 2020 19:53
Show Gist options
  • Save rozek/b0fc2539ae9352b9e766c1eee8d73e87 to your computer and use it in GitHub Desktop.
Save rozek/b0fc2539ae9352b9e766c1eee8d73e87 to your computer and use it in GitHub Desktop.
Bangle.js: associates a point on the screen with the current device tilt
//------------------------------------------------------------------------------
//-- TiltWatcher --
//------------------------------------------------------------------------------
(function () {
let _Sensitivity = 1; // factor to amplify or damp acceleration
const TakerList = [];
/**** setWatchFor ****/
function setWatchFor (Taker) {
if ((Taker == null) || (typeof Taker !== 'object')) {
throw new TypeError('"Taker" should be an object');
}
let TakerIndex = TakerList.indexOf(Taker);
if (TakerIndex < 0) {
TakerList.push(Taker);
if (TakerList.length === 1) {
Bangle.on('accel',handleTilt);
}
}
return this;
}
/**** clearWatchFor ****/
function clearWatchFor (Taker) {
if ((Taker == null) || (typeof Taker !== 'object')) {
throw new TypeError('"Taker" should be an object');
}
let TakerIndex = TakerList.indexOf(Taker);
if (TakerIndex >= 0) {
TakerList.splice(TakerIndex,1)
if (TakerList.length === 0) {
Bangle.removeListener('accel',handleTilt);
}
}
return this;
}
/**** clearWatches ****/
function clearWatches () {
if (TakerList.length > 0) {
TakerList.splice(0,TakerList.length);
Bangle.removeListener('accel',handleTilt);
}
return this;
}
/**** informTakers ****/
function informTakers (x,y) {
for (let i = 0, l = TakerList.length; i < l; i++) {
let Method = TakerList[i]['onTilt'];
if (typeof Method === 'function') {
try {
Method.call(TakerList[i],x,y);
} catch (Signal) { /* nop */ }
}
}
}
/**** TiltWatcher object ****/
TiltWatcher = {
get Sensitivity () { return _Sensitivity },
set Sensitivity (Value) {
switch (true) {
case (Value == null):
_Sensitivity = 1;
break;
case (typeof Value === 'number') || (Value instanceof Number):
_Sensitivity = (Value <= 0 ? 1 : Value);
break;
default:
throw new TypeError('number expected');
}
},
setWatchFor:setWatchFor, clearWatchFor:clearWatchFor,
clearWatches:clearWatches
};
/**** let TiltWatcher actually watch the device's tilt ****/
function handleTilt (ValueSet) {
let Width = g.getWidth();
let Height = g.getHeight();
let x = E.clip(Math.round((1 + _Sensitivity*ValueSet.x)*Width/2), 0,Width);
let y = E.clip(Math.round((1 + _Sensitivity*ValueSet.y)*Height/2), 0,Height);
informTakers(x,y);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment