开发者

Objective-C how do I "rotate" an "angular" value

开发者 https://www.devze.com 2023-02-11 06:18 出处:网络
Ok, I agree, my math is rusty and it stinks and my brain is completely empty right now. I have a function that delivers me angles in the range of 0 to 360 degrees (or 0 to 2PI if you prefer). When I

Ok, I agree, my math is rusty and it stinks and my brain is completely empty right now.

I have a function that delivers me angles in the range of 0 to 360 degrees (or 0 to 2PI if you prefer). When I use this function with the gyroscope data, I see that when it says the device is 270 degrees, it is in fact zero degrees. So, if I rotate it from 270 to 360, I need the angles to be varying from 0 to 90.

How do I convert this?

If I simply subtract 270 degrees from the values coming, I will end with negative angles and I don't want that. What I need is to shift the values so:

270 degrees... will become zero,
360 (=0)... will become 90,
90 will be 180 and
180 will be 270.

H开发者_Go百科ow do I shift that mathematically speaking.

thanks.


You could also walk along modulo lane. The basic trick is to keep degrees positive and then use the modulo, so the remainder of a division. Of course rotating 270 degree in one direction is the same as rotating 90 degrees in the other direction, so my implementation looks like this:

- (NSInteger) convertAngle:(NSInteger)oldAngle {
  NSInteger newAngle = oldAngle + 90;
  return newAngle%360;
}


double trans(double ang) { 
  ang+=270; 
  return (ang>=360)?ang-360:ang; 
}

Or in one step:

double trans(double ang) {
 return (ang>=90)?ang-90:ang+270;
}


I believe you want:

- (NSInteger)adjustedDegrees:(NSInteger)degrees {
    return ((degrees - 270) % 360);
}

You can use what's called modular arithmetic, which does your subtraction, then takes the positive remainder after dividing by 360.


I think this will do it

float angle = gyroscopeValue;
angle += 90;
if(angle == 360)
    angle = 90;
if(angle == 270)
    angle =0;
0

精彩评论

暂无评论...
验证码 换一张
取 消