2012-08-09 83 views
0

我想旋轉圖像(三角形)以將其與重力對齊。所以一個角落總是下降。但沒有任何幫助。三角生氣。使用CMDeviceMotion旋轉圖像

double accelX = motion.userAcceleration.x; 
double accelY = motion.userAcceleration.y; 
rollingX = (accelX * kFilteringFactor) + (rollingX * (1.0 - kFilteringFactor)); 
rollingY = (accelY * kFilteringFactor) + (rollingY * (1.0 - kFilteringFactor)); 
accelX = accelX - rollingX; 
accelY = accelY - rollingY; 
float angle = atan2(accelY, accelX); 

[rootLayer setAnchorPoint:CGPointMake(0.5, 0.5)]; 
CATransform3D rotation = CATransform3DIdentity; 
rotation.m34 = 1.0f/-500.0f; 
rotation = CATransform3DRotate(rotation, angle, 0.0f, 0.0f, 1.0f); 
rootLayer.sublayerTransform = rotation; 

回答

0

Asssuming是motion指CMDeviceMotion的實例,你應該使用gravity屬性代替用戶加速。那麼你必須直接使用重力矢量,即不用任何濾波。這是最簡單和推薦的方式,因爲它使用陀螺儀以提高精度。

如果因爲想要支持沒有陀螺儀的舊設備而必須使用純加速度計數據,則必須使用CMMotionManager的accelerometerData屬性。但是有一個小錯誤。代碼將高通濾波器應用於accelXaccelY而不是低通濾波器。因此,它應該是這樣的:

double accelX = motionManager.accelerometerData.acceleration.x; 
double accelY = motionManager.accelerometerData.acceleration.y; 
rollingX = (accelX * kFilteringFactor) + (rollingX * (1.0 - kFilteringFactor)); 
rollingY = (accelY * kFilteringFactor) + (rollingY * (1.0 - kFilteringFactor)); 
float angle = atan2(rollingY, rollingX); 

filteringFactor < = 0.3

+0

感謝。我已經嘗試了CMGyroData,但沒有運氣。 CMGyroData * gyroData = [_notification.userInfo objectForKey:@「gyroNotification」]; CMRotationRate rotate = gyroData.rotationRate; CATransform3D rotation = rootLayer.sublayerTransform; rotation.m34 = 1.0f/-500.0f;旋轉=旋轉,旋轉.y,0.0f,0.0f,1.0f); rootLayer.sublayerTransform =旋轉; – 2012-08-10 09:19:54