我在一次采访中遇到了这个问题,完全被难住了。我能想到的唯一解决方案是将 currentAngle
存储在 NSArray
中以计算下一个角度。
问题: 使用 iPhone 的指南针在屏幕上移动一个 35px 的球。一旦球位于屏幕中央,让用户点击它以“重置”位置。重置后,球将回到 Min
位置。请记住,指南针可能从 0-359 之间的某个位置开始,任务是找到最近的捕获角度并专注于该角度,直到球对齐。球对齐并重置后,iPhone 将移动到下一个角度,依此类推,直到球被重置 18
次。 18 次重置
* 20 度角
= 360
。
分配的变量:
int currentAngle = (Ranging between 0-359) (Constant updates as the user twirls around)
int captureAngle = 20
int centerX = view.center.x (160) - 35 (size of ball)
int ballSize = 35 (ball.width/2)
论文看起来像这样:
到目前为止的功能:
-(void)testMotion{
motionQueue = [[NSOperationQueue alloc] init];
motionManager = [[CMMotionManager alloc] init];
motionManager.deviceMotionUpdateInterval = 1.0f / 60.0f;
if (([CMMotionManager availableAttitudeReferenceFrames] & CMAttitudeReferenceFrameXTrueNorthZVertical) != 0) {
[motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXTrueNorthZVertical
toQueue:motionQueue
withHandler:^(CMDeviceMotion *motion, NSError *error)
{
if (!error) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
CMAttitude *attitude = motion.attitude;
CMRotationMatrix rm = attitude.rotationMatrix;
// Get the heading.
double heading = M_PI + atan2(rm.m22, rm.m12);
heading = heading*180/M_PI;
int currentAngle = (int)heading;
NSLog(@"Current Angle: %d",currentAngle);
int captureAngle = 20; // 20 Degress Capture Angle
}];
}
}];
}
}
请您参考如下方法:
如果我理解你的话,那就是这样的: 从角度计算 x 和 y 运动 (看 https://en.wikipedia.org/wiki/Rotation_of_axes
http://keisan.casio.com/has10/SpecExec.cgi?id=system/2006/1223522781 )
然后根据这些值移动球,如果它移动了 20 度的角度 - 允许重置它或退出循环(供您选择)
while(1) {
x = r \cos(currentAngle)
y = r \sin(currentAngle)
//change the ball position,
ball.position.x += x*speed
ball.position.y += y*speed
//check if angel is +20 or -20
if (((currentAngle + 20) % 360) != captureAngle && (abs(currentAngle - 20) % 360) != captureAngle)) {
allow_reset_ball = true
break;
}
}