SpriteKit

RSS for tag

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

SpriteKit Documentation

Posts under SpriteKit tag

101 Posts
Sort by:
Post not yet marked as solved
0 Replies
118 Views
// // ContentView.swift // TestSprite1 // // Created by Alireza | Datance on 4/14/22. // import SwiftUI import SpriteKit class GameScene: SKScene {   override func didMove(to view: SKView) {     physicsBody = SKPhysicsBody(edgeLoopFrom: frame)   }   override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {      //with this we would only process single touch     // good question how to process multi touch      guard let touch = touches.first else { return }           let location = touch.location(in: self)     let box = SKSpriteNode(color: SKColor.red, size: CGSize(width: 50, height: 50))     box.position = location     box.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 50, height: 50))     addChild(box)                 } } struct ContentView: View {   var scene: SKScene {     let scene = GameScene()     scene.size = CGSize(width: 300, height: 400)     scene.scaleMode = .fill     return scene      }       func initScene () {     // why doesn't it work     scene.removeAllActions()     scene.removeAllChildren()         }       var body: some View {     VStack {       Text("Hello, world!")         .padding()       Button("Reset") {         initScene()       }               SpriteView(scene: scene)         .frame(width: 300, height: 400)         .ignoresSafeArea()     }         } } struct ContentView_Previews: PreviewProvider {   static var previews: some View {     ContentView( )   } }
Posted
by
Post not yet marked as solved
3 Replies
362 Views
Working with a student who wants to build a game in SpriteKit as a Mac app, and I was wondering if there are any good tutorials out there for this? Secondary, is there a better way to do key controls for a macOS games in Swift? Using the KeyDown function with the key code has been more of an annoying process than I would like. Is there any way of simply doing if keyPressed == "D" {...}?
Posted
by
Post not yet marked as solved
0 Replies
135 Views
I have a SpriteKit scene using UITouch to drag and drop. That works. I have also an SKCameranode and a pinchGesture so you can pinch to zoom in and out of the scene. That works too. Lastly, I set up a panGesture so that you can pan the scene when it is zoomed in. That also works, but it conflicts with the drag and drop. The drag and drop works when the scene first loads, but if you zoom in on the scene, you can no longer drag and drop because it just tries to pan, and even if you zoom back out to normal size, the drag and drop function remains messed up and will only partially move. I know there are instructions on how to allow simultaneous gestures or how to prefer one gesture over another, but only UIGestureRecognizer is mentioned in Apple's explanation of those. I didn't see anything about UITouch. Is there a way to make touches using UITouch and UIGestureRecognizers not conflict with each other?
Posted
by
Post not yet marked as solved
1 Replies
233 Views
I’m currently working on a matching game and when the user touches the nodes (Fruit match cards) I want them to display different images when a user clicks the nodes (Fruit match cards). This is my current code:  import Foundation  import SpriteKit  class EasyScreen: SKScene {         override func didMove(to view: SKView) {          var background = SKSpriteNode(imageNamed: "Easy Screen Background")          let timerText = SKLabelNode(fontNamed: "Arial")      timerText.fontSize = 40     timerText.fontColor = SKColor.white      timerText.position = CGPoint(x: 20, y: 400)      timerText.zPosition = 1     var counter:Int = 120                timerText.run(SKAction.repeatForever(SKAction.sequence([SKAction.run {              counter-=1       timerText.text = " Time: (counter)"       print("(counter)")          if counter <= 0{            let newScene = TryAgainScreen(fileNamed: "Try Again Screen")       newScene?.scaleMode = .aspectFill       self.view?.presentScene(newScene)                }       },SKAction.wait(forDuration: 1)])))                 background.position = CGPoint(x: 0, y: 0)     background.size.width = self.size.width     background.size.height = self.size.height     background.anchorPoint = CGPoint(x: 0.5,y: 0.5)               let matchCardOne = SKSpriteNode(imageNamed: "Fruit Match Card")     let matchCardTwo = SKSpriteNode(imageNamed: "Fruit Match Card")     let matchCardThree = SKSpriteNode(imageNamed: "Fruit Match Card")     let matchCardFour = SKSpriteNode(imageNamed: "Fruit Match Card")                  matchCardOne.name = "FruitMatchCard1"     matchCardTwo.name = "FruitMatchCard2"     matchCardThree.name = "FruitMatchCard3"     matchCardFour.name = "FruitMatchCard4"          matchCardOne.size = CGSize(width: 150, height: 300)     matchCardTwo.size = CGSize(width: 150, height: 300)     matchCardThree.size = CGSize(width: 150, height: 300)     matchCardFour.size = CGSize(width: 150, height: 300)               matchCardOne.zPosition = 1     matchCardTwo.zPosition = 1     matchCardThree.zPosition = 1     matchCardFour.zPosition = 1               matchCardOne.anchorPoint = CGPoint(x: 0.5, y: 0.5)     matchCardTwo.anchorPoint = CGPoint(x: 0.5, y: 0.5)     matchCardThree.anchorPoint = CGPoint(x: 0.5, y: 0.5)     matchCardFour.anchorPoint = CGPoint(x: 0.5, y: 0.5)               matchCardOne.position = CGPoint(x: -125, y: 60)     matchCardTwo.position = CGPoint(x: -125, y: -260)     matchCardThree.position = CGPoint(x: 70, y: 60)     matchCardFour.position = CGPoint(x: 70 , y: -260)          addChild(background)     addChild(matchCardOne)     addChild(matchCardTwo)     addChild(matchCardThree)     addChild(matchCardFour)     addChild(timerText)        } override func touchesBegan(_ touches: Set, with event: UIEvent?) {         self.view?.isMultipleTouchEnabled = false      let touch = touches.first   let positionInScene = touch!.location(in: self)   let touchedCardOneNode = self.atPoint(positionInScene)      if let name = touchedCardOneNode.name {          if name == "FruitMatchCard1" {           let newTexture = SKTexture(imageNamed: "Apple")       FruitMatchCard1.init(texture: newTexture)          }      }      let touchTwo = touches.first     let positionInSceneTwo = touch!.location(in: self)     let touchedCardTwoNode = self.atPoint(positionInScene)           if let name = touchedCardTwoNode.name {               if name == "FruitMatchCard2" {                 FruitMatchCard2.init(imageNamed: "Banana")              }          }        let touchThree = touches.first       let positionInSceneThree = touch!.location(in: self)      let touchedCardThreeNode = self.atPoint(positionInScene)            if let name = touchedCardThreeNode.name {                if name == "FruitMatchCard3" {                            FruitMatchCard3.init(imageNamed: "Apple")                }            }        let touchFour = touches.first   let positionInSceneFour = touch!.location(in: self)   let touchedCardFourNode = self.atPoint(positionInScene)      if let name = touchedCardFourNode.name {         if name == "FruitMatchCard4" {                 FruitMatchCard4.init(imageNamed: "Banana")          }      }        } override func touchesEnded(_ touches: Set, with event: UIEvent?) {             } I’m trying to change the textures of the nodes in this part of the code. Inside the “if name == “FruitMatchCard” { } “ part of the code. However, when I launch the Xcode simulator the node’s textures aren't changing. Any advice on how I can do this? Thanks!
Posted
by
Post not yet marked as solved
1 Replies
450 Views
I am using xcode 13.3 beta 3 to make a game in spritekit using swift. The game is working pretty good and i am very happy with it so far. There is a problem i am trying to figure out. The game is a block type game where you drag a block into the game area from a holding area and drop it in an open spot. When you first touch and hold the block or touch and move the block, a method moves the block a certain number of points above the touch area Y axis using SKAction.moveby. The block x axis matches the touch area. Then you move the block to an open are and drop it. If you do this very slow, there is no problem. But if you try to do it fast, you can see it do the SKAction.moveby first and complete, then the block quickly moves from where it finished the moveby animation to where you current touch position is it. This makes it feel very jerky and unnatural. Is there a way to make the block follow your fingers position AND animate using moveby at the same time? I feel that the problem is with the skaction.moveby because if you move your finger fast enough, you can be way above where the animation would normally finish and thats why you see the block jump to the touch. I wonder if there is a way to use the update() method to somehow change the blocks position without using moveby or move to. Thank you for any help you can provide me. I can also you show you my touchesBegin, moved and ended methods if that will help.
Posted
by
Post not yet marked as solved
12 Replies
1.8k Views
I've an app I've been working on for quite some time now. It uses SpriteKit. The windows with the scenes in them are generated programmatically. All of a sudden, when it's up and running through XCode, the console throws out a continuous stream of errors - probably in the order of 1 per second. The main one that makes up this stream is: 2022-03-07 20:07:38.765930+0000 My*App[8461:465673] [] CurrentVBLDelta returned 0 for display 1 -- ignoring unreasonable value But others that appear slightly less frequently are: 2022-03-07 20:07:38.447800+0000 My*App[8461:465143] Metal GPU Frame Capture Enabled 2022-03-07 20:07:38.448070+0000 My*App[8461:465143] Metal API Validation Enabled 2022-03-07 20:07:38.613097+0000 My*App[8461:465640] [] [0x7f9596053820] CVCGDisplayLink::setCurrentDisplay: 1 2022-03-07 20:07:38.613415+0000 My*App[8461:465640] [] [0x7f9596053820] Bad CurrentVBLDelta for display 1 is zero. defaulting to 60Hz. 2022-03-07 20:07:38.613442+0000 My*App[8461:465640] [] [0x7f9596053800] CVDisplayLinkCreateWithCGDisplays count: 1 [displayID[0]: 0x1] [CVCGDisplayLink: 0x7f9596053820] 2022-03-07 20:07:38.613467+0000 My*App[8461:465640] [] [0x7f9596053800] CVDisplayLinkStart 2022-03-07 20:07:38.613487+0000 My*App[8461:465640] [] [0x7f9596053820] CVDisplayLink::start 2022-03-07 20:07:38.613541+0000 My*App[8461:465640] [] [0x7f9596053800] CVDisplayLinkStart 2022-03-07 20:07:38.613575+0000 My*App[8461:465640] [] [0x7f9596053820] CVDisplayLink::start 2022-03-07 20:07:38.613634+0000 My*App[8461:465671] [] [0x600000c09f10] CVXTime::reset 2022-03-07 20:07:38.613718+0000 My*App[8461:465671] [] CurrentVBLDelta returned 0 for display 1 -- ignoring unreasonable value 2022-03-07 20:07:38.639810+0000 My*App[8461:465671] [] CurrentVBLDelta returned 0 for display 1 -- ignoring unreasonable value 2022-03-07 20:07:38.639887+0000 My*App[8461:465671] [] [0x7f9596053820] CVCGDisplayLink::getDisplayTimes display: 1 -- SLSDisplayGetCurrentVBLDelta returned 0 => generating fake times 2022-03-07 20:07:38.673702+0000 My*App[8461:465653] [] [0x7f9596053820] CVCGDisplayLink::setCurrentDisplay: 1 2022-03-07 20:07:38.673748+0000 My*App[8461:465653] [] [0x7f9596053820] CVDisplayLink::stop 2022-03-07 20:07:38.673862+0000 My*App[8461:465653] [] [0x7f9596053820] Bad CurrentVBLDelta for display 1 is zero. defaulting to 60Hz. 2022-03-07 20:07:38.673883+0000 My*App[8461:465653] [] [0x7f9596053820] CVDisplayLink::start I really don't know how else to describe this. I can only imagine having to hand over the entire project as lately I've only been working on the storyboard file so how would this affect it? To be honest the only change I can see is my upgrade to OSX 12.2.1. It's definitely something to do with SpriteKit since not initialising a window with a scene in it stops the errors from showing.
Posted
by
Post not yet marked as solved
0 Replies
315 Views
We noticed when using async await with SpriteKit run function. Self is retained until run action is completed which can cause memory leak.   Task {             try? await Task.sleep(nanoseconds: 2 * NSEC_PER_SEC)             await controller.startIntro()             print("intro done")         } If you deallocate controller, memory won't be released until await is not completed.  calling:  scene.removeAllActions() cause memory leak.  Here is project reproducing steps with possible workarounds:  https://github.com/maradic/SpriteKitConcurrencyBug Is this SpriteKit bug or am I doing something wrong?
Posted
by
Post not yet marked as solved
0 Replies
251 Views
Im learning to use spritekit, first-project kind of newbie, and on various tutorials I've seen that there is a tab on the right column, on the bottom, with a menu that helps import visual assets quickly into a gamescene. Upon creating my first project I can't seem to find this tab nor a way to add it to my project; under the "Custom shader uniforms" my right-most column seems empty, unlike what I've seen on tutorials. Since this 'tab' doesn't seem to have a title I'm unsure of what I'm even looking for! This is how my new spritekit scene looks like: This is a screenshot from a tutorial where an asset importer kind of tab can be seen: Any help is very much appreciated!!!
Posted
by
Post not yet marked as solved
2 Replies
249 Views
In my app using storyboard and spritekit developed in Xcode 12.5.1 uses segue connected button to bring up another storyboard which presents a scene and show a sprite. The segue sequence triggered by the use pressing the Play button and running the segue shows an upward transition and the scene with the sprite that when clicked animates that sprite. My problem is I was getting two events that are causing me issues. The first is that I was expecting a sidewards transition for the Show segue. and second that the scene only covers 2 thirds on the screen not all of it. Screenshots of. Xcode showing main storyboard and segue connections, simulator app Settings, app Game initial view and app Game with sprite animated. Anyone any hints for me for explanation of the first event and how to resolve the second which is spoiling my development time?
Posted
by
Post not yet marked as solved
0 Replies
307 Views
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       }     }   } }
Posted
by
Post not yet marked as solved
2 Replies
279 Views
I am trying to get a simple animated sprite image in a very basic game using SpriteKit and Xcode 12. I am creating an skspritenode with image named and setting its position form the touch point and adding it as a child but a red X image is shown on the simulator of iPhone 8 Plus. I have attached screenshots. Can someone help me with this?
Posted
by
Post not yet marked as solved
0 Replies
225 Views
When I start my project the tile added to my SKScene using the editor do not appear until after I have clicked on the tiles that was selected in the scene setup. Anyone any ideas why> Also should these tiles be in the list shown to the left of the scene as those sprites (not part of the tileset) I dragged into the scene are. I have attached screen shots of at start and after clicking the tiles.
Posted
by
Post not yet marked as solved
1 Replies
239 Views
I wanted to build a game for my class like "UniWar: Multiplayer Strategy." It is a hexagonal tile 2d strategy game. Everywhere I search online, everything points to using SpriteKit and using the tile sets to accomplish what I want. The problem I am running into is that there is very little if not poor examples online of using Tile Sets and SpriteKit (or maybe they are super good but my novice skills is getting in the way). Every tutorial I have found is either 6 years old and is unrecognizable or Apple Documentation that tends to explain what it is but not how to use it. I should mention a couple things, one, yes, I am a novice swift programmer and, two, I learn best by doing not by being told (so for example, someone showing me how to use it helps a lot more than "use this code"). I really want to learn so does anyone have some suggestions for learning Tile Sets and SpriteKit in general? P.S. I am also not above a course that costs something (I have already searched Udemy for a course on this but couldn't find one)
Posted
by
Post not yet marked as solved
0 Replies
172 Views
I'm toying around with SpriteKit and using SKS files to construct scenes. I've started with the stock Game project and added one extra SKS file and a class to go along with it. My class will attempt to load the SKS file to build its scene just like the stock files do. However, when I go to the GameViewController and actually try to use my class, I get a runtime error that my SKS file can't be found. I've verified that the SKS file is in the project, is part of the bundle, is visible at runtime from within the bundle, but my class that uses the SKScene initializer to load the file can't see it and I'm not sure why.
Posted
by