0

In my SpriteKit game I have two sprites that rotate towards the point of touch. Also I have enemy sprites that fall from the top and travel down with increased frequency over time. After about thirty seconds of continuous touch with touchesMoved the sprite rotation and enemy sprite movement become very choppy as the frame rate drops to 30. I figure that this is caused by too much graphics processing on the main thread. Is there any way to handle the sprite rotation through CADisplayLink inside touchesBegan and touchesMoved?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?){
    for touch: AnyObject in touches {
        location = touch.location(in: self)
        let DegreesToRadians = Pi / 180

        let rightDeltaX = location.x - rightSprite.position.x
        let rightDeltaY = location.y - rightSprite.position.y
        let rightAngle = atan2(rightDeltaY, rightDeltaX)

        let leftDeltaX = location.x - leftSprite.position.x
        let leftDeltaY = location.y - leftSprite.position.y
        let leftAngle = atan2(leftDeltaY, leftDeltaX)

        leftSprite.zRotation = leftAngle - 90 * DegreesToRadians

        rightSprite.zRotation = rightAngle - 90 * DegreesToRadians

        }
    }
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch: AnyObject in touches {
        location = touch.location(in: self)
        let DegreesToRadians = Pi / 180

        let rightDeltaX = location.x - rightSprite.position.x
        let rightDeltaY = location.y - rightSprite.position.y
        let rightAngle = atan2(rightDeltaY, rightDeltaX)

        let leftDeltaX = location.x - leftSprite.position.x
        let leftDeltaY = location.y - leftSprite.position.y
        let leftAngle = atan2(leftDeltaY, leftDeltaX)

        leftSprite.zRotation = leftAngle - 90 * DegreesToRadians

        rightSprite.zRotation = rightAngle - 90 * DegreesToRadians

    }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch: AnyObject in touches {
        location = touch.location(in: self)

        leftSprite.zRotation = 0

        rightSprite.zRotation = 0

    }
}
stepjesse
  • 37
  • 6
  • Your code wouldn't cause lag, are you doing this on the simulator? – Knight0fDragon Aug 07 '18 at 02:12
  • I was testing this on iPhone 6 and iPad Pro 10.5, but I just realized that the only thing I didn't include in this post was that the sprites have SKConstraints for their zRotation. I went ahead and ran the code without the constraints and now it runs without lag – stepjesse Aug 07 '18 at 03:54
  • then you are not using your constraints properly, thus the lagging. – Knight0fDragon Aug 07 '18 at 13:14

0 Answers0