更新时间:2023-11-09 22:07:34
CMMotionMagager可使您绕iPhone的轴以及重力方向加速。通过将这两者相乘,您可以计算出从地球到地球的加速度。这是相乘结果的长度。我正在使用Ray Wenderlich的3D Vector工具。
CMMotionMagager gives you acceleration about the iPhone's axes and also the direction of gravity. By multiplying these two you can calculate the acceleration from/to the earth. It's the length of the result of this multiplication. I'm using Ray Wenderlich's 3D Vector utils.
在您的GameViewController中:
In your GameViewController:
var motionManager: CMMotionManager!
在GameViewController.viewDidLoad中:
In GameViewController.viewDidLoad:
motionManager = CMMotionManager()
motionManager.startDeviceMotionUpdates()
在GameScene中:
In GameScene:
override func update(_ currentTime: TimeInterval) {
if let deviceMotion = motionManager.deviceMotion {
let gravityVector = Vector3(x: CGFloat(deviceMotion.gravity.x),
y: CGFloat(deviceMotion.gravity.y),
z: CGFloat(deviceMotion.gravity.z))
let userAccelerationVector = Vector3(x: CGFloat(deviceMotion.userAcceleration.x),
y: CGFloat(deviceMotion.userAcceleration.y),
z: CGFloat(deviceMotion.userAcceleration.z))
// Acceleration to/from earth
let zVector = gravityVector * userAccelerationVector
let zAcceleration = zVector.length()
}
要知道运动方向:
sign(Double(zVector.x * zVector.y * zVector.z))
当您不再需要它时,请不要忘记调用.stopDeviceMotionUpdates()。
Don't forget to call .stopDeviceMotionUpdates() when you don't need it anymore.