In a iOS game app I have two CAShapeLayers as sublayers to the main view layer. Their position is updated within a timer loop. The issue I have is that the shapes movement doesn't synchronize, and one is lagging behind the other. When I use code execution breaks and examine the screen at every execution of the timer block it works as expected. But when the app runs the lagging on screen is obvious. At every point in time the "speedArrow" is slightly behind the "ballBearing". The code for updating the 2 sublayers (ballBearing & speedArrow) is shown below.
Timer.scheduledTimer(withTimeInterval: sampleTime, repeats: true) {_ in
//more code
//Draw ball position bearing line
self.ballBearingPath.removeAllPoints()
self.ballBearingPath.move(to: tableCenter)
self.ballBearingPath.addLine(to: ballView.center)
self.ballBearing.path = self.ballBearingPath.cgPath
//Update speed vector position
let screenDist = Double(sqrt(pow(ballView.center.x-tableCenter.x, 2.0) + pow(ballView.center.y-tableCenter.y, 2.0)))
let deltaX = screenDist >= sWidth ? 0.85*sWidth*cos(.pi/2-ballBearingAngle): 0.85*screenDist*cos(.pi/2-ballBearingAngle)
let deltaY = screenDist >= sWidth ? -0.85*sWidth*sin(.pi/2-ballBearingAngle): -0.85*screenDist*sin(.pi/2-ballBearingAngle)
var transform = CATransform3DMakeTranslation(deltaX, deltaY, 0.0)
transform = CATransform3DRotate(transform, ballSpeedAngle, 0.0, 0.0, 1.0)
self.speedArrow.transform = transform
//more code
}
Initially I thought that the code within the Timer loop was taking more time to execute than the timer repetition interval but I did some timing experiments and this is not the case.