Calculate rotation of a vertically held android phone in javascript

46 views Asked by At

I am attempting to calculate a full 360 degree rotation from a captured starting angle while the phone is being held vertically in either portrait or landscape.

I can easily get a starting angle by listening to the deviceorientation event and capturing the beta and gamma values to calculate a "start" angle with a button click => let startAngle = Match.atan2(beta,gamma)/(Math.PI /180)

I then calc the to delta with Math.abs(currentAngle - startAngle). The problem is when I cross 180 or -180 values I don't know the direction I came from. I also cross that boundary twice getting to 360. I could also go either clockwise or counter clockwise (pitch up or down). I would like to calculate a full 360 and reset to 0 at the start point. Not sure if using Trigonometry is the way to go here. Thanks in advance for any help or suedo logic that will help.

var startAngle = 150; //Just a test start value. Usually comes from setPoint button click
var currAngle = 0;
var calcRotation = 0;

window.addEventListener('deviceorientation', this.orientation, false);

orientation = event => {
    var alpha = event.alpha;
    var beta = event.beta;
    var gamma = event.gamma;

   //If device is vertical 
    if(this.isVertical) 
   { 
       this.currAngle = Math.round(Math.atan2(beta, gamma) / (Math.PI/180));

      //Calculate the difference 
      this.calcRotation = this.currAngle - this.startAngle;
0

There are 0 answers