My app uses CoreMotion to allow the player to move when the device is tilted. It worked perfectly in Swift 2 but when I updated it to Swift 3 it has stopped working. I am not receiving any accelerometer updates.
override func didMove(to view: SKView) {
manager.startAccelerometerUpdates()
manager.accelerometerUpdateInterval = 0.1
manager.startAccelerometerUpdates(to: OperationQueue.main){ (data, Error) in
if let accelerometerData = self.manager.accelerometerData {
self.physicsWorld.gravity = CGVector(dx: accelerometerData.acceleration.y * 10, dy: accelerometerData.acceleration.x * 10)
}
}
}
NSError has been renamed to Error in Swift 3, so please make your Error variable camelCase (lowercase in your situation). It should have been camelCase since it's a variable, anyways.
Here is a new version of the function with that and other minor errors fixed (NOTE MY COMMENT ABOUT SWAPPING X AND Y):
override func didMove(to view: SKView) {
manager.accelerometerUpdateInterval = 0.1
manager.startAccelerometerUpdates(to: OperationQueue.main) { data, _ in
if let accelerometerData = data {
// IMPORTANT: Are you intentionally swapping x and y here? -----------> ↓
self.physicsWorld.gravity = CGVector(dx: accelerometerData.acceleration.y * 10,
dy: accelerometerData.acceleration.x * 10)
}
}
}
And here is the original function with just the variable renamed (NOTE: There are a few programming mistakes in here, I don't recommend using it):
override func didMove(to view: SKView) {
manager.startAccelerometerUpdates()
manager.accelerometerUpdateInterval = 0.1
manager.startAccelerometerUpdates(to: OperationQueue.main) { (data, error) in
if let accelerometerData = self.manager.accelerometerData {
self.physicsWorld.gravity = CGVector(dx: accelerometerData.acceleration.y * 10, dy: accelerometerData.acceleration.x * 10)
}
}
}
EDIT: You should not use the main queue as your OperationQueue for recieving Accelerometer updates. See Apple's documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With