Spritekit Automapping Adventure
I have decided to develop a few games in 2022. In an effort to update my skills I’ve set about writing a Spritekit game with SwiftUI. In my head I would like to make a fairly large, 2D action-roguelike game where your character has to traverse an infinite number of “levels”, ward off the baddies and manuever whatever the story is. It’s a pickle!
Best place to start is the beginning so I created a new iOS app. I always liked to use a Navigation Controller to handle the main menu type stuff and starting with this in mind realized I had no idea how to create a navigation view in SwiftUI. Apple’s Docs are fairly clear on implementation, but the simplicity of things within SwiftUI initially through me for a loop. The ability to create everything required for navigation, e.g. stack, controller and subsequent views, for a Main Menu system is around 11 lines of code.
1 | struct MainView: View { |
There is a lot going on in those thirteen lines and it looks dramatically different than the bracketed world of Obj-C that I am more intimiately familiar with. I’m not going to dive too deep into those differences in this post, but will write something up in the future. Off of my menu there are two Views game & settings. Settings ATM is just a blank view but Game is the bread and butter. Inside I create a SKScene object to render and house game components, e.g sprites, tiles, player node, joystick, and then utilize SpriteView to draw it within a SwiftUI View.
1 | struct SpriteViewWrapper: View { |
This loads our GameScene():SKScene object and now we finally render whatever is contained within. Voila!
For the tiles I’m leveraging GamePlayKit to generate uniformed noise and then creating physics bodies for each tile to handle collisions. A player, currently playerNode = SKShapeNode(circleOfRadius: playerRadius), is added atop the map tiles and a Camera SKNode is generated with the joystick and other HUD elements attached to it to allow for everything to smoothly move on scroll. Scroll is accomplished by grabbing the velocity of the touches for the Joystick object and on the GameLoop update applying a scale of this velocity to the Player, which updates it’s x & y position, and then set the Camera’s current position to the Player’s updated. Keanu whoa
The only tricky bit in most of this is that Spritekit doesn’t allow one to simply set a collisions on an entire TileGroup, i.e. the rock or water tiles, so they are attached in the same loop that the tiles’ render is accomplished. The last bit of code accomplishes this
1 | func createCollisionNode(col: Int, row: Int, tileSize: CGSize, halfWidth: CGFloat, halfHeight:CGFloat, collisionBitMask: Int, categoryBitMask: Int) -> SKShapeNode |
It’s off to a pretty good start. Adding health, enemies and eventually some core hacky-slashy mechanic will be next on the list!