SpriteKit

RSS for tag

Drawing shapes, particles, text, images, and video in two dimensions using SpriteKit.

Posts under SpriteKit tag

44 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

GameplayKit usage with Swift 6: Call to main actor-isolated instance method 'run' in a synchronous nonisolated context
Hi there, With a couple of other developers we have been busy with migrating our SpriteKit games and frameworks to Swift 6. There is one issue we are unable to resolve, and this involves the interaction between SpriteKit and GameplayKit. There is a very small demo repo created that clearly demonstrates the issue. It can be found here: https://github.com/AchrafKassioui/GameplayKitExplorer/blob/main/GameplayKitExplorer/Basic.swift The relevant code also pasted here: import SwiftUI import SpriteKit struct BasicView: View { var body: some View { SpriteView(scene: BasicScene()) .ignoresSafeArea() } } #Preview { BasicView() } class BasicScene: SKScene { override func didMove(to view: SKView) { size = view.bounds.size anchorPoint = CGPoint(x: 0.5, y: 0.5) backgroundColor = .gray view.isMultipleTouchEnabled = true let entity = BasicEntity(color: .systemYellow, size: CGSize(width: 100, height: 100)) if let renderComponent = entity.component(ofType: BasicRenderComponent.self) { addChild(renderComponent.sprite) } } } @MainActor class BasicEntity: GKEntity { init(color: SKColor, size: CGSize) { super.init() let renderComponent = BasicRenderComponent(color: color, size: size) addComponent(renderComponent) let animationComponent = BasicAnimationComponent() addComponent(animationComponent) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } @MainActor class BasicRenderComponent: GKComponent { let sprite: SKSpriteNode init(color: SKColor, size: CGSize) { self.sprite = SKSpriteNode(texture: nil, color: color, size: size) super.init() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class BasicAnimationComponent: GKComponent { let action1 = SKAction.scale(to: 1.3, duration: 0.07) let action2 = SKAction.scale(to: 1, duration: 0.15) override init() { super.init() } override func didAddToEntity() { if let renderComponent = entity?.component(ofType: BasicRenderComponent.self) { renderComponent.sprite.run(SKAction.repeatForever(SKAction.sequence([action1, action2]))) } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } As SKNode is designed to run on the MainActor, the BasicRenderComponent is attributed with MainActor as well. This is needed as this GKComponent is dedicated to encapsulate the node that is rendered to the scene. There is also a BasicAnimationComponent, this GKComponent is responsible for animating the rendered node. Obviously, this is just an example, but when using GameplayKit in combination with SpriteKit it is very common that a GKComponent instance manipulates an SKNode referenced from another GKComponent instance, often done via open func update(deltaTime seconds: TimeInterval) or as in this example, inside didAddToEntity. Now, the problem is that in the above example (but the same goes foupdate(deltaTime seconds: TimeInterval) the methoddidAddToEntity is not isolated to the MainActor, as GKComponent is not either. This leads to the error Call to main actor-isolated instance method 'run' in a synchronous nonisolated context, as indeed the compiler can not infer that didAddToEntity is isolated to the MainActor. Marking BasicAnimationComponent as @MainActor does not help, as this isolation is not propogated back to the superclass inherited methods. In fact, we tried a plethora of other options, but none resolved this issue. How should we proceed with this? As of now, this is really holding us back migrating to Swift 6. Hope someone is able to help out here!
1
2
241
7h
SKLabelNode keeps jumping back and forth when displaying different numbers with equal number of digits
I'm trying to display a right-aligned timecode in my game. I had expected that digits would all have the same width, but this doesn't seem to be the case in SpriteKit, even though it seems to be the case in AppKit. In SpriteKit, with the default font there is a noticeable difference in width between the digit 1 and the rest (1 is thinner), so whenever displaying a number with the least significant digit 1 all preceding digits shift slightly to the right. This happens even when setting a NSAttributedString with a font that has a fixedAdvance attribute. class GameScene: SKScene { override func didMove(to view: SKView) { let label = SKLabelNode(text: "") view.scene!.addChild(label) // label.horizontalAlignmentMode = .left label.horizontalAlignmentMode = .right var i = 11 Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { _ in label.text = "\(i)" // let font = NSFont(descriptor: NSFontDescriptor(fontAttributes: [.name: "HelveticaNeue-UltraLight", .fixedAdvance: 20]), size: 30)! // let paragraphStyle = NSMutableParagraphStyle() // paragraphStyle.alignment = .right // label.attributedText = NSAttributedString(string: "\(i)", attributes: [.font: font, .foregroundColor: SKColor.labelColor, .paragraphStyle: paragraphStyle]) i += 5 } } } With AppKit, when using SpriteKit's default font HelveticaNeue-UltraLight, this issue doesn't exist, regardless whether I set the fixedAdvance font attribute. class ViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() let font = NSFont(descriptor: NSFontDescriptor(fontAttributes: [.name: "HelveticaNeue-UltraLight"]), size: 30)! // let font = NSFont(descriptor: NSFontDescriptor(fontAttributes: [.name: "HelveticaNeue-Light", .fixedAdvance: 20]), size: 30)! let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .right let textField = NSTextField(labelWithString: "") textField.font = font textField.alignment = .right // textField.alignment = .left textField.frame = CGRect(x: 100, y: 100, width: 100, height: 100) view.addSubview(textField) var i = 11 Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { _ in textField.stringValue = "\(i)" // textField.attributedStringValue = NSAttributedString(string: "\(i)", attributes: [.font: font, .paragraphStyle: paragraphStyle]) i += 5 } } } Is there a solution to this problem? I filed FB15553700.
0
0
88
1w
SKAction.removeFromParent() causes crash when run in SCNView.overlaySKScene on iOS
Even when the action is run on the main thread, the following code causes a crash on iOS, but not on macOS. The game launches with a simple yellow rectangle, and when it finishes fading out and should be removed from the overlay scene, the app crashes. The code can be pasted into the file GameController.swift of Xcode's default project for Multiplatform macOS and iOS game. import SceneKit import SpriteKit @MainActor class GameController: NSObject { let scene: SCNScene let sceneRenderer: SCNSceneRenderer init(sceneRenderer renderer: SCNSceneRenderer) { sceneRenderer = renderer scene = SCNScene(named: "Art.scnassets/ship.scn")! super.init() sceneRenderer.scene = scene renderer.overlaySKScene = SKScene(size: CGSize(width: 500, height: 500)) DispatchQueue.main.async { let node = SKShapeNode(rect: CGRect(x: 100, y: 100, width: 100, height: 100)) node.fillColor = .yellow node.run(.sequence([ .fadeOut(withDuration: 1), .removeFromParent() ])) renderer.overlaySKScene!.addChild(node) } } } The Xcode console shows this stacktrace: *** Assertion failure in -[UIApplication _performAfterCATransactionCommitsWithLegacyRunloopObserverBasedTiming:block:], UIApplication.m:3246 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Call must be made on main thread' *** First throw call stack: ( 0 CoreFoundation 0x00000001804ae0f8 __exceptionPreprocess + 172 1 libobjc.A.dylib 0x0000000180087db4 objc_exception_throw + 56 2 Foundation 0x0000000180d17058 _userInfoForFileAndLine + 0 3 UIKitCore 0x00000001853cf678 -[UIApplication _performAfterCATransactionCommitsWithLegacyRunloopObserverBasedTiming:block:] + 376 4 UIKitCore 0x000000018553f7a0 -[_UIFocusUpdateThrottle scheduleProgrammaticFocusUpdate] + 300 5 UIKitCore 0x0000000184e2e22c -[UIFocusSystem _requestFocusUpdate:] + 548 6 UIKitCore 0x0000000184e2dfa4 -[UIFocusSystem requestFocusUpdateToEnvironment:] + 76 7 UIKitCore 0x0000000184e2e864 -[UIFocusSystem _focusEnvironmentWillDisappear:] + 408 8 SpriteKit 0x00000001a3d472f4 _ZL12_removeChildP6SKNodeS0_P7SKScene + 240 9 SpriteKit 0x00000001a3d473b0 -[SKNode removeChild:] + 80 10 SpriteKit 0x00000001a3d466b8 -[SKNode removeFromParent] + 128 11 SpriteKit 0x00000001a3d1678c -[SKRemove updateWithTarget:forTime:] + 64 12 SpriteKit 0x00000001a3d1b740 _ZN11SKCSequence27cpp_updateWithTargetForTimeEP7SKCNoded + 84 13 SpriteKit 0x00000001a3d20e3c _ZN7SKCNode6updateEdf + 156 14 SpriteKit 0x00000001a3d20f20 _ZN7SKCNode6updateEdf + 384 15 SpriteKit 0x00000001a3d26fb8 -[SKScene _update:] + 464 16 SpriteKit 0x00000001a3cf3168 -[SKSCNRenderer _update:] + 80 17 SceneKit 0x000000019c932bf0 -[SCNMTLRenderContext renderSKSceneWithRenderer:overlay:atTime:] + 60 18 SceneKit 0x000000019c9ebd98 -[SCNRenderer _drawOverlaySceneAtTime:] + 204 19 SceneKit 0x000000019cb1a1c0 _ZN3C3D11OverlayPass7executeERKNS_10RenderArgsE + 60 20 SceneKit 0x000000019c8e05ec _ZN3C3D13__renderSliceEPNS_11RenderGraphEPNS_10RenderPassERtRKNS0_9GraphNodeERPNS0_5StageENS_10RenderArgsEbRPU27objcproto16MTLCommandBuffer11objc_object + 2660 21 SceneKit 0x000000019c8e18ac _ZN3C3D11RenderGraph7executeEv + 3808 22 SceneKit 0x000000019c9ed26c -[SCNRenderer _renderSceneWithEngineContext:sceneTime:] + 756 23 SceneKit 0x000000019c9ed544 -[SCNRenderer _drawSceneWithNewRenderer:] + 208 24 SceneKit 0x000000019c9ed9fc -[SCNRenderer _drawScene:] + 40 25 SceneKit 0x000000019c9edce4 -[SCNRenderer _drawAtTime:] + 500 26 SceneKit 0x000000019ca87950 -[SCNView _drawAtTime:] + 368 27 SceneKit 0x000000019c943b74 __83-[NSObject(SCN_DisplayLinkExtensions) SCN_setupDisplayLinkWithQueue:screen:policy:]_block_invoke + 44 28 SceneKit 0x000000019ca50600 -[SCNDisplayLink _displayLinkCallbackReturningImmediately] + 132 29 libdispatch.dylib 0x000000010239173c _dispatch_client_callout + 16 30 libdispatch.dylib 0x0000000102394c14 _dispatch_continuation_pop + 756 31 libdispatch.dylib 0x00000001023aa4e0 _dispatch_source_invoke + 1736 32 libdispatch.dylib 0x00000001023997f0 _dispatch_lane_serial_drain + 340 33 libdispatch.dylib 0x000000010239a774 _dispatch_lane_invoke + 420 34 libdispatch.dylib 0x00000001023a71a8 _dispatch_root_queue_drain_deferred_wlh + 324 35 libdispatch.dylib 0x00000001023a6604 _dispatch_workloop_worker_thread + 488 36 libsystem_pthread.dylib 0x000000010242bb74 _pthread_wqthread + 284 37 libsystem_pthread.dylib 0x000000010242a934 start_wqthread + 8 ) libc++abi: terminating due to uncaught exception of type NSException Am I doing something wrong?
5
0
190
1w
Not getting scroll wheel input
Hi all, I'm new to swift and I've just gotten started by making a simple pong-like game using SpriteKit. I'm trying to use the scroll wheel input to spin an object, however, nothing seems to make this work. From my googling and AI advice the way I've been doing it should, as shown in the snippet below, however debugging suggests the scrollWheel function isn't even being called. #if os(OSX) extension GameScene { override func scrollWheel(with event: NSEvent ) { print("Scroll detected: \(event.scrollingDeltaY)") let scrollDelta = event.scrollingDeltaY self.rotatePaddle(value: scrollDelta) } } #endif I have changed the build targets in Xcode to Mac os, not the designed-for-ipad version of it, and the app does launch and draw sprites correctly as well as detect other mouse or trackpad inputs like mouseDown and rightMouseDown, so it only seems to be this one specific input not working. I've also tried hardware debugging like restarting Xcode and my Mac, but no luck there either. Maybe I've missed something or am doing it completely wrong, so any help would be much appreciated. Thanks heaps
1
0
169
3w
What triggers Game Mode?
What are the specific characteristics that trigger Game Mode in an iOS game? I have several casual SpriteKit games in the App Store but only one of them triggers Game Mode. What does GCSupportsGameMode do when set to true? Will it trigger Game Mode or will the OS still decide by itself?
1
0
319
3w
iOS 18 arm64 simulator disables audio output with unknown "AudioConverterService" error
Hello, I'm getting an unknown, never-before-seen error at application launch, when running my iOS SpriteKit game on the iOS 18 arm64 simulator from Xcode 16.0 (16A242d) — AudioConverterOOP.cpp:847 Failed to prepare AudioConverterService: -302 This is occurs on all iOS 18 simulator devices, between application(_:didFinishLaunchingWithOptions:) and the first applicationDidBecomeActive(_:) — the SKScene object may have been already initialized by SpriteKit, but the scene's didMove(to:) method hasn't been called yet. Also, note that the error message is being emitted from a secondary (non-main) thread, obviously not created by the app. After the error occurs, no SKScene is able to play audio — this had never occurred on iOS versions prior to 18, neither on physical devices nor on the simulator. Has anyone seen anything like this on a physical device running 18? Unfortunately, at the moment I cannot test myself on an 18 device, only on the simulator... Thank you, D.
2
0
335
Sep ’24
Determining SpriteKit Interaction using SKRenderer
Hey, Wondering how other developers have been able to determine the location of a mouse event or tap (ie NSEvent) when using MetalView (MKTView) with SKRenderer with a SpriteKit scene (.sks scene) for a 2D game. In the original scenario with SpriteKit, we could use SKViews convertPoint(fromView:) to determine where in the scene the user tapped. But with the SKRenderer we can no longer use convertPoint(fromView:) as its reliant on SKView being used and thus its making it difficult to determine. What I do have is: locationInWindow: NSPoint for showing me where in the MKTView which was touched Any ideas, would be great Many thanks
0
0
240
Sep ’24
SKTexture initialized with system UIImage has slightly wrong aspect ratio and ignores system symbol color
On macOS, system symbols displays in a SKTexture as expected, with the correct color and aspect ratio. But on iOS they are always displayed in black, and sometimes with slightly wrong aspect ratio. Is there a solution to this problem? import SpriteKit #if os(macOS) import AppKit #else import UIKit #endif class GameScene: SKScene { override func didMove(to view: SKView) { let systemImage = "square.and.arrow.up" let width = 400.0 #if os(macOS) let image = NSImage(systemSymbolName: systemImage, accessibilityDescription: nil)!.withSymbolConfiguration(.init(hierarchicalColor: .white))! let scale = NSScreen.main!.backingScaleFactor image.size = CGSize(width: width * scale, height: width / image.size.width * image.size.height * scale) #else let image = UIImage(systemName: systemImage)!.applyingSymbolConfiguration(.init(pointSize: width))!.applyingSymbolConfiguration(.init(hierarchicalColor: .white))! #endif let texture = SKTexture(image: image) print(image.size, texture.size(), image.size.width / image.size.height) let size = CGSize(width: width, height: width / image.size.width * image.size.height) addChild(SKSpriteNode(texture: texture, size: size)) } }
8
0
459
Sep ’24
SceneKit app randomly crashes with EXC_BAD_ACCESS in jet_context::set_fragment_texture
Every now and then my SceneKit game app crashes and I have no idea why. The SCNView has a overlaySKScene, so it might also be SpriteKit's fault. The stack trace is #0 0x0000000241c1470c in jet_context::set_fragment_texture(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>> const&, jet_texture*) () #27 0x000000010572fd40 in _pthread_wqthread () Does anyone have an idea where I could start debugging this, without being able to consistently reproduce it?
9
0
509
Sep ’24
Best way to navigate multiple game screens
Good morning everyone, I'm building a simple game (my first game) using SwiftUI and SpriteKit that contains multiple views. I'm writing my game based on a main scene loaded into the GameView using a SpriteView. From there, using buttons, I move from one scene to another using self.scene?.view?.presentScene(...) and also with some cool transitions (.crossFade(withDuration: 0.5))). But I'm not sure if this is the best approach. I would need some guidance because I cannot find any material discussing the best way to create a proper navigation with SpriteKit. Do you have an updated article, tutorial, or reference that I can follow to learn about the best way to implement navigation in a SpriteKit game? What I'm doing right now is working, but I have limitations, for example, if I want to mix SwiftUI views and SpriteKit scenes. I want to add a Credits scene with some text and images that I want to do in SwiftUI and a Statistic scene with some cool graphics to show the players, but I don't know if I can navigate from an SKScene into a View, or if I need a completely different approach. Can I add UI components directly in a SpriteKit scene instead of using a different navigation system and full SwiftUI views? I really appreciate any help you can provide. As you can see, I'm a little bit lost 😅 Thanks a lot in advance 🙏
0
1
290
Aug ’24
How do I set the *static* position of a `SKSpriteNode` so that it tilts toward the `UIBezierPath` as if it were following this Path?
How do I set the static position of a SKSpriteNode so that it tilts toward the UIBezierPath as if it were following this Path? When I first start my App, these Nodes are all aligned in a straight line When I call: var trainAction = SKAction.follow(trainPath.cgPath, asOffset: false, orientToPath: true, speed: thisSpeed) for moving the train, the train + each car will orient its tilt to hug the trainPath. But I want the identical tilt to hug the trainPath for its initial static presentation. How do I do that?
0
0
371
Aug ’24
SpriteKit PPI
Hi, I’m looking for a way to keep some custom buttons in SpriteKit the same physical size (inches) accross iOS devices (or only slightly vary their size so they’re not humongous on large screens). How do I get PPI in Swift? (cannot be library code which doesn’t compile in Swift Playgrounds). I will use PPI for determining total screen size which I will use to determine how to adjust the button sizes while also respecting some physical desirable dimensions for the buttons. I'm only asking for handheld (same distance from eyes to screen) use, so I don't care about Apple TV (longer distance).
2
0
601
Jul ’24
Apply sprite scene as material in Reality Composer pro
Hello, I’m trying to move my app into vision OS, my app is used for pilot to study the airplane system, is a 3d airplane cockpit build with scene kit and I use sprite scene to animate the cockpit instruments . Scenekit allow to apply as material a sprite scene , so I could animate easy all the different instruments and indication there, but I can’t find this option on reality compose pro , is this possible? any suggestions I can look into to animate and simulate instruments.
2
0
516
Jul ’24
Action Will Not Run The Second Time Method is called
In my method moveSun() it successfully rotates and plays the sound the first time it is called. However, subsequent calls to the method only play the sound and do not execute the rotate action. Does anyone know what may be causing this? Here's the relevant code: func moveSun() { print(sunMoving) let rotateAction = SKAction.rotate(toAngle: 2 * CGFloat.pi, duration: 2) let playGearSound = SKAction.playSoundFileNamed("spinningGear", waitForCompletion: true) let rotateAndPlayGearSound = SKAction.group([rotateAction, playGearSound]) sun.run(rotateAndPlayGearSound, completion: { self.sunMoving = false; print("completed completion handler") }) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchDown(atPoint: t.location(in: self)) } } func touchDown(atPoint pos : CGPoint) { let touchedNodes = nodes(at: pos) for touchedNode in touchedNodes { print("touchNode: \(String(describing: touchedNode.name))") if touchedNode.name == "sun" && !sunMoving { sunMoving = true moveSun() } } }
1
0
443
Jun ’24
How to use CFMessagePort in a Sandbox App when App Group naming convention is not possible?
I am working on an App and I am in the process of adding Syphon support. Syphon uses CFMessagePort for IPC and passing of FrameBuffer data (MTLTexture) between apps - and is widely used in the professional video app and video production space. What I have noticed is that when the App is built as a Sandbox app, during the Syphon initialization, I see the following error message in the log: *** CFMessagePort: bootstrap_register(): failed 1100 (0x44c) 'Permission denied', port = 0x8703, name = 'info.v002.Syphon.D2499DBD-93AE-4CEA-B21F-FF356DCC069D' See /usr/include/servers/bootstrap_defs.h for the error codes. Syphon uses the "info.v002.Syphon.UUID" naming convention to identify IPC Syphon servers, so I don't think I can use the App Groups naming convention for Sandbox support. I have a very simple example app on github that publishes SpriteKit frames as a Syphon Server. To see the issue, simply enable App Sandbox for the build, and run the app. You should see the error message in the log and no data appears in any Syphon Client (I use Syphon Recorder for testing - available at syphon.github . io I am looking for other options to enable CFMessagePorts on a Sandbox App.
6
0
825
May ’24
Apple activity ring(sparkle)
Hello everyone My goal is to create Apple's activity ring sparkle effect. So I found Paul Hudson's Vortex library. There is already a sparkle effect, but I don't know how to modify it to achieve my goal. Because I'm pretty new to SwiftUI animations. Does anyone have any idea how I could do this? Vortex project: https://github.com/twostraws/Vortex
2
0
586
May ’24
spritekit Scene in swiftui
I'm trying to add a SpriteKit scene to my view using SpriteView(scene: spriteScene). But it's doesn't work the .sks scene doesn't display here is the image. (and this is the code :) import SwiftUI import _SpriteKit_SwiftUI struct Gameplay: View { let spriteScene: MainGameScene var body: some View { ZStack { ----------------------- SpriteView(scene: spriteScene) ---------------------------- } } }
0
0
406
May ’24
SKNode calculateAccumulatedFrame() returns wrong frame
I'm writing a SpriteKit game in Swift that does this familiar dance in my GameScene touchesEnded(...)... let touch = touches.first!.location(in: self) let nodes = self.nodes(at: touch) ...but sometimes when the game is running, the nodes collection is empty, even though there are clearly, visibly nodes under the touch. All of the nodes I care about are children of a single SKNode, MapNode, that is one of two children of the GameScene. After a bunch of debugging, I've noticed that when this problem happens, something is causing calculateAccumulatedFrame() to return a frame that is way, way smaller than the real bounds of MapNode. When the scene begins, calculateAccumulatedFrame() is perfect, but something that happens later on breaks it. I've tried adding a node to MapNode that is the correct size to 'force' calculateAccumulatedFrame to do the right thing, but this doesn't work. Is there something obvious I am doing wrong, or some common pitfalls? Is there some way to force calculateAccumulatedFrame to return this correct size?
1
0
524
May ’24