Obtain absolute rotation using CMDeviceMotion?

后端 未结 3 1373
醉酒成梦
醉酒成梦 2021-01-03 06:42

I\'m building a simple game with Sprite Kit, the screen doesn\'t rotate but I want to know the angle the user is holding the phone for a game mechanic.

The values I

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-03 07:36

    You can get the angle by reading the gyro data provided by CoreMotion. Initialize a CM object like so:

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

    Then in the update function, you can read it:

    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
        }
    }
    

    You can now use the x, y and z values for your game mechanic. However, note that it's giving the current rotation rate and not the absolute rotation. You could keep track of it yourself if that's what you need. Alternatively you could use the accelerometer data:

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

提交回复
热议问题