Building a game with Swift Playgrounds is mostly an exercise in trying to find ways to hack together a solution that’ll work for your idea. You don’t have access to all the tools that you would in full Xcode, so you just have to make do with what you’ve got.
Using SwiftUI Charts
Swift UI Charts is a powerful framework built specifically for displaying different types of data in a graphical way to a user. This would typically be used to display data in maybe an accounting app, a habit tracker, or even the Fitness app on your Apple Watch.
However, I’m using it a bit differently in my Swift Playgrounds game “Rockets are Fun”. In this small prototype of a game, I’m going to be using the SwiftUI Charts framework to display dynamic fuel gauges to the player as they navigate through the world. It’s not pretty (yet) but it’s working and that’s the first step in game design right?
Adding SwiftUI Charts to a SpriteKit Game
The idea sounds strange to say, but it’s quite simple to implement. If you don’t want to watch the full 28-minute video I did put some timestamps in there so you can jump around.
But if you really can’t be bothered to watch the YouTube video here’s the general gist of what I did.
Inside the SpriteKit scene which is fed into the SwiftUI view using SpriteView() I write to different @Published variables for the fuel. These are contained in a separate class called GameData() which adheres to the ObservableObject protocol allowing it to be read from any view within my app.
So now, I just need to read the values that are tied to the different fuel types and feed them into the charts that SwiftUI has so conveniently given me access to.
A Personal Milestone
This solution is sort of a personal milestone for me as a programmer. Whether this is a good solution or not, it’s a solution I came up with without relying on previous works to riff off of. I had this idea because I’d previously worked with SwiftUI Charts in another app and thought that I could make them work as fuel gauges so I set out to create the solution.