SpriteKit

RSS for tag

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

Posts under SpriteKit tag

45 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

SKTextureAtlas Error
I am using the following code to create a texture atlas at runtime using a single .png image sprite sheet: func createSpriteTextureAtlas(atlasNumber atlas:Int, forWorld world:Int) { //load the png file let image = UIImage(named: "world\(world)_spritesheet\(atlas)_2048x2048.png") //create the dictonary var imageDictionary = [String: UIImage]() //iterate through all rows and columns and get the subimage var imageIndex = 0 for row in 0...7 { for column in 0...7 { let sourceRect = CGRect(x:column * 256, y:row * 256, width:256, height:256) let sourceImage = image?.cgImage!.cropping(to: sourceRect) let subImage = UIImage(cgImage: sourceImage!) //add the sub image and name to the dictionary imageDictionary["\(imageIndex)"] = subImage imageIndex = imageIndex + 1 } } //create the texture atlas using the dictionary spriteTextureAtlas[atlas] = SKTextureAtlas(dictionary: imageDictionary) } I have a different sprite sheet for every world. I made all the sprite sheets myself using the same tool. This code works 100% of the time for most images. For some images however, the program crashes at: SKTextureAtlas(dictionary: imageDictionary) with the error: Thread 4: EXC_BAD_ACCESS (code=1, address=0x105ff2000). The stack trace says it is crashing inside: #0 0x00000002178e2d34 in -[SKTextureAtlasPacker isFullyOpaque:] (). The crash does not happen every time and only happens for some images. The crash never happens on the simulator. Did I make a mistake inside createSpriteTextureAtlas or is this a SpriteKit bug? P.S. I already know that I can let Xcode make the texture atlas for me by using a folder with a .atlas extension but this is not what i want to do.
2
0
516
Jan ’24
SpriteKit animations freeze in second window on second display on Apple Silicon
We have a 2023 Mac mini with an Apple M2 Pro chip. The Mac has two displays connected. If a SpriteKit application has two windows on separate desktops, one of the windows can’t run animations. You can easily replicate this issue with the following steps: Create a new macOS project in Xcode. Select the sample Game project with SpriteKit as the technology. Edit the fade duration in GameScene.swift to make the animated nodes live longer (e.g. 15 seconds). In AppDelegate.applicationDidFinishLaunching, add code to instantiate a second window: let mainStoryboard = NSStoryboard.init(name: NSStoryboard.Name("Main"), bundle: nil) if let newWindow = mainStoryboard.instantiateInitialController() as? NSWindowController { newWindow.showWindow(self) } Run the app. If both windows are on the same desktop, animations run correctly. If the windows are on separate desktops, then animations halt on the 1080p desktop, even though the SKView reports full frame rate. You can also just check out the sample project from my github repo: https://github.com/lanephillips/SKTest The issue does not occur if the application is built for Intel processors only and run on Apple Silicon under Rosetta. We've seen this issue occur in both macOS 13 and 14. I've filed a report through Feedback Assistant, but I'm posting here in case someone else has seen this and has a workaround.
1
6
565
Jan ’24
Different methods of animating shape along custom path?
I'm trying to animate a shape (e.g. a circle) to follow a custom path, and struggling to find the best way of doing this. I've had a look at the animation options from SwiftUI, UIKit and SpriteKit and all seem very limited in what paths you can provide. Given the complexity of my path, I was hoping there'd be a way of providing a set of coordinates in some input file and have the shape follow that, but maybe that's too ambitious. I was wondering if this were even possible, and assuming not, if there were other options I could consider.
1
0
897
Jan ’24
SpriteKit in Vision OS can't detect touch input
Hello everyone I am porting my existing 2d game writing by spritekit to visionOS and I am creating a SpriteView in WindowGroup let currentScene = BattleScene.newGameScene(gameMode: "endless", dataContext: dataController.container.viewContext) SpriteView(scene: currentScene) .ignoresSafeArea(.all) .frame(width: currentScene.frame.width, height: currentScene.frame.height, alignment: .center) .onReceive(NotificationCenter.default.publisher(for: GameoverNotification)) { _ in stopAllAudio() } .onTapGesture { location in let viewPosition = location let touchLocation = CGPoint(x: viewPosition.x, y: viewPosition.y) print("touch on vision window: ", touchLocation.x, touchLocation.y) } .glassBackgroundEffect() //WindowGameView() // .environment(\.managedObjectContext, dataController.container.viewContext) // .environment(model) // .environment(pressedKeys) } .windowStyle(.automatic) .defaultSize(width: 0.5, height: 1.0, depth: 0.0, in: .meters) run it and it turns out the scene can't receive tap event. but it works normal if I run it with my ios target (vision Os designd for ipad) is there anything I missed?
0
0
518
Jan ’24
CIFilter + SpriteKit broken behavior on iOS 16
Hello there 👋 I've noticed a different behavior between iOS 15 and iOS 16 using CIFilter and SpriteKit. Here is a sample code where I want to display a text and apply a blurry effect on the same text in the back of it. Here is the expected behavior (iOS 15): And the broken behavior on iOS 16: It looks like the text is rotated around the x-axis and way too deep. Here is the sample code: import UIKit import SpriteKit class ViewController: UIViewController {     var skView: SKView?     var scene: SKScene?     override func viewDidLoad() {         super.viewDidLoad()         skView = SKView(frame: view.frame)         scene = SKScene(size: skView?.bounds.size ?? .zero)         scene?.backgroundColor = UIColor.red         view.addSubview(skView!)         skView!.presentScene(scene)         let neonNode = SKNode()         let glowNode = SKEffectNode()         glowNode.shouldEnableEffects = true         glowNode.shouldRasterize = true         let blurFilter = CIFilter(name: "CIGaussianBlur")         blurFilter?.setValue(20, forKey: kCIInputRadiusKey)         glowNode.filter = blurFilter         glowNode.blendMode = .alpha         let labelNode = SKLabelNode(text: "MOJO")         labelNode.fontName = "HelveticaNeue-Medium"         labelNode.fontSize = 60         let labelNodeCopy = labelNode.copy() as! SKLabelNode         glowNode.addChild(labelNode)         neonNode.addChild(glowNode)         neonNode.addChild(labelNodeCopy)         neonNode.position = CGPoint(x: 200, y: 200)         scene?.addChild(neonNode) } }
5
4
2.7k
Dec ’23
Can't hear CAF Audio in running app
I have an unusual situation. I'm working through some self study training and this particular project is a game similar to fruit ninja where things are flying around the screen and you slice through them by swiping your finger. Anyway the instructor provided a series of "*.caf" files for various sounds while playing the game. For some reason I can't hear any of the sounds on my personal Mac when running the app via Xcode to either an iOS iPad simulator or to a real iPad that I have attached to my mac and setup for developer use in Xcode. Yes sound is working on the mac (hear new email come in etc. and can play videos in the browser). In the iPad simulator I can play youtube videos in mobile safari. While adjusting the sound doesn't seem to raise or lower the volume I can hear the audio in the youtube videos. On the real iPad: yes the sound is on and I can hear audio while playing videos in the browser etc. Lastly, I pushed the code up to GitHub and pulled it to my work Mac. There the sound plays just find in the iOS iPad simulator on that Mac (not allowed to attach my personal iPad to my work mac so can't try the iPad there). So I fell like this confirms the code is correct for playing the sounds in the running app. Oh, and I can select the file in left nav and click the little play button icon to hear it played in Xcode. so, I feel like this is an issue on my personal Mac with Xcode etc., but I'm at a loss as to what the issue is. Can anyone suggest some things to look for on my Mac to get sound working in this app? if you want to see the code it's here and the free training i'm following is at https://www.hackingwithswift.com/100/77. TIA
3
0
642
Dec ’23
SpriteKit - Associating sound with motion
I need to associate sound with the movement of a sprite. Movement can be as a result of physics, not as a result of an SKAction. When the object is sliding thee should be sliding sound throughout the time when it is sliding, and then a different sound when it bumps into a rock and goes up in the air. When the object is airborne, there is no sound, till it falls again - a falling sound, and then slides down with a sliding sound. The sounds associated with the collision ( rock, ground and so on ) are straightforward and work fine. But am having difficulty associating the sound with movement. The closest result I have is to check the velocity of the sprite's physics body every update cycle and play or stop the sound based on whether the velocity is greater than zero. I tried SKAction.playSoundFileNamed first - the sound kept going even when the object was not moving. I tried adding an SKAudioNode with Play and Stop, with no better result. I finally tried using AVAudioPlayer to play and Pause , which yielded the best results, but the sliding sound still played past the sliding action. What is the best way to do this? My code for playing the sound is as follows: var blockSliding = false for block in gameBlocks { if (block.physicsBody?.velocity.dx ?? 0) + (ball.physicsBody?.velocity.dy ?? 0) > 0.05 { blockSliding = true break } } if slideSound.isPlaying { if !blockSliding { slideSound.pause() } } else { if blockSliding { slideSound.play() } } I have setup slideSound earlier loading the appropriate sound file into an AVAudioPlayer
0
0
473
Nov ’23
ProRes4444 with alpha not work using AVPlayer
I have a ProRes 4444 format video with an alpha channel. The circle in the middle of the video is completely opaque, while the rest is fully transparent. Everything looks normal in iMovie, as I can see the background through the surrounding parts. However, when I play it using AVPlayer, the parts that are supposed to be fully transparent appear somewhat opaque, as shown in the image below: I used the official project provided by Apple named 'using_hevc_video_with_alpha', but I only replaced the HEVC with alpha format file with a ProRes 4444 format video file. Below is the main code. import Cocoa import SpriteKit import AVFoundation class ViewController: NSViewController { @IBOutlet var skView: SKView! var videoPlayer: AVPlayer! override func viewDidLoad() { super.viewDidLoad() if let view = self.skView { // Load the SKScene from 'backgroundScene.sks' guard let scene = SKScene(fileNamed: "backgroundScene") else { print ("Could not create a background scene") return } // Set the scale mode to scale to fit the window scene.scaleMode = .aspectFill // Present the scene view.presentScene(scene) // Add the video node guard let alphaMovieURL = Bundle.main.url(forResource: "xuewang", withExtension: "mov") else { print("Failed to overlay alpha movie on the background") return } videoPlayer = AVPlayer(url: alphaMovieURL) let video = SKVideoNode(avPlayer: videoPlayer) video.size = CGSize(width: view.frame.width, height: view.frame.height) print( "Video size is %f x %f", video.size.width, video.size.height) scene.addChild(video) // Play video videoPlayer.play() } } }
0
0
585
Nov ’23
Unable to use SpriteKit with Swift Playground Books
All our custom Playground Books using SpriteKit stopped working after upgrading to SwiftPlaygrounds version 4.4 To reproduce the issue, simply create a new book by clicking the top right hand icon and in the book add two lines of code. import SpriteKit let circle = SKShapeNode(circleOfRadius: 100.0) The second line produces an error. I tried with other classes. SKAction seems to work. SKSpriteNode, SKTexture etc have the same issue. Please help. Our students are stuck!
2
0
737
Oct ’23
err: [0x159dec540|RoomCongruence::Processor|Processor] One or more of the chosen IR Presets does not contain room congruence data or the data is corrupted.
mac mini 2018, MAC OS Ventura 13.5.2, Xcode 15.0 im running my game app in iPhone SE(3rd gen) device(not simulator) with IOS 17 and getting the following error in console: [0x159dec540|RoomCongruence::Processor|Processor] One or more of the chosen IR Presets does not contain room congruence data or the data is corrupted. err shows in console among this other errs messages: getFilePtr: error -1 getting file status [Room Congruence] isIrDataUserDataDictionaryStructurallyValid: IRData User Data invalid - underlying CF object is nil. [0x159dec540|RoomCongruence::Processor|Processor] One or more of the chosen IR Presets does not contain room congruence data or the data is corrupted. the error is showing only(one time) when user have started a game, but not showing if user select to play again. app have been tested on IOS 15 and 16 but not showing this error. appreciate any help, i can provide any other data as necessary. Sorry if im may be missing any info or data necessary this my first time posting here, thanks.
0
0
596
Oct ’23
err:[Room Congruence] isIrDataUserDataDictionaryStructurallyValid: IRData User Data invalid - underlying CF object is nil.
mac mini 2018, MAC OS Ventura 13.5.2, Xcode 15.0 using SpriteKit im running my game app in iPhone SE(3rd gen) device(not simulator) with IOS 17 and getting the following error in console: [Room Congruence] isIrDataUserDataDictionaryStructurallyValid: IRData User Data invalid - underlying CF object is nil. the error is showing only(one time) when user have started a game, but not showing if user select to play again. the error is showing among the following console errs: getFilePtr: error -1 getting file status [Room Congruence] isIrDataUserDataDictionaryStructurallyValid: IRData User Data invalid - underlying CF object is nil. [0x159dec540|RoomCongruence::Processor|Processor] One or more of the chosen IR Presets does not contain room congruence data or the data is corrupted. app have been tested on IOS 15 and 16 but not showing this error. appreciate any help, i can provide any other data as necessary. Sorry if im may be missing any info or data necessary this my first time posting here, thanks.
0
1
577
Oct ’23
Is it possible to make Unity iOS App into iOS widget extension?
HELLO WORLD! I am currently developing an amazing Unity mini Game. The game development has come to the deploying stage. Using Unity allows me to deploy this game on MacOS, iOS, Android and Windows which is fantastic . However, I really need this game to have the iOS widget extension as a key feature on mobile. Just like the "Steve" dinosaur game which can be played in widget. I had seen a lot of tutorials and youtube videos but still cant find a solution which make Unity iOS app into a widget. If I really want to make widget Game on iOS, do I need to develop the whole game all over again in xcode or using GameKit? Really hoping there's a way to simply convert the Unity iOS app into a widget.
2
1
1.8k
Oct ’23
Sudden error being logged continuously in XCode console
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.
20
4
7.6k
Oct ’23
Can a physical body be partially contained by an edge-loop body?
I have a sprite kit scene with an edge loop physics body set programmatically with the category bit mask set to a custom Physics Category called Edge. Through the scene editor, I've added several sprite nodes with varying physics body types and various category masks and collision masks. The collision mask for a particular sprite node includes the Edge category. Initially, I have this node partially off the screen on the scene editor but when I run the program, it appears completely inside the edge loop. Is it possible to have a sprite node be positioned partially inside the edge loop and partially outside the edge loop?
0
0
444
Sep ’23