I am currently prototyping a web app which is using the compass heading in a browser. This is a value ranging from 0 ~ 360.
Whenever i do a full rotation the value jumps from 360 back to 0. I cannot figure out how i can get it to increase from 360 to for example 720 on the second rotation.
What piece of math magic am i missing?
Thanks!
This is my code
if ('ondeviceorientationabsolute' in window) {
window.addEventListener('deviceorientationabsolute', handleOrientationAbsolute);
} else if ('ondeviceorientation' in window) {
window.addEventListener('deviceorientation', handleOrientation);
}
function handleOrientationAbsolute(e) {
alpha = Math.round(360 - e.alpha);
update();
}
function handleOrientation(e) {
alpha = Math.round(e.webkitCompassHeading);
update();
}
function update() {
headingEl.innerHTML = alpha; //This value should be able to return higher than 360
}
I'll steal a technique from Mario Kart.
Have, around your circle, certain thresholds. You need to divide the circle into at least 3 groups. (Let's say you're using the 120°
points.) Store which group you're in (e.g. 0
, 1
or 2
), and every so often check which group you are in. If you change between 0
and 1
, or 1
and 2
, just store that. But if you change between 2
and 0
, increment or decrement a counter.
This will allow you to return values greater than 360°.