gpt4 book ai didi

swift - 检测绝对垂直轴上的加速度

转载 作者:行者123 更新时间:2023-11-28 12:14:51 26 4
gpt4 key购买 nike

我正在编写一个应用程序,我想在其中访问绝对垂直轴(即从地面到地板)的加速度数据,但是使用 CoreMotion 我只能从设备的相对轴检索加速度.例如,如果设备平放在 table 上,它的垂直轴实际上与绝对垂直轴成 90º。

我一直在研究陀螺仪数据试图解决这个问题,但数据没有意义。

// Make sure the accelerometer hardware is available.
if self.motion.isAccelerometerAvailable && self.motion.isDeviceMotionAvailable {
self.motion.accelerometerUpdateInterval = 1.0 / Double(slider.value) // Hz managed by slider
self.motion.startAccelerometerUpdates()
self.motion.startDeviceMotionUpdates(using: self.motion.attitudeReferenceFrame)
self.motion.deviceMotionUpdateInterval = 1.0 / Double(slider.value)



// Configure a timer to fetch the data.
self.timer = Timer(fire: Date(), interval: (1.0/Double(slider.value)),
repeats: true, block: { (timer) in
// Get the gyroscope data.

if let data = self.motion.deviceMotion {
//Angles: pitch
pitch = data.attitude.pitch
print("Pitch angle: \(self.degrees(radians: pitch))")

//Angles: yaw
yaw = data.attitude.yaw
print("Yaw angle: \(self.degrees(radians: yaw))")
}

//Get the accelerometer data

if let data = self.motion.accelerometerData {
let x = data.acceleration.x
//let y = data.acceleration.y
//let z = data.acceleration.z


// Use the accelerometer data in your app.
self.label.text = "x: \(x)"
let xCorrectedWithPitch = cos(self.degrees(radians: pitch)) * x
print("x: \(x)\nPitch: \(pitch)\nxCorrectedWithPitch: \(xCorrectedWithPitch)")
let xCorrectedWithYaw = cos(self.degrees(radians: yaw)) * xCorrectedWithPitch
print("x: \(x)\nYaw: \(yaw)\nxCorrectedWithYaw: \(xCorrectedWithYaw)")

// Use the accelerometer data in your app.

self.accelArrayY.append(xCorrectedWithYaw*9.81)
time = time + timer.timeInterval
self.timeArrayY.append(time)


}

任何人的帮助将不胜感激

最佳答案

CMMotionMagager 为您提供关于 iPhone 轴的加速度以及重力方向。通过将这两个相乘,您可以计算出来自/到地球的加速度。这是乘法结果的长度。我正在使用 Ray Wenderlich 的 3D Vector utils。

在你的 GameViewController 中:

  var motionManager: CMMotionManager!

在 GameViewController.viewDidLoad 中:

  motionManager = CMMotionManager()
motionManager.startDeviceMotionUpdates()

在游戏场景中:

 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()。

关于swift - 检测绝对垂直轴上的加速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47073389/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com