iOS罗盘翻转计算

时间:2016-06-01 16:04:45

标签: ios

我认为这是一个简单的问题。我的主题是在胸前佩戴iphone。他们需要走几英尺然后转180度,我正在使用磁罗盘标题,但是当指南针“滚动”,即从359到1或从1到359时,它会变得混乱。我已经尝试过放置开关和东西(见下面的代码),但它仍然不起作用。我相信其他人之前已经面对过这个问题了。任何想法,技巧,技巧? 感谢。

 // Turn completion logic here
 if (self.firstTimeInTurnCheckingOne) {
      self.firstTimeInTurnCheckingOne = FALSE;
      self.startingCompass = newHeading.magneticHeading;
      self.lastCompass = newHeading.magneticHeading;
      self.currentCompass = newHeading.magneticHeading;
      NSLog(@"First time in: %f", self.startingCompass);
 }

 NSLog(@"Before roll check - start: %f Last: %f current: %f", self.startingCompass, self.lastCompass, self.currentCompass);

 // check to see if compass rolled over
 if (!self.compassRolled) {
      if ((fabs (self.lastCompass - self.currentCompass) > 340)) {
      NSLog(@"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@it rolled %f  %f", self.lastCompass, self.currentCompass);
      self.compassRolled = TRUE;
      if (self.currentCompass > self.lastCompass) {
           self.currentCompass = self.currentCompass - 360;
           self.startingCompass = self.startingCompass - 360;
           self.rolledDown = TRUE;
           NSLog(@"Rolled Down");
      } else {
           self.currentCompass = self.currentCompass + 360;
           self.startingCompass = self.startingCompass + 360;
           self.rolledUp = TRUE;
           NSLog(@"Rolled Up");
           }
      }
 }

 self.lastCompass = self.currentCompass;
 NSLog(@"After roll check - start: %f Last: %f current: %f", self.startingCompass, self.lastCompass, self.currentCompass);
 NSLog(@"Difference: %f", fabs(self.startingCompass - self.currentCompass));


 if (!self.turnOneComplete) {

      if ((fabs (self.startingCompass - self.currentCompass)) > 120) {
           NSLog(@"Turn Calc: %f", (fabs (self.startingCompass - self.currentCompass)));
           NSLog(@"Turn One Complete");
           self.turnOneLabel.hidden = NO;
           self.turnOneComplete = TRUE;
           self.compassRolled = FALSE;

           self.startingCompass = newHeading.magneticHeading;
           self.lastCompass = self.startingCompass;
           self.currentCompass = self.startingCompass;
           NSLog(@"Turn One complete setup: %f", self.startingCompass);

      } else {
          // do something here
      }

1 个答案:

答案 0 :(得分:0)

暂时搁置180º并想象一个更一般的要求:您必须编写返回用户已转动的度数的代码,并且答案必须对于任意度数都是正确的。

很明显,您当前的方法不可行,因为如果用户转动720º,结果可能是0º。实现通过仅存储初始(startingCompass)和最终(currentCompass)状态而错过了大量信息,因此没有办法考虑滚动。

您应该做的是定义一个累加器变量,当用户的标题发生变化时,该变量会连续递增或递减。启动具有足够高频率的计时器,并在每个计时器刻度上计算现在和前一刻度之间的航向差异。然后将该值添加到累加器。