# 使用 CMDeviceMotion 获得绝对旋转?[英] Obtain absolute rotation using CMDeviceMotion?

### 问题描述

```if let data = motionManager.accelerometerData? {
let y = CGFloat(data.acceleration.y)
let x = CGFloat(data.acceleration.x)
}

// Device Motion
if let attitude = motionManager.deviceMotion?.attitude? {
let y = CGFloat(-attitude.pitch * 2 / M_PI) // This matches closely with data.acceleration.y
let x = ??????????
}
```

## 推荐答案

```            if let attitude = motionManager.deviceMotion?.attitude? {
// Convert pitch and roll to [-1, 1] range
let pitch = CGFloat(-attitude.pitch * 2 / M_PI)
let roll = CGFloat(abs(attitude.roll) > M_PI / 2 ? (2 - abs(attitude.roll) * 2 / M_PI) * (attitude.roll > 0 ? 1 : -1) : attitude.roll * 2 / M_PI)

// Calculate x and y
let y = pitch
let x = roll*(1.0-abs(pitch))
}
```

## 其他推荐答案

<块引用>

CMDeviceMotion 的一个实例封装了对设备的姿态、旋转速率和加速度的测量.

```import SpriteKit
import CoreMotion

class GameScene: SKScene {
let motionManager = CMMotionManager()

override func didMoveToView(view: SKView) {
motionManager.deviceMotionUpdateInterval = 1.0 / 30.0
}

override func willMoveFromView(view: SKView!) {
}

override func update(currentTime: CFTimeInterval) {
if let attitude = motionManager.deviceMotion?.attitude? {
println(attitude)
let y = CGFloat(-attitude.pitch * 2 / M_PI)
let x = CGFloat(-attitude.roll * 2 / M_PI)
}
}
}
```

```class GameScene: SKScene {
let motionManager = CMMotionManager()

override func didMoveToView(view: SKView) {
motionManager.deviceMotionUpdateInterval = 1.0 / 30.0
}

override func willMoveFromView(view: SKView) {
}

override func update(currentTime: CFTimeInterval) {
if let attitude = motionManager.deviceMotion?.attitude {
print(attitude)
let y = CGFloat(-attitude.pitch * 2 / M_PI)
let x = CGFloat(-attitude.roll * 2 / M_PI)
}
}
}
```

## 其他推荐答案

```class GameScene: SKScene {
var motionManager = CMMotionManager()
override func didMoveToView(view: SKView) {
}
}
```

```override func update(currentTime: CFTimeInterval) {
if let data = motionManager.gyroData {
let x = data.rotationRate.x
let y = data.rotationRate.y
let z = data.rotationRate.z
}
}
```

```motionManager.startAccelerometerUpdates()
...
if let data = motionManager.accelerometerData {
let x = data.acceleration.x
}
```