I'm constructing a Swift Playground with UIKit that contains an SKScene. After creating the code I'm planning to use within an Xcode project, I tried to adapt it into my Playground.
I encountered an issue while running the Playground - when a new SKSpriteNode is added to the Scene, the new and existing nodes jitter, freeze, and lag for a split-second, the FPS counter drops to around 49fps, then returns to smooth 60fps. No errors or warnings are spat, and the console is completely empty.
The scene in the project didn't have this issue, and I can't recreate it on another project - even when I directly copy-paste the code from the Playground to the project.
I've seen other posts with this question - and made a few myself elsewhere - and there's been no responses. I desperately need help for this as nothing I've tried is working and the deadline is in a few days!
Thanks!
The code that is in effect for this SKScene is below.
class SimulatorController: UIViewController {
override func loadView() {
let view = SKView()
let scene = GameScene(size: view.bounds.size)
view.showsFPS = true
view.showsNodeCount = true
view.ignoresSiblingOrder = true
scene.scaleMode = .resizeFill
view.presentScene(scene)
self.view = view
}
}
class GameScene: SKScene {
override func didMove(to view: SKView) {
run(SKAction.repeatForever(SKAction.sequence([
SKAction.run(addNeutron),
SKAction.wait(forDuration: 1)
])
))
}
func random() -> CGFloat {
return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
func random(min: CGFloat, max: CGFloat) -> CGFloat {
return random() * (max - min) + min
}
func addNeutron() {
let neutron = SKSpriteNode(imageNamed: "neutron.heic")
neutron.size = CGSize(width: 20, height: 20)
neutron.physicsBody = SKPhysicsBody(rectangleOf: neutron.size)
neutron.physicsBody?.isDynamic = true
let actualX = random(min: 0, max: size.width)
let actualY = random(min: 0, max: size.height)
neutron.position = CGPoint(x: actualX, y: actualY)
addChild(neutron)
let actualDuration = random(min: CGFloat(2.0), max: CGFloat(4.0))
let actualX2 = random(min: 0, max: size.width)
let actualY2 = random(min: 0, max: size.height)
let actionMove = SKAction.move(to: CGPoint(x: actualX2, y: actualY2), duration: TimeInterval(actualDuration))
let actionMoveDone = SKAction.removeFromParent()
neutron.run(SKAction.sequence([actionMove, actionMoveDone]))
}
}