GCVirtualController isn't displaying when used with SKScene class. The Virtual controllers appear but then it seems that they are obscured by the SKScene itself!? The documentation says that calling connect() will display the virtual controllers but I seem to be missing how to add the controllers to the SKScene?
class GameScene: SKScene {
private var _virtualController: Any?
@available(iOS 15.0, *)
public var virtualController: GCVirtualController? {
get { return self._virtualController as? GCVirtualController }
set { self._virtualController = newValue }
}
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed: ".jpg")
background.zPosition = -1
addChild(background)
let virtualConfig = GCVirtualController.Configuration()
virtualConfig.elements = [GCInputLeftThumbstick, GCInputRightThumbstick, GCInputButtonA, GCInputButtonB]
virtualController = GCVirtualController(configuration: virtualConfig)
virtualController?.connect()
}
}
I've also tried adding the virtual controllers in the UIViewController but this doesn't work either.
SpriteKit
RSS for tagDrawing shapes, particles, text, images, and video in two dimensions using SpriteKit.
Post
Replies
Boosts
Views
Activity
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)
}
}
I'm trying to create a Apple Watch game using Xcode 14.2 and watchOS 9. Getting started creating a watchOS App seems pretty straight forward, and getting started creating a game project via the starter template seems easy enough. Trying to put these two together though doesn't seem to work (or is not straight foward). The documentation specifies limitations on what libraries can be used with watchOS noting WKInterfaceSKScene, but doesn't give any specific examples of how to start out a WatchOS project using this. Additionally nearly every online tutorial that I'm able to find uses Storyboards to create a watchOS game, which does not seem to be supported in the latest version of watchOS or Xcode. Can anyone provide example starter code using the watchOS App project starter that that loads with a small colored square on the screen that moves from left to right using the WKInterfaceSKScene library?
I've tried the Apple documentation, asking ChatGPT for a sample or reference links, and various tutorials on YouTube and elsewhere.
I have multiple images that at various times I need to replace a target image for a SKSpriteNode.
Each of these multiple images has a different size.
The target SKSpriteNode has a fixed frame that I want to stay fixed.
This target is created via:
myTarget = SKSpriteNode(imageNamed: “target”)
myTarget.size = CGSize(…)
myTarget.physicsBody = SKPhysicsBody(rectangleOf: myTarget.size)
How do I resize each of the multiple images so that each fills up the target frame (expand or contract)?
Pretend the target is a shoebox and each image is a balloon that expands or contracts to fill the shoebox.
I have tried the following that fails, that is, it changes the size of the target to fit the new image .. in short, it does the exact opposite of what I want.
let newTexture = SKTexture(imageNamed: newImage)
let changeImgAction = SKAction.setTexture(newTexture, resize: true)
myTarget.run(changeImgAction)
Again, keep frame of myTarget fixed and change size of newTexture to fit the above frame ..
Hi,
I'm creating a SF Symbols image like this:
var img = UIImage(systemName: "x.circle" ,withConfiguration: symbolConfig)!.withTintColor(.red)
In the debugger the image is really red.
and I'm using this image to create a SKTexture:
let shuffleTexture = SKTexture(image: img)
The texture image is ALWAYS black and I have no idea how to change it's color. Nothing I've tried so far works.
Any ideas how to solve this?
Thank you!
Best Regards,
Frank
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.
Hi all
So I'm quite new into GameDev and am struggling a bit with the Tilemap
All my elements have the size of 64x64. As you can see in my screenshot there is some gap between the street and the water. It might be simple but what's the best way to fix that gap? I could increase the width of the left and right edge png but then I will sooner or later run into other problems as it then is not fitting with the rest.
Thanks for your help
Cheers from Switzerland
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
Background:
This is a question asking for a good example of SpriteKit from a very new iOS developer who is investigating for starting an iOS 2D game project.
As I explored in the official apple development doc, to dev a 2D game SpriteKit is the very framework I am looking for.
There have been some clear and succinct words for any API and class documented in the reference spec when I started a project in Xcode. However I haven't been able to finish the project as having no any general idea about what is always needed of a typical game using the framework.
Question:
As an experienced Java Spring programmer I believe that I am needed a brief example to get started with the SpriteKit framework which provides me an idea of necessary steps for a 2D game.
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?
I have implemented auto renewable subscriptions in my app, as well as promo codes. Purchase of subscriptions both monthly and annual; work correctly. What I don't know is what to "listen for" instead of product, when the user uses a promo code to purchase the product. am I looking for a different product code? or product identifier when the offer code is used to subscribe?
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.
How do I change a UIBezierPath.currentPoint to a SKSpriteNode.position?
Here are the appropriate code snippets:
func createTrainPath() {
let startX = -tracksWidth/2,
startY = tracksPosY
savedTrainPosition = CGPoint(x: startX, y: startY!)
trackRect = CGRect(x: savedTrainPosition.x,
y: savedTrainPosition.y,
width: tracksWidth,
height: tracksHeight)
trainPath = UIBezierPath(ovalIn: trackRect)
trainPath = trainPath.reversing() // makes myTrain move CW
} // createTrainPath
Followed by:
func startFollowTrainPath() {
let theSpeed = Double(5*thisSpeed)
var trainAction = SKAction.follow(
trainPath.cgPath,
asOffset: false,
orientToPath: true,
speed: theSpeed)
trainAction = SKAction.repeatForever(trainAction)
createPivotNodeFor(myTrain)
myTrain.run(trainAction, withKey: runTrainKey)
} // startFollowTrainPath
So far, so good (I think?) ...
Within other places in my code, I call:
return trainPath.currentPoint
I need to convert trainPath.currentPoint to myTrain.position ...
When I insert the appropriate print statements, I see for example:
myTrain.position = (0.0, -295.05999755859375)
trainPath.currentPoint = (392.0, -385.0)
which obviously disqualifies a simple = , as in:
myTrain.position = trainPath.currentPoint
Since this = is not correct, what is ?
After more investigation, my guess is that .currentPoint is in SKSpriteNode coordinates and .position is in SKScene coordinates.
An SCNNode is created and used for either an SCNView or an SKView.
SceneKit and SpriteKit are using default values.
The SceneView has an SCNScene with a rootNode of the SCNNode.
The SpriteKitView has a SpriteKitScene with an SK3DNode that has an SCNScene with a rootNode of the SCNNode.
There is no other code changing or adding values.
Why are the colors for the SCNView less vibrant than the colors for the SKView?
Is there a default to change to make them equivalent, or another value to add? I have tried changing the default SCNMaterial but only succeeded in making the image black or dark.
Any help is appreciated.
I am trying to make an application for the Vision Pro where the particles don't move but rather stay still so that there is no lag. For example I am trying to spawn in a 100 particles here:
I want the particles to remain static but spawning in many causes the simulator to lag. Also is there maybe a way i can get a particle system to follow a specific shape like the one i have in the image.
Currently, I have multiple model entities that take on a particle system component
for i in 0..<100 {
let newEntity = ModelEntity()
var particleSystem = particleSystem(color: newColor)
newEntity.components.set(particleSystem)
newEntity.position = position
newEntity.scale = scale
stars.append(newEntity)
}
}
func particleSystem(color: UIColor) -> ParticleEmitterComponent {
var particles = ParticleEmitterComponent()
particles.emitterShapeSize = .init(repeating: 0.02)
// make burst smaller
particles.emitterShape = .sphere
particles.mainEmitter.birthRate = 1
particles.mainEmitter.lifeSpan = 2
particles.mainEmitter.size = 0.02
particles.burstCount = 50
particles.speed = 0.01
particles.mainEmitter.isLightingEnabled = false
particles.mainEmitter.color = .constant(.single(color))
return particles
}
I'm trying to add an image in UIImage format to SpritKit's SKSpriteNode.
When converting a UIImage into a texture to SKTexture and adding it to SKSpriteNode, the image that takes into account the orientation of the image held by the UIImage is not displayed on the screen.
I tried the code below, but the result is identical.
Code1:
let image: UIImage?
let texture: SKTexture = SKTexture(image: image!)
ver imageNode = SKSpriteNode(texture: texture)
Code2:
let image: UIImage?
let cgImage = image?.cgImage
let ciImage = CIImage(cgImage: cgImage!)
let orientedImage = UIImage(cgImage: CIContext(options: nil).createCGImage(ciImage, from: ciImage.extent)!, scale: 0, orientation: image!.imageOrientation)
let texture: SKTexture = SKTexture(image: orientedImage)
ver imageNode = SKSpriteNode(texture: texture)
Code3:
let image: UIImage?
guard let cgImage = image?.cgImage else { return }
let orientedImage = UIImage(cgImage: cgImage, scale: image!.scale, orientation: .up)
let texture = SKTexture(image: orientedImage)
ver imageNode = SKSpriteNode(texture: texture)
Is there a way to ensure that the image orientation is taken into account when displayed?
Calling SKAction.follow(..) causes my SKSpriteNode to rotate 90 degrees CW and not stay horizontal as it follows my UIBezierPath?
I have this code (within my GameViewController Class) which implements the following of a SKSpriteNode along a UIBezierPath.
=====
Please note that a brilliant contributor solved the above challenge by creating a new Class, e.g., class NewClass: NSObject. Nevertheless, I need the solution to appear in an extension of my GameViewController
=====
func createTrainPath() {
trackRect = CGRect(x: tracksPosX - tracksWidth/2,
y: tracksPosY,
width: tracksWidth,
height: tracksHeight)
trainPath = UIBezierPath(ovalIn: trackRect)
} // createTrainPath
func startFollowTrainPath() {
var trainAction = SKAction.follow(
trainPath.cgPath,
asOffset: false,
orientToPath: true,
speed: theSpeed)
trainAction = SKAction.repeatForever(trainAction)
myTrain.run(trainAction, withKey: runTrainKey)
} // startFollowTrainPath
func stopFollowTrainPath() {
guard myTrain == nil else {
myTrain.removeAction(forKey: runTrainKey)
savedTrainPosition = getPositionFor(myTrain, orPath: trainPath)
return
}
} // stopFollowTrainPath
https://developer.apple.com/documentation/spritekit/sktransition/configuring_whether_animations_play_during_the_transition
the figure 1 Frame progression during transitions,the last pair of pauseIncomingScene and pauseOutgoingScene. the pauseOutgoingScene should be false not true
So I have an SKScene in SpriteKit, and I am trying to export the scene as an image, but have no idea how.
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).