我想知道如何创建代码,允许我将iPhone平放在曲面上并向前移动以获得正y值,返回到-y,向左获取-x并获得 - X。我使用的代码似乎只测量正加速度,当手机平放在表面上时,我无法生成负值。如果我拿起手机然后将其向右或向左倾斜,我将获得正x和负x并且与y相同,但是我希望在将其留在表面上并且仅在左右方向上移动手机时具有相同的效果保持面朝前,没有任何类型的转动或旋转。我正在使用swift,但如果有解决方案,也会很乐意使用对象c。
import UIKit
import CoreMotion
class ViewController: UIViewController {
var currentMaxAccelX: Double = 0.0
var currentMaxAccelY: Double = 0.0
var currentMaxAccelZ: Double = 0.0
let motionManager = CMMotionManager()
@IBOutlet var accX : UILabel? = nil
@IBOutlet var accY : UILabel? = nil
@IBOutlet var accZ : UILabel? = nil
@IBOutlet var maxAccX : UILabel? = nil
@IBOutlet var maxAccY : UILabel? = nil
@IBOutlet var maxAccZ : UILabel? = nil
override func viewDidLoad() {
super.viewDidLoad()
motionManager.accelerometerUpdateInterval = 0.1
//[self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue new] withHandler:^(CMDeviceMotion *motion, NSError *error)
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler: {(accelerometerData: CMAccelerometerData!, error:NSError!)in
self.outputAccelerationData(accelerometerData.acceleration)
if (error != nil)
{
println("\(error)")
}
})
}
func outputAccelerationData(acceleration:CMAcceleration)
{
// Swift does not have string formation yet
accX?.text = NSString(format:"%.4f", acceleration.x) as String
if fabs(acceleration.x) > fabs(currentMaxAccelX)
{
currentMaxAccelX = acceleration.x
}
accY?.text = NSString(format:"%.4f", acceleration.y) as String
if acceleration.y > currentMaxAccelY
{
currentMaxAccelY = acceleration.y
}
accZ?.text = NSString(format:"%.4f", acceleration.z) as String
if acceleration.z > currentMaxAccelZ
{
currentMaxAccelZ = acceleration.z
}
maxAccX?.text = NSString(format:"%.4f", currentMaxAccelX) as String
maxAccY?.text = NSString(format:"%.4f", currentMaxAccelY) as String
maxAccZ?.text = NSString(format:"%.4f", currentMaxAccelZ) as String
}