Im using the accelerometer as the steering mechanism for my game. It works fine usually but occasionally it will act very odd. Randomly there is suddenly a large amount of input delay and every rotation I make isn't registered for a while. In some cases there might be a lot of delay in between commands entered right after each other leading to my character drifting in one direction for far too long. Is this due to game lag or is my code at fault? My code below.
actionMoveLeft = SKAction.moveBy(x: -3, y: 0, duration: 0.1)
actionMoveRight = SKAction.moveBy(x: 3, y: 0, duration: 0.1)
self.addChild(ship)
if motionManager.isAccelerometerAvailable == true {
motionManager.startAccelerometerUpdates(to: OperationQueue.current!, withHandler:{
data, error in
if (data!.acceleration.y) < -0.05 {
self.ship.run(self.actionMoveLeft)
}
else if data!.acceleration.y > 0.05 {
self.ship.run(self.actionMoveRight)
}
})
}
It's not guaranteed that the accelerometer will give you updates with regular intervals of 0.1 seconds (assuming that the deviceMotionUpdateInterval property of your CMMotionManager instance is set to 0.1). SKActions work fine when every action is executed at a discrete interval of time. But since the accelerometer gives you irregular interval updates, you may end up executing more actions at the same time.
An easy fix for that would be to remove the previous action every time:
if (data!.acceleration.y) < -0.05 {
self.ship.removeAction(forKey: "Move")
self.ship.run(self.actionMoveLeft, withKey: "Move")
}
But I still not recommend to use this approach, because the movement still doesn't look smooth, but it looks like your ship is moving jerkily. I suggest to use a SKPhysicsBody and directly manipulate its velocity property. Something like this:
// Inside the update method, assuming you have saved the acceleration vector
// and you have a deltaTime variable that holds the difference of time
// elapsed from the previous update
self.ship.physicsBody.velocity = CGVector(dx: self.ship.physicsBody.velocity.dx + CGFloat(acceleration.x * deltaTime), dy: self.ship.physicsBody.velocity.dy + CGFloat(acceleration.y * deltaTime))
If you don't want to use a physics body because you're just handling physics using your custom functions, then I suggest to compute the position of the ship manually at every frame.