SpriteKit

RSS for tag

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

Posts under SpriteKit tag

200 Posts

Post

Replies

Boosts

Views

Activity

[plugin] AddInstanceForFactory: No factory registered for id <CFUUID 0x60000276b020> F8BB1C28-BAE8-11D6-9C31-00039315CD46
Can anyone help me with the following output which is related to playing sounds/music in a SpriteKit game I'm working on? [plugin] AddInstanceForFactory: No factory registered for id <CFUUID 0x60000276b020> F8BB1C28-BAE8-11D6-9C31-00039315CD46 I'm new to SpriteKit and I've searched the web for answers and found quite a few post concerning the warning (I wouldn't call it an error because the game and sound/music output works perfectly), but no definitive answers on fixing it. I get the warning regardless of how I play the music, adding SKAudioNode to the scene, creating an AVAudioPlayer, etcetera. I suppose I could just ignore the warning as it doesn't seem to impact my game, but I just hate not understanding warnings in the Xcode output window. I'm also getting the below in the output window which I believe is related. AudioObjectGetPropertyData: no object with given ID 0 throwing -10878
0
0
1.7k
Sep ’22
I tagged some Sprite Atlas to On Demand Resources' Tags and not loading in TestFlight
My game's new version used On Demand Resources with Sprite Atlas. Everything work fine in Simulator until I submitted a version to AppStoreConnect and install through TestFlight. All Sprite Atlas' assets only show "X" inside my game. Is it TestFlight's bug? Can I still submit for Review and will it working fine in App Store version?
1
0
1.8k
Sep ’22
Future of Spritekit?
Hi,I coming from another engine, which is Cocos Creator, and would like to know, if SpriteKit is worth learning along with Swift. I've already started working on a Game using Xcode 9.2, and Swift, and looking at some tutorials along the way. But, I'm really somewhat worried about the direction if any SpriteKit will take. I've some posts in the community, concerning the lack of support from Apple towards this framework, instability, etc........So, my main question to Apple moderators, is, does SpriteKit have a future in the Apple Ecosystem, or should I just stick with another engine. One of the main reasons for me to switching from my other engine, is that, I really like ARKit, and the potential it has to be the next frontier in game making, but I wouldn't like to waste my time in a framework that could be not supported in the near future.....Would really appreciate any thoughts and info regarding this.......Thanks for the time and God Bless....Sincerely,Sunday
7
1
7.6k
Aug ’22
Scalable event handling in SpriteKit game
I am in the process of building a fairly complex game in SpriteKit. Per Apple's documentation (see https://developer.apple.com/documentation/spritekit/sknode/controlling_user_interaction_on_nodes) there are two main ways of handling events in a SpriteKit game. One is to handle all user interaction from a single node, the main SKScene in my case. I attach gesture recognizers in the SKScene.didMove(to:) method and test for which nodes were interacted with, then trigger the appropriate event based on the node. This is the technique I am currently using because it seems to be what everyone recommends, based on online research. The second approach involves attaching gesture recognizers on a node-by-node basis. I am quickly running into a scale problem of handling all the events at the SKScene level (the first approach). Currently I am checking which nodes were touched using the name of the node, then triggering the appropriate event based on the touched node. This worked fine when I had around a dozen different nodes the user could interact with, but it is quickly getting out of control as I build out my game and add dozens and dozens of different nodes that are capable of being interacted with. This technique does not seem scalable at all. I would like to start exploring attaching gesture recognizers to the individual nodes, but I cannot find a single example anywhere online of this technique. I have also purchased and read a book on SpriteKit, which only describes the former technique. Can anyone point me in the right direction, provide some code examples, or tell me where I might find information about how to better scale out a SpriteKit game, specifically in terms of event handling?
0
0
736
Aug ’22
Displaying alerts shows compiler warnings
I'm pretty new to Swift and I'm having some trouble implementing alerts into my SpriteKit game. Well, it works however it keeps giving warnings: 2022-06-03 02:04:04.465264+0100 Project14[57880:10648157] [LayoutConstraints] Changing the translatesAutoresizingMaskIntoConstraints property of a UICollectionViewCell that is managed by a UICollectionView is not supported, and will result in incorrect self-sizing. View: <_UIAlertControllerTextFieldViewCollectionCell: 0x13ed18d70; frame = (0 24; 270 24); gestureRecognizers = <NSArray: 0x6000009c81b0>; layer = <CALayer: 0x600000713600>> 2022-06-03 02:06:16.239075+0100 Project14[57880:10648157] [HardwareKeyboard] -[UIApplication getKeyboardDevicePropertiesForSenderID:shouldUpdate:usingSyntheticEvent:], failed to fetch device property for senderID (778835616971358211) use primary keyboard info instead. How do I get rid of this warnings? Thanks. let alert = UIAlertController(title: "title", message: "message", preferredStyle: UIAlertController.Style.alert) alert.addTextField { field in field.placeholder = "Input your name" field.isSecureTextEntry = false field.textAlignment = .left } alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in print("ok") }) alert.addAction(UIAlertAction(title: "Cancel", style: .default) { _ in print("cancel") }) view?.window?.rootViewController?.present(alert, animated: true) } I cannot use just present(alert, animated: true). In this case I get compiler error - "Value of type 'SceneMenu' has no member 'present'"
7
1
3.7k
Aug ’22
SpriteKit Game
OK I'm trying to make a sprite(model.Emmiter) that shoots balls(EnergyBalls) and the balls wont emit at the touch location: import SpriteKit import GameplayKit class Sprites {     var Emmiter: SKSpriteNode = .init(imageNamed: "Emmiter") } class GameScene: SKScene {     var model: Sprites = .init()     var Emmiter = Sprites().Emmiter     var playableRect: CGRect = .zer     var lastTouch: CGPoint = .zero     override func didMove(to view: SKView) {        Emmiter.position = CGPoint(x: size.width / 2, y: size.width/* view.frame.minY + 100 */)         print(Emmiter.position)         self.addChild(Emmiter)     }               func touchDown(atPoint pos : CGPoint) {         lastTouch = pos         let rotation = -atan2(             lastTouch.x - Emmiter.position.x,             lastTouch.y - Emmiter.position.y         )         Emmiter.run(             .rotate(                 toAngle: rotation,                 duration: 0.25             )         )         fireEnergyBall(atPoint: lastTouch)     }          func touchMoved(toPoint pos : CGPoint) {     }          func touchUp(atPoint pos : CGPoint) {     }          func fireEnergyBall(atPoint location: CGPoint) {         let EnergyBall = SKSpriteNode(imageNamed: "Energy")         EnergyBall.position = Emmiter.position         print(EnergyBall.position)                  let fly: SKAction = .run {             EnergyBall.run(.move(to: location, duration: 1))             DispatchQueue.main.asyncAfter(deadline: .now() + 1) {                     EnergyBall.un(.sequence([.scale(to: 0, duration: 0.125), .removeFromParent()]))                 }         }         EnergyBall.run(fly)         self.addChild(EnergyBall)     }     override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {         let rotation = -atan2(             touches.first!.location(                 in: self             ).x - Emmiter.position.x,             touches.first!.location(                 in: self             ).y - Emmiter.position.y         )         Emmiter.run(             .rotate(                 toAngle: rotation,                 duration: 0.25             )         )         fireEnergyBall(atPoint: touches.first!.location(in: self.view))     }          override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {     }          override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {     }          override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {     }               override func update(_ currentTime: TimeInterval) {              } }
2
0
1k
Aug ’22
Speech Recognition 'recognitionTask' Function Not Executing
I'm building a game where the player is able to speak commands, so I want to enable speech-to-text capability. I've setup the required info.plist property (for speech recognition privacy) as well as the App Sandbox hardware setting (for audio input). I've confirmed that the application is listening via the audio tap and sending audio buffers to the recognition request. However, the recognition task never executes. NOTE: This is for MacOS, NOT iOS. Also, it works when I have this in a Playground, but when I try to do this in an actual application, the recognition task isn't called. Specs: MacOS: 12.1 XCode: 13.2.1 (13C100) Swift: 5.5.2 Here is the code that I've placed in the AppDelegate of a freshly built SpriteKit application: // // AppDelegate.swift // import Cocoa import AVFoundation import Speech @main class AppDelegate: NSObject, NSApplicationDelegate {   private let speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))!   private let audioEngine = AVAudioEngine()   private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?   private var recognitionTask: SFSpeechRecognitionTask?   func applicationDidFinishLaunching(_ aNotification: Notification) {     SFSpeechRecognizer.requestAuthorization(requestMicrophoneAccess)   }   func applicationWillTerminate(_ aNotification: Notification) {     // Insert code here to tear down your application   }   func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {     return true   }   fileprivate func requestMicrophoneAccess(authStatus: SFSpeechRecognizerAuthorizationStatus) {     OperationQueue.main.addOperation {       switch authStatus {       case .authorized:           self.speechRecognizer.supportsOnDeviceRecognition = true           if let speechRecognizer = SFSpeechRecognizer() {             if speechRecognizer.isAvailable {               do {                 try self.startListening()               } catch {                 print(">>> ERROR >>> Listening Error: \(error)")               }             }           }       case .denied:           print("Denied")                 case .restricted:           print("Restricted")                 case .notDetermined:           print("Undetermined")                 default:           print("Unknown")       }     }   }   func startListening() throws {     // Cancel the previous task if it's running.     recognitionTask?.cancel()     recognitionTask = nil           let inputNode = audioEngine.inputNode     // Configure the microphone input.     let recordingFormat = inputNode.outputFormat(forBus: 0)     inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) {(buffer: AVAudioPCMBuffer, when: AVAudioTime) in /********** * Confirmed that the following line is executing continuously **********/       self.recognitionRequest?.append(buffer)     }     startRecognizing()     audioEngine.prepare()     try audioEngine.start()   }   func startRecognizing() {     // Create a recognition task for the speech recognition session.     recognitionRequest = SFSpeechAudioBufferRecognitionRequest()     guard let recognitionRequestInternal = recognitionRequest else { fatalError("Unable to create a SFSpeechAudioBufferRecognitionRequest object") }     recognitionRequestInternal.shouldReportPartialResults = true     recognitionRequestInternal.requiresOnDeviceRecognition = true /************** * Confirmed that the following line is executed, * however the function given to 'recognitionTask' is never called **************/     recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequestInternal) { result, error in       var isFinal = false               if result != nil {         let firstTranscriptionTimestamp = result!.transcriptions.first?.segments.first?.timestamp ?? TimeInterval.zero         isFinal = result!.isFinal || (firstTranscriptionTimestamp != 0)       }               if error != nil {         // Stop recognizing speech if there is a problem.         print("\n>>> ERROR >>> Recognition Error: \(error)")         self.audioEngine.stop()         self.audioEngine.inputNode.removeTap(onBus: 0)         self.recognitionRequest = nil         self.recognitionTask = nil       } else if isFinal {         self.recognitionTask = nil       }     }   } }
2
0
1.6k
Aug ’22
How to Unit/UI test a game?
Hi there, Could anyone please provide some clues on how to do a Unit/UI test to a game, for me, a beginner in app/game development? I am making a little game, and basically I’ve done coding for the gameplay. My game is rather simple. Basically it just switches between different “GKState”. When entering each state, I give nodes of actors some actions, and when leaving each state, the actions are removed. The nodes are either “SKNode” or “SKSpriteNode” and are wrapped in “GKComponent”. In some states, I give nodes “GKBehavior”. I’ve been thinking how to test. For Unit test, I learned that it’s for the app’s logic. But my (perhaps naive) understanding is that I can prove the logic is all correct because I play the game and it runs well. I accept the point that we should test it numerically not just visually. But, for example, for the “presentScene” method of “SKView”, should I make some dummy scene and, when entering the dummy scene, should I make some dummy nodes with giving the dummy nodes some actions? Perhaps I can do these, but what’s the meaning? For the UI test, I found all I can retrieve from a UI is the images. But for a game, since actors have different positions and speed and images every time I run the game. So it looks for me that it’s not very possible to do UI test for a game, either via the “UI recording” or programmatically. I also think my playing is a test. So far, for Unit test, I just measure the time of loading my resources. For UI test, I just tested a button in my game. Thanks a lot for any clues!
1
0
2.1k
Aug ’22
Unable to load custom class 'GameScene' from module '(null)'
For some reason Xcode has started showing this message over the last couple days. Even loading a new SpriteKit project and running it unmodified gets the error. The scene loads, but is unresponsive. I've also tried modifying the program by removing the default scene and creating a new one; new SKS file has the same issue. Existing projects still compile and load properly, however. Considering the default template isn't working out of the box anymore, is this an Xcode update gone wrong, or is there something that can be done to force it to realize the class does, in fact, exist? Thanks!
7
0
2.7k
Aug ’22
Adding gradient background to SKScene
Hi.I am trying to add background with gradient color to my SKScene:class GameScene: SKScene { override func didMove(to view: SKView) { let gradientView = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)) let image = UIImage.gradientBackgroundImage(bounds: CGRect(x: 0, y: 0, width: frame.width, height: frame.height), colors: [UIColor.yellow.cgColor, UIColor.blue.cgColor]) let background = SKSpriteNode(color: UIColor(patternImage: image), size: frame.size) addChild(background) } } extension UIImage { /** http://www.riptutorial.com/ios/example/14328/gradient-image-with-colors */ static func gradientBackgroundImage(bounds: CGRect, colors: [CGColor]) -&gt; UIImage { let gradientLayer = CAGradientLayer() gradientLayer.frame = bounds gradientLayer.colors = colors UIGraphicsBeginImageContext(gradientLayer.bounds.size) gradientLayer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } }This is not working. Is there a better way to add gradient background to the SKScene?Thanks a lot!EDIT:If I do this in didMove(to view:):self.view?.backgroundColor = UIColor.blue let backgroundDep = IGABackgroundLayer().gradientMetar() // My method to create CAGradientLayer backgroundDep.frame = self.view!.bounds self.view!.layer.insertSublayer(backgroundDep, at: 0)...background is created nicely but added SKNodes are not seen on top of it.
5
0
4.6k
Jul ’22
SpriteKit objects not colliding
I am new to SpriteKit, and I am trying to make a simple game. however, when trying to integrate gravity, the player foes not hit the floor, but instead falls behind (despite having the same zPosition). I would like to know what I need to have the floor and player collide. I have currently set the collisionBitMask and categoryBitMask, have them on the same zPosition, and have gravity turned off of the floor, but enabled on the player. is there anything else that needs to be done?
0
0
622
Jun ’22
UITextField not showing when added as subview
Hi. I'm pretty new to Swift and I'm having some trouble displaying UITextField in SpriteKit. Init() in SceneMenu will not display the UITextField, while using function showTextField() with touchesBegan() works. How can I display UITextField without the user clicking the button Show TextField? GameViewController.swift: class GameViewController: UIViewController {       override func viewDidLoad() {           let scene = SceneMenu(size: view.frame.size)     scene.scaleMode = .aspectFill     scene.backgroundColor = .white           let view = view as! SKView     view.presentScene(scene)         }     } SceneMenu.swift: class SceneMenu: SKScene {       override init(size: CGSize) {           super.init(size: size)           let btnAlert = SKLabelNode(text: "Show TextField")     btnAlert.name = "btn_text"     btnAlert.fontSize = 20     btnAlert.fontColor = SKColor.blue     btnAlert.fontName = "Avenir"     btnAlert.position = CGPoint(x: size.width / 2, y: size.height / 2)     addChild(btnAlert) let textFieldFrame = CGRect(origin: CGPoint(x: 100, y: 300), size: CGSize(width: 200, height: 30))     let textField = UITextField(frame: textFieldFrame)     textField.backgroundColor = SKColor.blue     textField.placeholder = "Type name"         view?.addSubview(textField)         }       required init?(coder aDecoder: NSCoder) {           fatalError("init(coder:) has not been implemented")         }       func showTextField() {           let textFieldFrame = CGRect(origin: CGPoint(x: 100, y: 100), size: CGSize(width: 200, height: 30))     let textField = UITextField(frame: textFieldFrame)     textField.backgroundColor = SKColor.blue     textField.placeholder = "Type name"         view?.addSubview(textField)         }       override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {           if let touch = touches.first {               let location = touch.location(in: self)       let action = atPoint(location)               if action.name == "btn_text" {                   showTextField()                 }             }         }     }
2
0
2.2k
Jun ’22
How to turn AR SpriteKit App into AR SceneKit App
Hello! I am new to ARKit and currently working on this sample SpriteKit AR application from Apple. To use ARKits debug option of visualizing the feature points I am trying to change the app from an AR SpriteKit base to an AR SceneKit base. (I thought it should be possible after watching this Apple session.) Therefore I made some changes. But unfortunately, the application doesn't show the camera input anymore and throws an exception after some time. The object detector still correctly identifies objects but the main screen stays gray. Help would be much appreciated! Best regards! Main changes: @IBOutlet weak var sceneView: ARSCNView! // @IBOutlet weak var sceneView: ARSKView! class ViewController: ARSCNViewDelegate {} // class ViewController: ARSKViewDelegate {} Put the SpriteKit overlayScene into a SCNPlane. Had to change how child nodes get hidden when relocalization happens.
1
1
818
Jun ’22
Using the Rec. 2020 color gamut in SpriteKit
About a month ago I asked whether I could use HDR in SpriteKit. This wasn't a well-phrased question since HDR seems to mean different things in different questions, which probably led to my question going unanswered. What I meant to ask was whether it's possible to use assets that have a color gamut that many modern devices are capable of displaying (XDR is somewhat standard among mid- to high-end devices). In other words: Is SpriteKit keeping up with the hardware? If not, what framework options do I have that can quickly display large Rec. 2020 images? Do any of the Core frameworks offer this capability?
1
0
1.3k
May ’22
SKPhysicsContactDelegate not works
I wanna add a score when the character contacts with the 'coins' and game over when it contacts with the 'enemies'. But it doesn't work. I compiled the ...Category and &lt;SKPhysicsContactDelegate&gt; code in GameScene.h and these:- (instancetype)initWithSize:(CGSize)size { if (self = [super initWithSize:size]) { self.character = [SKSpriteNode spriteNodeWithImageNamed:@"character"]; self.character.position = CGPointMake(100, 100); [self addChild:self.character]; self.physicsWorld.gravity = CGVectorMake(0,0); self.physicsWorld.contactDelegate = self; } return self; }in .m above didMoveToView method. Can I use initWithSize in Xcode 8? And I do use these code in .m:character.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:character.size]; //1 character.physicsBody.dynamic = YES; //2 character.physicsBody.categoryBitMask = characterCategory; //3 character.physicsBody.contactTestBitMask = coinCategory | enemiesCategory;//4 character.physicsBody.collisionBitMask = 0; // 5I use them in "setPhysicsBody:(SKPhysicsBody *)physicsBody" method. And of couse I compiled the didBeginContact method. Did I miss anything? Please help me. Thank you very much.
10
0
2.7k
May ’22
animating all nodes
I'm trying to develop a system with skspritenode spawn and then they follow the player but when ever skspritenode spawn the original action stops so it ends up with only one following the node instead of all of them.
0
0
612
May ’22
Does Apple allow execution of Lua scripts inside an iOS game or app?
I am aware that this question has been asked before, but the answer seems to have changed over the years, and other answers online are still not clear to me. Currently (May 2022), it seems like Apple will allow Lua scripts to be run from inside an iOS app, but I am hoping someone can provide a definitive answer. I am planning on building a Lua scripting engine into my iOS game engine to allow AI designers to control the game's AI. The game engine is written in Swift and SpriteKit and targets iOS on iPhone and iPad. I am including the Lua scripts bundled with my application bundle, which are interpreted at runtime by a Lua interpreter that I am also including inside the application bundle. I believe section 3.3.2 of the Apple Developer Program License Agreement is the pertinent section, and it sounds like using Lua scripts that are interpreted at runtime by an iOS app is fine. If anyone can offer any further confirmation or guidance to my interpretation, it would be much appreciated. My Lua scripts are directly related to the primary purpose of my app (AI scripts for a game). I posted this question on StackOverflow, but it was closed because I was told the question seeks legal advice rather than technical advice, so if that will be true here as well, can anyone tell me where I should go to ask this question?
0
1
1.9k
May ’22
SKAudioNode in iOS9 and volume
I'm trying to use the new SKAudioNode in iOS9. I get the sound to play, but can't seemt to access the nodes volume?
Replies
4
Boosts
0
Views
3.6k
Activity
Sep ’22
[plugin] AddInstanceForFactory: No factory registered for id <CFUUID 0x60000276b020> F8BB1C28-BAE8-11D6-9C31-00039315CD46
Can anyone help me with the following output which is related to playing sounds/music in a SpriteKit game I'm working on? [plugin] AddInstanceForFactory: No factory registered for id <CFUUID 0x60000276b020> F8BB1C28-BAE8-11D6-9C31-00039315CD46 I'm new to SpriteKit and I've searched the web for answers and found quite a few post concerning the warning (I wouldn't call it an error because the game and sound/music output works perfectly), but no definitive answers on fixing it. I get the warning regardless of how I play the music, adding SKAudioNode to the scene, creating an AVAudioPlayer, etcetera. I suppose I could just ignore the warning as it doesn't seem to impact my game, but I just hate not understanding warnings in the Xcode output window. I'm also getting the below in the output window which I believe is related. AudioObjectGetPropertyData: no object with given ID 0 throwing -10878
Replies
0
Boosts
0
Views
1.7k
Activity
Sep ’22
I tagged some Sprite Atlas to On Demand Resources' Tags and not loading in TestFlight
My game's new version used On Demand Resources with Sprite Atlas. Everything work fine in Simulator until I submitted a version to AppStoreConnect and install through TestFlight. All Sprite Atlas' assets only show "X" inside my game. Is it TestFlight's bug? Can I still submit for Review and will it working fine in App Store version?
Replies
1
Boosts
0
Views
1.8k
Activity
Sep ’22
Future of Spritekit?
Hi,I coming from another engine, which is Cocos Creator, and would like to know, if SpriteKit is worth learning along with Swift. I've already started working on a Game using Xcode 9.2, and Swift, and looking at some tutorials along the way. But, I'm really somewhat worried about the direction if any SpriteKit will take. I've some posts in the community, concerning the lack of support from Apple towards this framework, instability, etc........So, my main question to Apple moderators, is, does SpriteKit have a future in the Apple Ecosystem, or should I just stick with another engine. One of the main reasons for me to switching from my other engine, is that, I really like ARKit, and the potential it has to be the next frontier in game making, but I wouldn't like to waste my time in a framework that could be not supported in the near future.....Would really appreciate any thoughts and info regarding this.......Thanks for the time and God Bless....Sincerely,Sunday
Replies
7
Boosts
1
Views
7.6k
Activity
Aug ’22
Scalable event handling in SpriteKit game
I am in the process of building a fairly complex game in SpriteKit. Per Apple's documentation (see https://developer.apple.com/documentation/spritekit/sknode/controlling_user_interaction_on_nodes) there are two main ways of handling events in a SpriteKit game. One is to handle all user interaction from a single node, the main SKScene in my case. I attach gesture recognizers in the SKScene.didMove(to:) method and test for which nodes were interacted with, then trigger the appropriate event based on the node. This is the technique I am currently using because it seems to be what everyone recommends, based on online research. The second approach involves attaching gesture recognizers on a node-by-node basis. I am quickly running into a scale problem of handling all the events at the SKScene level (the first approach). Currently I am checking which nodes were touched using the name of the node, then triggering the appropriate event based on the touched node. This worked fine when I had around a dozen different nodes the user could interact with, but it is quickly getting out of control as I build out my game and add dozens and dozens of different nodes that are capable of being interacted with. This technique does not seem scalable at all. I would like to start exploring attaching gesture recognizers to the individual nodes, but I cannot find a single example anywhere online of this technique. I have also purchased and read a book on SpriteKit, which only describes the former technique. Can anyone point me in the right direction, provide some code examples, or tell me where I might find information about how to better scale out a SpriteKit game, specifically in terms of event handling?
Replies
0
Boosts
0
Views
736
Activity
Aug ’22
Displaying alerts shows compiler warnings
I'm pretty new to Swift and I'm having some trouble implementing alerts into my SpriteKit game. Well, it works however it keeps giving warnings: 2022-06-03 02:04:04.465264+0100 Project14[57880:10648157] [LayoutConstraints] Changing the translatesAutoresizingMaskIntoConstraints property of a UICollectionViewCell that is managed by a UICollectionView is not supported, and will result in incorrect self-sizing. View: <_UIAlertControllerTextFieldViewCollectionCell: 0x13ed18d70; frame = (0 24; 270 24); gestureRecognizers = <NSArray: 0x6000009c81b0>; layer = <CALayer: 0x600000713600>> 2022-06-03 02:06:16.239075+0100 Project14[57880:10648157] [HardwareKeyboard] -[UIApplication getKeyboardDevicePropertiesForSenderID:shouldUpdate:usingSyntheticEvent:], failed to fetch device property for senderID (778835616971358211) use primary keyboard info instead. How do I get rid of this warnings? Thanks. let alert = UIAlertController(title: "title", message: "message", preferredStyle: UIAlertController.Style.alert) alert.addTextField { field in field.placeholder = "Input your name" field.isSecureTextEntry = false field.textAlignment = .left } alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in print("ok") }) alert.addAction(UIAlertAction(title: "Cancel", style: .default) { _ in print("cancel") }) view?.window?.rootViewController?.present(alert, animated: true) } I cannot use just present(alert, animated: true). In this case I get compiler error - "Value of type 'SceneMenu' has no member 'present'"
Replies
7
Boosts
1
Views
3.7k
Activity
Aug ’22
How to make SKSpriteNode (with png texture) be touchable only on pixels and not on alpha?
Hi, could anyone help to solve this: have couple of sprites with pngs, and needed to make them react only when sprite touched at its part with some data, and ignore alpha.
Replies
1
Boosts
0
Views
818
Activity
Aug ’22
SpriteKit Game
OK I'm trying to make a sprite(model.Emmiter) that shoots balls(EnergyBalls) and the balls wont emit at the touch location: import SpriteKit import GameplayKit class Sprites {     var Emmiter: SKSpriteNode = .init(imageNamed: "Emmiter") } class GameScene: SKScene {     var model: Sprites = .init()     var Emmiter = Sprites().Emmiter     var playableRect: CGRect = .zer     var lastTouch: CGPoint = .zero     override func didMove(to view: SKView) {        Emmiter.position = CGPoint(x: size.width / 2, y: size.width/* view.frame.minY + 100 */)         print(Emmiter.position)         self.addChild(Emmiter)     }               func touchDown(atPoint pos : CGPoint) {         lastTouch = pos         let rotation = -atan2(             lastTouch.x - Emmiter.position.x,             lastTouch.y - Emmiter.position.y         )         Emmiter.run(             .rotate(                 toAngle: rotation,                 duration: 0.25             )         )         fireEnergyBall(atPoint: lastTouch)     }          func touchMoved(toPoint pos : CGPoint) {     }          func touchUp(atPoint pos : CGPoint) {     }          func fireEnergyBall(atPoint location: CGPoint) {         let EnergyBall = SKSpriteNode(imageNamed: "Energy")         EnergyBall.position = Emmiter.position         print(EnergyBall.position)                  let fly: SKAction = .run {             EnergyBall.run(.move(to: location, duration: 1))             DispatchQueue.main.asyncAfter(deadline: .now() + 1) {                     EnergyBall.un(.sequence([.scale(to: 0, duration: 0.125), .removeFromParent()]))                 }         }         EnergyBall.run(fly)         self.addChild(EnergyBall)     }     override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {         let rotation = -atan2(             touches.first!.location(                 in: self             ).x - Emmiter.position.x,             touches.first!.location(                 in: self             ).y - Emmiter.position.y         )         Emmiter.run(             .rotate(                 toAngle: rotation,                 duration: 0.25             )         )         fireEnergyBall(atPoint: touches.first!.location(in: self.view))     }          override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {     }          override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {     }          override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {     }               override func update(_ currentTime: TimeInterval) {              } }
Replies
2
Boosts
0
Views
1k
Activity
Aug ’22
Speech Recognition 'recognitionTask' Function Not Executing
I'm building a game where the player is able to speak commands, so I want to enable speech-to-text capability. I've setup the required info.plist property (for speech recognition privacy) as well as the App Sandbox hardware setting (for audio input). I've confirmed that the application is listening via the audio tap and sending audio buffers to the recognition request. However, the recognition task never executes. NOTE: This is for MacOS, NOT iOS. Also, it works when I have this in a Playground, but when I try to do this in an actual application, the recognition task isn't called. Specs: MacOS: 12.1 XCode: 13.2.1 (13C100) Swift: 5.5.2 Here is the code that I've placed in the AppDelegate of a freshly built SpriteKit application: // // AppDelegate.swift // import Cocoa import AVFoundation import Speech @main class AppDelegate: NSObject, NSApplicationDelegate {   private let speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))!   private let audioEngine = AVAudioEngine()   private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?   private var recognitionTask: SFSpeechRecognitionTask?   func applicationDidFinishLaunching(_ aNotification: Notification) {     SFSpeechRecognizer.requestAuthorization(requestMicrophoneAccess)   }   func applicationWillTerminate(_ aNotification: Notification) {     // Insert code here to tear down your application   }   func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {     return true   }   fileprivate func requestMicrophoneAccess(authStatus: SFSpeechRecognizerAuthorizationStatus) {     OperationQueue.main.addOperation {       switch authStatus {       case .authorized:           self.speechRecognizer.supportsOnDeviceRecognition = true           if let speechRecognizer = SFSpeechRecognizer() {             if speechRecognizer.isAvailable {               do {                 try self.startListening()               } catch {                 print(">>> ERROR >>> Listening Error: \(error)")               }             }           }       case .denied:           print("Denied")                 case .restricted:           print("Restricted")                 case .notDetermined:           print("Undetermined")                 default:           print("Unknown")       }     }   }   func startListening() throws {     // Cancel the previous task if it's running.     recognitionTask?.cancel()     recognitionTask = nil           let inputNode = audioEngine.inputNode     // Configure the microphone input.     let recordingFormat = inputNode.outputFormat(forBus: 0)     inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) {(buffer: AVAudioPCMBuffer, when: AVAudioTime) in /********** * Confirmed that the following line is executing continuously **********/       self.recognitionRequest?.append(buffer)     }     startRecognizing()     audioEngine.prepare()     try audioEngine.start()   }   func startRecognizing() {     // Create a recognition task for the speech recognition session.     recognitionRequest = SFSpeechAudioBufferRecognitionRequest()     guard let recognitionRequestInternal = recognitionRequest else { fatalError("Unable to create a SFSpeechAudioBufferRecognitionRequest object") }     recognitionRequestInternal.shouldReportPartialResults = true     recognitionRequestInternal.requiresOnDeviceRecognition = true /************** * Confirmed that the following line is executed, * however the function given to 'recognitionTask' is never called **************/     recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequestInternal) { result, error in       var isFinal = false               if result != nil {         let firstTranscriptionTimestamp = result!.transcriptions.first?.segments.first?.timestamp ?? TimeInterval.zero         isFinal = result!.isFinal || (firstTranscriptionTimestamp != 0)       }               if error != nil {         // Stop recognizing speech if there is a problem.         print("\n>>> ERROR >>> Recognition Error: \(error)")         self.audioEngine.stop()         self.audioEngine.inputNode.removeTap(onBus: 0)         self.recognitionRequest = nil         self.recognitionTask = nil       } else if isFinal {         self.recognitionTask = nil       }     }   } }
Replies
2
Boosts
0
Views
1.6k
Activity
Aug ’22
How to Unit/UI test a game?
Hi there, Could anyone please provide some clues on how to do a Unit/UI test to a game, for me, a beginner in app/game development? I am making a little game, and basically I’ve done coding for the gameplay. My game is rather simple. Basically it just switches between different “GKState”. When entering each state, I give nodes of actors some actions, and when leaving each state, the actions are removed. The nodes are either “SKNode” or “SKSpriteNode” and are wrapped in “GKComponent”. In some states, I give nodes “GKBehavior”. I’ve been thinking how to test. For Unit test, I learned that it’s for the app’s logic. But my (perhaps naive) understanding is that I can prove the logic is all correct because I play the game and it runs well. I accept the point that we should test it numerically not just visually. But, for example, for the “presentScene” method of “SKView”, should I make some dummy scene and, when entering the dummy scene, should I make some dummy nodes with giving the dummy nodes some actions? Perhaps I can do these, but what’s the meaning? For the UI test, I found all I can retrieve from a UI is the images. But for a game, since actors have different positions and speed and images every time I run the game. So it looks for me that it’s not very possible to do UI test for a game, either via the “UI recording” or programmatically. I also think my playing is a test. So far, for Unit test, I just measure the time of loading my resources. For UI test, I just tested a button in my game. Thanks a lot for any clues!
Replies
1
Boosts
0
Views
2.1k
Activity
Aug ’22
Unable to load custom class 'GameScene' from module '(null)'
For some reason Xcode has started showing this message over the last couple days. Even loading a new SpriteKit project and running it unmodified gets the error. The scene loads, but is unresponsive. I've also tried modifying the program by removing the default scene and creating a new one; new SKS file has the same issue. Existing projects still compile and load properly, however. Considering the default template isn't working out of the box anymore, is this an Xcode update gone wrong, or is there something that can be done to force it to realize the class does, in fact, exist? Thanks!
Replies
7
Boosts
0
Views
2.7k
Activity
Aug ’22
'cyclone' is not a recognized processor for this target (ignoring processor)
Building and running a SpriteKit game on iPhone simulator starts up and after did move to view, I get this error and app abends with illegal instruction. Xcode beta 5, Big Sur beta 5 Apple Silicon Anyone else seen this?
Replies
12
Boosts
4
Views
6.8k
Activity
Aug ’22
Adding gradient background to SKScene
Hi.I am trying to add background with gradient color to my SKScene:class GameScene: SKScene { override func didMove(to view: SKView) { let gradientView = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)) let image = UIImage.gradientBackgroundImage(bounds: CGRect(x: 0, y: 0, width: frame.width, height: frame.height), colors: [UIColor.yellow.cgColor, UIColor.blue.cgColor]) let background = SKSpriteNode(color: UIColor(patternImage: image), size: frame.size) addChild(background) } } extension UIImage { /** http://www.riptutorial.com/ios/example/14328/gradient-image-with-colors */ static func gradientBackgroundImage(bounds: CGRect, colors: [CGColor]) -&gt; UIImage { let gradientLayer = CAGradientLayer() gradientLayer.frame = bounds gradientLayer.colors = colors UIGraphicsBeginImageContext(gradientLayer.bounds.size) gradientLayer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } }This is not working. Is there a better way to add gradient background to the SKScene?Thanks a lot!EDIT:If I do this in didMove(to view:):self.view?.backgroundColor = UIColor.blue let backgroundDep = IGABackgroundLayer().gradientMetar() // My method to create CAGradientLayer backgroundDep.frame = self.view!.bounds self.view!.layer.insertSublayer(backgroundDep, at: 0)...background is created nicely but added SKNodes are not seen on top of it.
Replies
5
Boosts
0
Views
4.6k
Activity
Jul ’22
SpriteKit objects not colliding
I am new to SpriteKit, and I am trying to make a simple game. however, when trying to integrate gravity, the player foes not hit the floor, but instead falls behind (despite having the same zPosition). I would like to know what I need to have the floor and player collide. I have currently set the collisionBitMask and categoryBitMask, have them on the same zPosition, and have gravity turned off of the floor, but enabled on the player. is there anything else that needs to be done?
Replies
0
Boosts
0
Views
622
Activity
Jun ’22
UITextField not showing when added as subview
Hi. I'm pretty new to Swift and I'm having some trouble displaying UITextField in SpriteKit. Init() in SceneMenu will not display the UITextField, while using function showTextField() with touchesBegan() works. How can I display UITextField without the user clicking the button Show TextField? GameViewController.swift: class GameViewController: UIViewController {       override func viewDidLoad() {           let scene = SceneMenu(size: view.frame.size)     scene.scaleMode = .aspectFill     scene.backgroundColor = .white           let view = view as! SKView     view.presentScene(scene)         }     } SceneMenu.swift: class SceneMenu: SKScene {       override init(size: CGSize) {           super.init(size: size)           let btnAlert = SKLabelNode(text: "Show TextField")     btnAlert.name = "btn_text"     btnAlert.fontSize = 20     btnAlert.fontColor = SKColor.blue     btnAlert.fontName = "Avenir"     btnAlert.position = CGPoint(x: size.width / 2, y: size.height / 2)     addChild(btnAlert) let textFieldFrame = CGRect(origin: CGPoint(x: 100, y: 300), size: CGSize(width: 200, height: 30))     let textField = UITextField(frame: textFieldFrame)     textField.backgroundColor = SKColor.blue     textField.placeholder = "Type name"         view?.addSubview(textField)         }       required init?(coder aDecoder: NSCoder) {           fatalError("init(coder:) has not been implemented")         }       func showTextField() {           let textFieldFrame = CGRect(origin: CGPoint(x: 100, y: 100), size: CGSize(width: 200, height: 30))     let textField = UITextField(frame: textFieldFrame)     textField.backgroundColor = SKColor.blue     textField.placeholder = "Type name"         view?.addSubview(textField)         }       override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {           if let touch = touches.first {               let location = touch.location(in: self)       let action = atPoint(location)               if action.name == "btn_text" {                   showTextField()                 }             }         }     }
Replies
2
Boosts
0
Views
2.2k
Activity
Jun ’22
How to turn AR SpriteKit App into AR SceneKit App
Hello! I am new to ARKit and currently working on this sample SpriteKit AR application from Apple. To use ARKits debug option of visualizing the feature points I am trying to change the app from an AR SpriteKit base to an AR SceneKit base. (I thought it should be possible after watching this Apple session.) Therefore I made some changes. But unfortunately, the application doesn't show the camera input anymore and throws an exception after some time. The object detector still correctly identifies objects but the main screen stays gray. Help would be much appreciated! Best regards! Main changes: @IBOutlet weak var sceneView: ARSCNView! // @IBOutlet weak var sceneView: ARSKView! class ViewController: ARSCNViewDelegate {} // class ViewController: ARSKViewDelegate {} Put the SpriteKit overlayScene into a SCNPlane. Had to change how child nodes get hidden when relocalization happens.
Replies
1
Boosts
1
Views
818
Activity
Jun ’22
Using the Rec. 2020 color gamut in SpriteKit
About a month ago I asked whether I could use HDR in SpriteKit. This wasn't a well-phrased question since HDR seems to mean different things in different questions, which probably led to my question going unanswered. What I meant to ask was whether it's possible to use assets that have a color gamut that many modern devices are capable of displaying (XDR is somewhat standard among mid- to high-end devices). In other words: Is SpriteKit keeping up with the hardware? If not, what framework options do I have that can quickly display large Rec. 2020 images? Do any of the Core frameworks offer this capability?
Replies
1
Boosts
0
Views
1.3k
Activity
May ’22
SKPhysicsContactDelegate not works
I wanna add a score when the character contacts with the 'coins' and game over when it contacts with the 'enemies'. But it doesn't work. I compiled the ...Category and &lt;SKPhysicsContactDelegate&gt; code in GameScene.h and these:- (instancetype)initWithSize:(CGSize)size { if (self = [super initWithSize:size]) { self.character = [SKSpriteNode spriteNodeWithImageNamed:@"character"]; self.character.position = CGPointMake(100, 100); [self addChild:self.character]; self.physicsWorld.gravity = CGVectorMake(0,0); self.physicsWorld.contactDelegate = self; } return self; }in .m above didMoveToView method. Can I use initWithSize in Xcode 8? And I do use these code in .m:character.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:character.size]; //1 character.physicsBody.dynamic = YES; //2 character.physicsBody.categoryBitMask = characterCategory; //3 character.physicsBody.contactTestBitMask = coinCategory | enemiesCategory;//4 character.physicsBody.collisionBitMask = 0; // 5I use them in "setPhysicsBody:(SKPhysicsBody *)physicsBody" method. And of couse I compiled the didBeginContact method. Did I miss anything? Please help me. Thank you very much.
Replies
10
Boosts
0
Views
2.7k
Activity
May ’22
animating all nodes
I'm trying to develop a system with skspritenode spawn and then they follow the player but when ever skspritenode spawn the original action stops so it ends up with only one following the node instead of all of them.
Replies
0
Boosts
0
Views
612
Activity
May ’22
Does Apple allow execution of Lua scripts inside an iOS game or app?
I am aware that this question has been asked before, but the answer seems to have changed over the years, and other answers online are still not clear to me. Currently (May 2022), it seems like Apple will allow Lua scripts to be run from inside an iOS app, but I am hoping someone can provide a definitive answer. I am planning on building a Lua scripting engine into my iOS game engine to allow AI designers to control the game's AI. The game engine is written in Swift and SpriteKit and targets iOS on iPhone and iPad. I am including the Lua scripts bundled with my application bundle, which are interpreted at runtime by a Lua interpreter that I am also including inside the application bundle. I believe section 3.3.2 of the Apple Developer Program License Agreement is the pertinent section, and it sounds like using Lua scripts that are interpreted at runtime by an iOS app is fine. If anyone can offer any further confirmation or guidance to my interpretation, it would be much appreciated. My Lua scripts are directly related to the primary purpose of my app (AI scripts for a game). I posted this question on StackOverflow, but it was closed because I was told the question seeks legal advice rather than technical advice, so if that will be true here as well, can anyone tell me where I should go to ask this question?
Replies
0
Boosts
1
Views
1.9k
Activity
May ’22