<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Johan Steen on Medium]]></title>
        <description><![CDATA[Stories by Johan Steen on Medium]]></description>
        <link>https://medium.com/@johansteen?source=rss-2550414c666e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Ccyu3r5rd01ohZ5l.</url>
            <title>Stories by Johan Steen on Medium</title>
            <link>https://medium.com/@johansteen?source=rss-2550414c666e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:38:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@johansteen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SpriteKit Safe Area]]></title>
            <link>https://medium.com/@johansteen/spritekit-safe-area-e44f50fabada?source=rss-2550414c666e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e44f50fabada</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[gamedev]]></category>
            <category><![CDATA[spritekit]]></category>
            <dc:creator><![CDATA[Johan Steen]]></dc:creator>
            <pubDate>Fri, 24 Mar 2023 09:43:51 GMT</pubDate>
            <atom:updated>2023-05-09T07:20:49.324Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Handle the screen’s safe areas with collapsing margins in a SpriteKit SKScene.</em></p><figure><img alt="SpriteKit Safe Area" src="https://cdn-images-1.medium.com/max/1024/1*otYwMEP5Fw-CyPMbpx_GkQ.png" /></figure><p>To ensure that no important elements are obstructed on devices with notches or curved corners, the screen’s safe area values are available to help with the layout. When building an app with SwiftUI, AppKit, or UIKit, taking safe areas into account is quite simple and straightforward.</p><p>As the story usually goes with SpriteKit, it is not as simple out of the box, and we have to take a few extra steps to handle safe areas in a SKScene.</p><p>There are many ways to skin a cat, and here’s the workflow I’ve come up with that has worked very well for my SpriteKit projects.</p><p>I try to avoid having to make different versions of my code for different devices as much as possible, and that philosophy also applies when it comes to safe areas. To cover any scenario, I like to add collapsing margins combined with the safe areas, to have the content placed where I want it on all devices without any other modifications.</p><p>When there is no safe area, we are going to want to use a margin between the screen’s edge and the content. On devices with a safe area, the safe area will be used instead of the margin. Basically, we intend to collapse the margin with the safe area, to make the same setup work predictably enough on any device.</p><p>Let’s study a few examples to narrow it down, we’ll pretend that the circle shape represents an important HUD element that we want to place in the top left corner of the screen.</p><figure><img alt="Collapsed Margins on device with safe areas" src="https://cdn-images-1.medium.com/max/1024/0*DgeagSG5fJDFv2I9.jpg" /></figure><p>The version to the left illustrates what we’d get if we do nothing and just place the element in the top left corner. On a modern iPhone, a portion of the element will be obstructed by the rounded corner.</p><p>Most likely, we’d like to add a margin, and also use the safe area of the screen. If we were to put the element in a container with a margin for left and top edges, and then also use the safe area, we would end up with the middle scenario on a modern iPhone. We have a nice margin from the top, but on the left side we have both the safe area and the margin. In this case, it would most likely look the best to only use the safe area on the left side.</p><p>That leaves us with the version to the right, where the left margin is collapsed as there is a safe area, while we still use the margin on the top edge, as there is no safe area there.</p><figure><img alt="Margins on device without safe area" src="https://cdn-images-1.medium.com/max/1024/0*yjYP_8Px6SaenOed.jpg" /></figure><p>On a device with no safe areas, where the content would line up with the edge if we only used the safe area values, the margin will kick in on both the top and the left side.</p><h3>SKScene Safe Areas</h3><p>Before we get started, my workflow is based on the assumption that the SpriteKit scene adapts to the size based on the viewport, like I’ve lined out in a previous article, <a href="https://blog.bitbebop.com/spritekit-game-aspect-ratio-resolution/">Multiple Aspect Ratios and Resolutions with SpriteKit</a>. If you use another scaleMode for your projects, you might need to adjust accordingly.</p><p>With that out of the way, let’s get down to business. The hosting view for the SpriteKit scene, SKView, provides a safeAreaInsets property that inherited from UIView. While this provides all necessary information about the device safe areas, the values are not directly usable, as a SpriteKit scene has its own coordinate system and then scaled inside SKView. To get something usable in SKScene we are going to recalculate these values.</p><p>For our convenience, let’s extend SKScene and give it its own safeAreaInsets property. We are going to need a struct that can hold the SKScene specific values.</p><pre>extension SKScene {<br>  public struct SafeAreaInsets {<br>    public let top: CGFloat<br>    public let left: CGFloat<br>    public let bottom: CGFloat<br>    public let right: CGFloat<br><br>    public static var zero: SafeAreaInsets {<br>      SafeAreaInsets(top: 0, left: 0, bottom: 0, right: 0)<br>    }<br>  }<br>}</pre><p>This will allow us to have an API similar to the one provided via SKView, but with more relevant values for working with SpriteKit.</p><p>With the struct in place, we will have to figure out how much the SpriteKit SKScene has scaled in relationship to the hosting SKView. Let&#39;s add a property that calculates that information.</p><pre>fileprivate var scaleFactor: CGFloat {<br>  guard let view = view else { fatalError(&quot;Scene has no hosting view&quot;) }<br><br>  return size.height / view.frame.size.height<br>}</pre><p>We can now use the struct and the scaleFactor, to add the final property that will provide us with relevant safe area values for the SKScene.</p><pre>public var safeAreaInsets: SafeAreaInsets {<br>  guard let view = view else { return .zero }<br><br>  return SafeAreaInsets(<br>    top: view.safeAreaInsets.top * scaleFactor,<br>    left: view.safeAreaInsets.left * scaleFactor,<br>    bottom: view.safeAreaInsets.bottom * scaleFactor,<br>    right: view.safeAreaInsets.right * scaleFactor)<br>}</pre><p>If the scene has not yet been added to a view we return the shorthand static zero property of the SafeAreaInsets struct, else we multiply the view&#39;s safe area insets with how much the scene has scaled, to get safe area values that work as-is for the current SpriteKit scene.</p><p>To put it all together, we have ended up with this extension.</p><pre>extension SKScene {<br>  public struct SafeAreaInsets {<br>    public let top: CGFloat<br>    public let left: CGFloat<br>    public let bottom: CGFloat<br>    public let right: CGFloat<br><br>    public static var zero: SafeAreaInsets {<br>      SafeAreaInsets(top: 0, left: 0, bottom: 0, right: 0)<br>    }<br>  }<br><br>  fileprivate var scaleFactor: CGFloat {<br>    guard let view = view else { fatalError(&quot;Scene has no hosting view&quot;) }<br><br>    return size.height / view.frame.size.height<br>  }<br><br>  public var safeAreaInsets: SafeAreaInsets {<br>    guard let view = view else { return .zero }<br><br>    return SafeAreaInsets(<br>      top: view.safeAreaInsets.top * scaleFactor,<br>      left: view.safeAreaInsets.left * scaleFactor,<br>      bottom: view.safeAreaInsets.bottom * scaleFactor,<br>      right: view.safeAreaInsets.right * scaleFactor)<br>  }<br>}</pre><h3>First Scene Gotcha</h3><p>When the first scene is presented, SKView has not yet got the SafeAreaInsets and returns 0 for all edges. Once the view is displayed, the inset updates to the correct values.</p><p>For every following scene being presented, the view will have the correct values right away. If the first scene presented does not need to care about safe areas, it could likely be a loading scene where safe area play no part, then this gotcha is really nothing to care about.</p><p>In the case where the first presented scene needs to care about safe areas, that can be resolved by extending SKView.</p><pre>extension SKView {<br>  override open func safeAreaInsetsDidChange() {<br>    scene?.didChangeSize(scene!.size)<br>  }<br>}</pre><p>Once the system provides the app with the safe area values, safeAreaInsetsDidChange will be triggered in SKView. We hook in to that method to notify the presented scene about the change.</p><pre>override func didChangeSize(_ oldSize: CGSize) {<br>  super.didChangeSize(oldSize)<br>  layoutScene()<br>}</pre><p>In the presented scene, we can then use didChangeSize once the SafeAreaInsets becomes available, so the scene has a chance to do its positioning of elements there to ensure the layout for the first presented scene will look correct on all devices.</p><p>If the game supports both portrait and landscape mode, this should probably be handled in every scene to adjust the layout if the player rotates the device.</p><h3>Collapsing Margins</h3><p>Now, let’s take a look at handling margins. Let’s say that we have a player card that should be placed in the top left corner. To simplify things, let’s say that we have set the anchor points of our scene to have the top left corner at (0, 0).</p><pre>override func didChangeSize(_ oldSize: CGSize) {<br>  super.didChangeSize(oldSize)<br><br>  let leftOffset = safeAreaInsets.left<br>  let topOffset = safeAreaInsets.top<br><br>  playerCard.position = CGPoint(<br>    x: leftOffset,<br>    y: -topOffset<br>  )<br>}</pre><p>By placing the card using the safe area values to offset the asset from the edges of the screen, we are ending up with this as a result.</p><figure><img alt="Safe area and device orientation without collapsing margins" src="https://cdn-images-1.medium.com/max/1024/0*lVA-XkRCOsg5O6wU.jpg" /></figure><p>When we display the scene in portrait mode, we get an offset from the top of the screen, while we have no margin on the left side. When rotating the screen to landscape mode, we instead get an offset on the left edge of the screen, but we now have no margin at the top.</p><p>So what we want to do is this:</p><ul><li><strong>Portrait mode:</strong> Left edge use margin, top edge use safe area.</li><li><strong>Landscape mode:</strong> Left edge use safe area, top edge use margin.</li></ul><p>This can easily be accomplished by using max(), let&#39;s expand the layout code from before by adding a margin of 16.0 and then using max to collapse it with the safe area.</p><pre>override func didChangeSize(_ oldSize: CGSize) {<br>  super.didChangeSize(oldSize)<br><br>  let margin = 16.0<br>  let leftOffset = max(margin, safeAreaInsets.left)<br>  let topOffset = max(margin, safeAreaInsets.top)<br><br>  playerCard?.position = CGPoint(<br>    x: leftOffset,<br>    y: -topOffset<br>  )<br>}</pre><p>With this change we are ending up with something that looks much healthier where we have a margin kicking in when there is no safe area available.</p><figure><img alt="Safe area and device orientation cith collapsing margins" src="https://cdn-images-1.medium.com/max/1024/0*ArEQOLXF4pOS8EKI.jpg" /></figure><h3>Conclusion</h3><p>I hope this approach can serve as a start to get a solid foundation for how to handle safe areas and margins for content living near the edges of the screen. See this as a starting point and spur ideas how to take this further to set up a layout and positioning system with SpriteKit. As a first next step, I can definitely see the collapsing of margins being automated into a property or method.</p><p><em>Originally published at </em><a href="https://blog.bitbebop.com/spritekit-safe-area/"><em>https://blog.bitbebop.com</em></a><em> on March 24, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e44f50fabada" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Game Event System with Swift]]></title>
            <link>https://medium.com/@johansteen/game-event-system-with-swift-b350273f4918?source=rss-2550414c666e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b350273f4918</guid>
            <category><![CDATA[gamedevhq]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[gamedev]]></category>
            <dc:creator><![CDATA[Johan Steen]]></dc:creator>
            <pubDate>Mon, 30 May 2022 12:05:00 GMT</pubDate>
            <atom:updated>2023-05-09T07:24:06.142Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Build an event system with Swift for a highly modular game architecture using isolated game systems without hard dependencies.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hsd7d2ABPD4nwODA.jpg" /></figure><p>A game can usually be broken down into different systems, which are the building blocks of the game’s architecture.</p><p>One system could manage the on screen HUD, another the player, a third the enemies, and so on, and all these systems need to communicate with each other in one way or another. It is very easy to end up with a dependency nightmare between the different game systems.</p><h3>Dependency Nightmare</h3><p>We begin with an example of a problematic architecture, one that we are going to try to avoid by using game events for a more modular approach.</p><p>Let’s say that we have an enemy entity that we want to test in isolation to save some time. There’s really no need to startup the entire game world to see the animations, how the enemy responds to certain interactions, or similar things. So we are going to use a barebone scene where we can drop in an enemy entity and to be able to do some quick tests in a live environment.</p><p>We setup the barebone scene and add some initialization code to instantiate our enemy. But it won’t compile; the enemy entity depends on the existence of the EnemyManager.</p><p>So we also instantiate the EnemyManager in our test scene and give it another go. Won&#39;t compile again, the EnemyManager can&#39;t find the Player, a dependency that is used to let enemies make their AI decisions.</p><p>Okay, so we are adding the player to the test scene too. And let’s run it.</p><p>Ouch, the Player needs the InventoryManager. Okay, let add that one as well. And go! Nooooooo! The player also needs the HUDManager.</p><p>Eventually we’ve pretty much rebuilt the entire game architecture inside what was supposed to be our lean and mean debug scene.</p><h3>Game Events</h3><p>Which brings us to events. By using events to communicate between the game’s different systems, we get a much more decoupled architecture. When a system raises an event, it doesn’t care who listens to it, and a system that listens for an event doesn’t care who raised it.</p><p>This makes it very easy to take out any object from the game and drop it in an isolated environment or scene and it will pretty much work right away. And we can decorate our test scene with event triggers so we can trigger any event we want on demand and observe the behavior, without actually having to add the system that would trigger the event in the game.</p><p>This architecture helps us get rid of hard dependencies between our game’s systems.</p><p>And of course, when it comes to the actual gameplay scenes, the more decoupled and isolated our systems are, the more reusable the systems will become for future projects, and as a bonus, way easier to debug and test.</p><h3>Observers vs Broadcasters</h3><p>When it comes to handling events, there are primarily two design patterns that are highly popular, either using observers or broadcasters with listeners.</p><p>I’ve implemented and used both approaches in different projects, and while I like many things about the observer pattern, it relies on dependencies between objects in one way or another. Which is what we are trying to avoid.</p><p>I’ve used solutions similar to this.</p><pre>class HealthComponent: GKComponent, Observable {<br>  private(set) var health: Int {<br>    didSet { notifyObservers(with: .entityHealthChanged) }<br>  }<br>}</pre><p>And then, the HUD can observe the health component to instantly update the health bar whenever the player’s health changes. But this requires that the HUD is aware of the player object, to register with it, which gives us a hard-wired dependency.</p><p>So I personally rarely use this pattern anymore, and instead I most of the time rely on broadcasting events and having listeners, which provides a much more decoupled architecture.</p><p>The drawback can be that it can be harder to read and follow the event flow in code when there are no hard connections between the systems. Someone new to the code base would have to spend some time looking up and finding out what is listening to what events, as the compiler can’t help with that.</p><p>I now handle that by logging events when running the game in debug mode, so I can at any time request the log and see what events that were triggered, and which objects that responded to each event. That more or less take care of that drawback.</p><h3>Implementation</h3><p>That was a lot of background and theory, but now when we have decided that we want to broadcast events between systems, let’s look at how we can implement that functionality in Swift. We are going to make our own implementation as we want maximum performance. We don’t want to rely on NotficationCenter or other built-in solutions that are <a href="https://stackoverflow.com/a/28309749/1152087">less performant</a> than what we can build ourselves.</p><h3>Event Channels</h3><p>We are going to use event channels that we broadcast on, and pass along any relevant data. Interested parties can listen to channels of interest and react to events.</p><p>So we are going to setup an Event class that each event channel that we create will instantiate and be available for systems to broadcast on or listen to.</p><pre>public class Event&lt;T&gt; {<br>}</pre><p>We are going to use Swift generics for this class, when we define an event channel we also determine with the generic what kind of data we will pass along with the event.</p><pre>let enemyDestroyedEvent = Event&lt;Enemy&gt;()</pre><p>Here we create an enemyDestroyedEvent channel where we will pass along an instance of an Enemy object. When an enemy is destroyed the enemy will broadcast and pass along itself on this channel just before it removes itself from the game.</p><p>A number of other systems might listen to this event; the audio system could take the Enemy object and determine which sound effect to play; the UI system shows a score floating for a short period of time where the enemy was destroyed. The VFX system instantiates an explosion animation on screen at the enemy’s last position.</p><p>Our Event class is going to need to store a collection of listeners for each channel so the channel knows which objects that should be notified when the event is raised.</p><pre>public typealias EventAction = (_ subject: T) -&gt; Void<br><br>/// Listener wrapper to be able to use a weak reference to the listener.<br>private struct Listener {<br>  /// Weak reference to the listener.<br>  weak var listener: AnyObject?<br><br>  /// Action closure provided by the listener.<br>  var action: EventAction<br>}<br><br>private var listeners: [ObjectIdentifier: Listener] = [:]</pre><p>We don’t want to risk that the event channel keeps the object alive if the object is removed from the game, so we use a Listener struct as a wrapper around the object that listens, so we can have a weak reference to the listener. We are using ObjectIdentifier as the key for the listener, so it&#39;s easy to find the listener in the collection if we need to remove it.</p><p>The EventAction typealias gives us some sugared syntax.</p><p>Now we have a place to store the listeners for an event channel, so let’s add some methods so objects can let the channel know that they want to listen for events.</p><pre>/// Register a new listener for the event.<br>public func addListener(_ listener: AnyObject, action: @escaping EventAction) {<br>  let id = ObjectIdentifier(listener)<br><br>  listeners[id] = Listener(listener: listener, action: action)<br>}<br><br>// Unregister a listener for the event.<br>public func removeListener(_ listener: AnyObject) {<br>  let id = ObjectIdentifier(listener)<br><br>  listeners.removeValue(forKey: id)<br>}</pre><p>Thanks to the solid structure where we store the listeners, the addListener(), and removeListener() methods become very straightforward. We basically just have to get the ObjectIdentifier for the listener and add/remove it from the collection.</p><p>And finally, we are going to need a method to broadcast events to listeners.</p><pre>/// Raise the event to notify all registered listeners.<br>public func notify(_ subject: T) {<br>  for (id, listener) in listeners {<br>    // If the listening object is no longer in memory,<br>    // we can clean up the listener for its ID.<br>    if listener.listener == nil {<br>      listeners.removeValue(forKey: id)<br>      continue<br>    }<br><br>    listener.action(subject)<br>  }<br>}</pre><p>Here we raise the event to iterate through the collection of listeners to notify them. As we used a weak reference to the listener to not keep them alive if they are removed from the game, we also check here so the listener is still around. If it’s not, we take the opportunity to clean up the collection by removing it.</p><p>And that’s it; this class gives us everything we need to broadcast and listen to events.</p><h3>Using Event Channels</h3><p>That leaves us with how to use the event channels when we need to communicate between the game’s different systems. There are many approaches to choose from. I prefer to use a GameEvent singleton as a communication central where I define all channels that the game uses.</p><pre>class GameEvent {<br>  static let shared = GameEvent()<br>  private init() {}<br><br>  // Event Channels.<br>  let scoreChangedEvent = Event&lt;GameData&gt;()<br>  let livesChangedEvent = Event&lt;GameData&gt;()<br>  let enemyDestroyedEvent = Event&lt;Enemy&gt;()<br>  let playerDamagedEvent = Event&lt;HealthComponent&gt;()<br>}</pre><p>This is the place where I’m collecting and organizing all event channels that the game will need, and by exposing it as a singleton, I can simply use it from anywhere in the game code.</p><p>For an object to register itself as a listener, we would use the addListener() method in the event channel.</p><pre>class AudioComponent: Component {<br>  init() {<br>      GameEvent.shared.playerDamagedEvent.addListener(self) { [weak self] _ in<br>        self?.onPlayerDamaged()<br>      }<br>  }<br><br>  func onPlayerDamaged() {<br>    // Play the sound effect when player is taking damage.<br>  }<br>}</pre><p>We have a component that handles playing sound effects. By having it listen to the playerDamageEvent it can play the appropriate sound effect every time the player is damaged. Also, the health bar in the HUD would listen to this event and maybe also an animation component that would play a damage animation, and possibly emit some particles.</p><p>To be useful, events must also be raised.</p><pre>class HealthComponent: Component {<br>  func takeDamage() {<br>      // Do some other damage related things...<br><br>      GameEvent.shared.playerDamagedEvent.notify(self)<br>  }<br>}</pre><p>Which is more or less self-explanatory. This would be the health component for the player that raises the event every time the player takes damage, so other systems can react to it. The component passes along itself with the event, so listeners that relies on data in the health component can do so. The HUD most likely is going to check the health percentage for the component when the visuals on screen are updated.</p><h3>Conclusion</h3><p>This is my preferred way to pass data between game systems and I find it highly powerful and flexible. The complete decoupling between objects provides possibilities for very interesting solutions. As an object is not aware, care, or even interested in what listens to its events, you can wire up pretty much anything with anything.</p><p>With that in mind, each game component can be kept very clean and only focus on one thing. The health component only needs to track health; everything else in the game that depends on health is handled by other systems, more relevant for the separate purpose, and events are the delivery mechanism between them.</p><p>The UI is driven by events from the health component; a destroy component is driven by the same events. An audio component can also listen to the event in question. Anything that makes sense can listen to events, without having to introduce a dependency between objects.</p><p>But don’t forget… With great power comes great responsibility.</p><p><em>Originally published at </em><a href="https://blog.bitbebop.com/game-event-system-swift/"><em>https://blog.bitbebop.com</em></a><em> on May 30, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b350273f4918" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Game Center Achievements with Swift]]></title>
            <link>https://medium.com/@johansteen/game-center-achievements-with-swift-3a5a015f9828?source=rss-2550414c666e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a5a015f9828</guid>
            <category><![CDATA[gamecenter]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[gamedev]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[gamedevhq]]></category>
            <dc:creator><![CDATA[Johan Steen]]></dc:creator>
            <pubDate>Sun, 08 May 2022 04:04:00 GMT</pubDate>
            <atom:updated>2023-05-09T07:27:20.753Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Use Swift to manage Game Center Achievements and report progress with decoupled condition logic.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zsxLk2Uuoc5tqVtb.jpg" /></figure><p>I start early on in the development of a game to think about achievements and make notes during the development progress whenever I add something to the game that could also add some sort of additional challenge for the player in one way or another, to make it into a possible candidate to become an achievement.</p><p>Implementing achievements in a game is a great way to add some additional fun things to do in the game, and to give players more enjoyment. To be able to collect an achievement is an opportunity to make the players feel good while playing, and not only to keep grinding to collect points towards a new high score.</p><p>Achievements can also be used as hints and help to direct the player to try unusual things or to find some hidden area or mechanic they might not have found out about.</p><p>As a gamer myself, I do enjoy spending some extra time in games I buy to keep collecting achievements, event after I have beaten the game.</p><p>All in all, achievements can help to add some extra playtime to the game and give some extra joy to the players, which makes me feel its worth the extra time to implement some meaningful achievements for the players to collect.</p><p>When I did my first implementation, I immediately saw the danger that the logic to check for achievement progress could add some serious code pollution. I wanted to come up with an approach to keep it as decoupled as possible from the actual game code.</p><h3>Game Center for Progress Storage</h3><p>Also, I did not want to worry about storing progress myself, but instead delegated that responsibility to Apple and Game Center. By letting Game Center be the only source of truth for the player’s progress, players get progress synced between all their devices as a bonus. So a player who progresses towards an achievement on the iPhone, will see the same progress advancement when opening up the game on the Apple TV.</p><p>The only drawback with this solution is that Game Center only stores integers, while a custom solution could track floats and have much more fine-grained tracking towards a goal if needing more than 100 steps.</p><p>I found the convenience of not having to store things myself and not having to make a custom iCloud-based sync solution more important, than being able to have other value types for more fine-grained progress tracking.</p><h3>The Achievement Logic</h3><p>I came up with an approach where I make a class for each achievement in the game, and let the class contain the unique logic to track the progress of that achievement.</p><p>Doing it this way, I can keep all the achievement logic code contained completely separate from the rest of the game code. The game code should only need to worry about when to let the achievement know when it’s time to run its logic.</p><p>To handle this, I’m inheriting from GKAchievement to add some additional logic while still being able to piggyback on the functionality to read from and report back the progress to Game Center using only one object.</p><pre>class BaseAchievement: GKAchievement {<br>  /// Determine if the achievement has unreported progress.<br>  var isDirty: Bool = false<br><br>  /// Increase progress towards getting the achievement.<br>  func progress() {<br>    // If achievement is already completed, no need to track progress.<br>    guard !isCompleted else { return }<br><br>    // Run the logic to update the percentage.<br>    updatePercentComplete()<br><br>    // Mark it as dirty.<br>    isDirty = true<br><br>    // Report immediately if achievement was completed.<br>    reportIfCompleted()<br>  }<br><br>  /// Logic to update the percentage completed.<br>  func updatePercentComplete() {<br>    fatalError(&quot;Should be overriden in subclass&quot;)<br>  }<br><br>  /// Report the achievement if it is completed.<br>  func reportIfCompleted() {<br>    if isCompleted {<br>      GameCenter.shared.report(achievement: self)<br>    }<br>  }<br>}</pre><p>My BaseAchievement class is the base for every achievement I add to the game. It gives us two additional features. First, a location for where to put the logic to track progress towards the achievement; and second, it handles deferred reporting.</p><p>Some achievements execute the progress logic quite often; for instance, an achievement to have destroyed maybe 5000 enemies could potentially run the logic in very short intervals. I don’t want the game to constantly connect to Game Center servers and report every single enemy. Instead, I defer that report to occur between game levels.</p><h3>Deferred Reporting</h3><p>Whenever the game trigger that progress towards an achievement has happened the progress() method is executed. Unless the achievement is already completed, the logic to update the progress happens, and the achievement is marked as isDirty.</p><p>By marking achievements that have progress happening as isDirty is how we later can determine which achievements that have had changes, and then batch report all of them in one go, instead of constantly reporting them one by one as progress happens.</p><p>The exception is if the progress has completed the achievements. If so, I want the report to happen right away with reportIfCompleted() so the player gets the achievement banner shown on screen at the very moment the achievement was completed.</p><h3>Progress Logic</h3><p>The updatePercentComplete() method is where the unique logic is located for each achievement. So when we make our achievements classes, this is the only method we need to implement for each achievement.</p><p>Let’s look at an achievement that will be awarded when the player has collected 100 upgrades.</p><pre>/// Upgrade the Weapon 100 Times.<br>class UpgradeAchievement: BaseAchievement {<br>  override func updatePercentComplete() {<br>    percentComplete += 1.0<br>  }<br>}</pre><p>This class increases progress by 1% each time the player collects an upgrade, and once it reaches 100%, the achievement will be completed. That won’t happen until after many game sessions, as one session might just be a few upgrades. But as mentioned, Game Center keeps track of the progress between sessions and also between devices.</p><p><em>As we execute code in this method, we could do any kind of logic required or any kind of conditions or comparisons for different achievement types.</em></p><p>Some achievements are one-shot achievements.</p><pre>/// Read the rules.<br>class LibrarianAchievement: BaseAchievement {<br>  override func updatePercentComplete() {<br>    percentComplete = 100.0<br>  }<br>}</pre><p>The player gets the librarian achievement for reading the game’s instructions page. There’s not really any progress to collect, so we set the achievement to 100% right away.</p><p>So, what to do when needing more fine grained progress tracking than 1–100?</p><pre>/// Destroy 1000 Drones.<br>class WhackDroneAchievement: BaseAchievement {<br>  override func updatePercentComplete() {<br>    percentComplete += 0.1<br>  }<br>}</pre><p>The above code could easily be mistaken for a solution, as we progress with 0.1% per event, and GKAchievement uses a double for the progress value, and by that we get 1000 levels. Which is sort of true. That is exactly what will happen locally.</p><p>Unfortunately, Game Center only stores integers on the server even though a double is reported. So if reporting 5.4, it will only store a 5.</p><p>So we can’t use Game Center to track progress with more than 100 steps. If we really needed to store more than 100 steps, we’d have to track locally and then report or track with a custom cloud saving if tracking over devices, and then report each time we reach a reportable progress of the achievement.</p><p>What I found, depending on how fast the achievement progresses, is that you many times can get away with tracking with floats locally and reporting the integer at the end of the session; it will work good enough. So, I will track with 0.1 units in the game and just accepts that if the player progress 3.9% only 3% will be recorded.</p><p>Progress will be tracked slightly slower than what the player actually does, but I believe it won’t be noticeable most of the time. It’s been good enough for the games I’ve been developing so far. It has to be some really major part of the gameplay for me to consider using a custom cloud-synced solution instead, just to get more reportable steps between devices. If not needing sync between devices, it would be a lot simpler to track progress locally between sessions before reporting progress.</p><h3>Triggering Achievement Logic</h3><p>Now we just need to trigger the execution of these classes. I wanted to have an as simple API as I possible could, so there would be a minimum of additional code to add to the game logic. I definitely wanted to use a dot syntax for the achievement names.</p><p>So I came up with this, using a singleton combined with a factory for the achievements, which gives us a syntax like this.</p><pre>// Record the achievement.<br>GameCenter.shared.progress(achievement: .librarian)</pre><p>The code that handles the game’s instruction page, has the above line of code to ensure the achievement gets handled.</p><p>When an enemy is destroyed in the game, when the state machine enters the destroyed state for the enemy, we can run something like this.</p><pre>// Progress towards achievement.<br>GameCenter.shared.progress(achievement: .bring_pain)<br>GameCenter.shared.progress(achievement: .whack_drone)</pre><p>Which records the progress towards two different achievements that are related to the event of a destroyed enemy. We don’t need any conditions on these calls. As soon as an achievement is completed, these calls return immediately.</p><h3>The Achievement Factory</h3><p>The GameCenter class is a singleton that we call the progress method on with the achievement in question whenever we need to record progress, using a dot syntax.</p><pre>GameCenter.shared.progress(achievement: .survivor)</pre><p>In turn, GameCenter passes on the request to record progress to the relevant achievement.</p><pre>func progress(achievement: Achievement) {<br>  Achievement.achievements[achievement]?.progress()<br>}</pre><p>To be able to do that with our achievement objects, I am using an enum that also has a factory and holds all achievement instances.</p><pre>/// Manages available Game Center achievements<br>enum Achievement: String, CaseIterable {<br>  case champion, collector, survivor, veteran<br>  case librarian<br>}</pre><p>This is what gives us the dot syntax so we get those clean and beautiful API calls from within our game code.</p><p>Moving on, we need our enum to hold instances of all our achievement objects. We need to populate each instance with the current data stored in Game Center and we need them to be ready to track progress happening at any time.</p><pre>/// Collection of objects for all available achievements.<br>static var achievements = [Achievement: BaseAchievement]()<br><br>/// Factory to make GKAchievement objects for Game Center IDs.<br>static func factory(achievement: Achievement) -&gt; BaseAchievement {<br>  let gkAchievement: BaseAchievement<br>  let id = achievement.rawValue<br><br>  switch achievement {<br>  case .champion: gkAchievement = ChampionAchievement(identifier: id)<br>  case .collector: gkAchievement = CollectorAchievement(identifier: id)<br>  case .survivor: gkAchievement = SurvivorAchievement(identifier: id)<br>  case .veteran: gkAchievement = VeteranAchievement(identifier: id)<br><br>  case .librarian: gkAchievement = LibrarianAchievement(identifier: id)<br>  }<br><br>  gkAchievement.showsCompletionBanner = true<br><br>  return gkAchievement<br>}</pre><p>We call the factory using the enum cases with dot syntax, and we get back an instance of the achievement object for the requested case. I’m pretty sure this could be done more dynamically so we don’t have to use a switch statement.</p><p>That’s something for future enhancements. But for now, when my games don’t have more than about ten or so achievements, this has worked out.</p><p>This factory is supposed to be called when we have achievement data returned from Game Center so we can populate each underlying GKAchivement with the current progress and the identifier the achievement has in the Game Center database.</p><p>I create the achievements in Game Center database using my enum cases as identifiers, so I can simply use the rawValue for each case to set the correct id for each achievement before I get a response from Game Center.</p><pre>/// Create a local GKAchievement object for each Game Center achievement.<br>static func initAchievements() {<br>  for achievement in Self.allCases {<br>    Self.achievements[achievement] = Self.factory(achievement: achievement)<br>  }<br>}<br><br>/// Update local achievements with values from Game Center.<br>static func updateAchievements(_ achievements: [GKAchievement]) {<br>  for gkAchievement in achievements {<br>    if let achievement = Achievement(rawValue: gkAchievement.identifier) {<br>      // Update percent completed.<br>      Self.achievements[achievement]?.percentComplete = gkAchievement.percentComplete<br>    }<br>  }<br>}</pre><p>I use these two methods to handle the collection of achievements. With init I can create achievements at any time without having to wait for a response from Game Center. By having unconnected achievements, makes the code work even if the player does not use Game Center, so I don’t need to have conditions for that.</p><p>The update method I can pass in an array of achievements and update the local copies in memory at any time with fresh data from Game Center.</p><h3>Reporting Achievement Progress</h3><p>During the startup of a game, where all different game systems are initialized, would be a good place to also sync up with Game Center and get the player’s stored progress for the game’s different achievements.</p><p>I use Game Center for other things too, like Leaderboard. So during the game’s authentication process with Game Center, I end the authentication by loading the progress, if authentication was successful.</p><pre>func loadAchievements() {<br>  Achievement.initAchievements()<br><br>  GKAchievement.loadAchievements { (achievements, error) in<br>    if let error = error {<br>      os_log(.error, log: .game_center, &quot;Error in loading achievements: %@&quot;, String(describing: error))<br>    }<br>    if let achievements = achievements {<br>      // Process the array of loaded achievements.<br>      Achievement.updateAchievements(achievements)<br>    }<br>  }<br>}</pre><p>So here is where we use the methods in the enum we created earlier. Before we ask Game Center for the achievement progress, we create an empty set of Achievement objects. The request is asynchronous and it can potentially take some time until we get a response, or maybe no response at all if the player is offline.</p><p>But if we have a successful response, we will use the update method from our enum so we have fresh data for the progress. If the player is offline, I’ve opted to not handle that case, and instead just not count progress for those sessions.</p><p>Depending on the game and importance of achievements, one could choose to store progress locally in that case, to sync up once the player is back online. In my case I have decided it’s not worth the effort for my more casual games. I might revise that thinking for future titles.</p><pre>/// Report a single achievement to game center.<br>func report(achievement: BaseAchievement) {<br>  report(achievements: [achievement])<br>}<br><br>/// Submit the achievement report to Game Center.<br>func report(achievements: [BaseAchievement]) {<br>  guard isEnabled else { return }<br><br>  var achievements = achievements<br><br>  // To follow best practices, remove achievements that has no new progress.<br>  achievements = achievements.filter({ (achievement) -&gt; Bool in<br>    return achievement.isDirty<br>  })<br><br>  // Reset the isDirty flag in achivements with progress.<br>  achievements.forEach { (achievement) in<br>    achievement.isDirty = false<br>  }<br><br>  // Submit the report to game center.<br>  GKAchievement.report(achievements) { (error) in<br>    if let error = error {<br>      os_log(.error, log: .game_center, &quot;Error in reporting achievements: %@&quot;, String(describing: error))<br>    }<br>  }<br>}</pre><p>And finally, we need to get updated data back to Game Center. I have two methods that handle reporting. The main one that takes a collection of achievement objects to report, and then for convenience I have a report method that takes a single achievement object and passes it on as a collection to the actual report method.</p><p>I use the convenience single achievement report method to report immediately during play time when an achievement completes, so the player gets an immediate response.</p><p>And between levels, I pass in the entire achievement collection to report progress on every achievement before the next level begins.</p><p>Before the GKAchievement.report() call happens, which is what triggers the communication with the Game Center servers, we do a bit of tidying up. This is all happening in the GameCenter singleton and first we check so the player has Game Center enabled. If Game Center for any reason can not be authenticated this will be set to false, and we will not attempt to report.</p><p>If the player uses Game Center and is online, we will move on. Next we check the isDirty flag we set in our achievement objects. So we can filter out any objects that have had no progress. Sending back objects without progress won&#39;t cause any issues with the data, but Apple recommends to only report objects that have had changes.</p><p>And that pretty much sums it up.</p><h3>Conclusion</h3><p>This is the approach I’ve come up with to interact with Game Center, and to collect my players’ progress towards the games different achievements while keeping the logic as separated as possible to avoid polluting the game’s code with achievement logic.</p><p>I’m always dabbling with and considering new and better approaches for my different game systems, and I’d love to hear if you have any other ideas or thoughts on how to improve on these concepts. Or if you have taken a completely different approach that I haven’t even thought of. If so, please let me know, don’t be a stranger.</p><p><em>Originally published at </em><a href="https://blog.bitbebop.com/game-center-gkachievement-swift/"><em>https://blog.bitbebop.com</em></a><em> on May 8, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a5a015f9828" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sprite Component in GameplayKit]]></title>
            <link>https://medium.com/@johansteen/sprite-component-in-gameplaykit-89c3b7f46076?source=rss-2550414c666e------2</link>
            <guid isPermaLink="false">https://medium.com/p/89c3b7f46076</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[spritekit]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[gamedev]]></category>
            <category><![CDATA[gameplaykit]]></category>
            <dc:creator><![CDATA[Johan Steen]]></dc:creator>
            <pubDate>Sun, 01 May 2022 04:04:00 GMT</pubDate>
            <atom:updated>2023-05-09T07:31:13.690Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Use a dedicated sprite component with GameplayKit using Swift to decouple rendering from transformations.</em></p><figure><img alt="Sprite Component in GameplayKit" src="https://cdn-images-1.medium.com/max/1024/0*ZgdTHR6d8VR4-_05.jpg" /></figure><p>Let’s continue our journey to get a few useful core components for GameplayKit built, that almost every game will have use for that we write in Swift and using Apple’s game frameworks.</p><p>Last time we looked at making a <a href="https://blog.bitbebop.com/gameplaykit-transform-component/">GameplayKit Transform Component</a>, so let’s pair that component up with a Sprite Component. A sprite and a transform component complement each other and provide a powerful, yet manageable, system to get things moving on screen.</p><p>By having a dedicated component for rendering the visuals of our entities, we get a clear separation of concerns between transformation and the visual representation.</p><h3>The Sprite Component</h3><p>To start off the sprite component, we will have an empty node that will serve as a root that holds one or many child nodes that make up the entity’s visuals.</p><pre>/// Handles visual representation of an `Entity`.<br>class SpriteComponent: GKComponent {<br>  /// The root node to add children that will be rendered in the scene.<br>  private let node = SKNode()<br>}</pre><p>This makes the sprite component completely stand alone. In my own production code I shared this with my transform component. If you’ve read my previous article about building a transform component, you might remember that we use an SKNode there to hold the transformation data. As every entity in my setup always has a transform component, my sprite component references the same SKNode.</p><p>But for simplicity, in the example we are building here, we will let the sprite have its own. But keep in mind that you can get a very lean and elegant setup by sharing that node between some of the core components.</p><h3>Sprite Properties</h3><p>Let’s move on to the basic properties, we are using Swift’s computed properties to wrap around some of the built-in properties of SKNode, and then we add a few additional properties on top of that.</p><pre>/// Computed property that manages the name of the root node.<br>var name: String? {<br>  get { node.name }<br>  set { node.name = newValue }<br>}<br><br>/// Computed property that manages the alpha of the root node.<br>var alpha: CGFloat {<br>  get { node.alpha }<br>  set { node.alpha = newValue }<br>}<br><br>/// Computed property that manages the zPosition of the root node.<br>var zPosition: CGFloat {<br>  get { node.zPosition }<br>  set { node.zPosition = newValue }<br>}</pre><p>To start it off, we basically wrap some common properties from SKNode that I&#39;ve found useful to be able to modify from other components that provide the unique behavior for the entity and are by that convenient to have exposed in the component.</p><p>Now let’s make it a bit more interesting.</p><pre>/// Determines if the node is visible in camera.<br>var inCamera: Bool {<br>  if let camera = scene?.camera {<br>    if let child = node.children.first {<br>      return camera.contains(child)<br>    }<br>  }<br><br>  return false<br>}</pre><p>I often need to know if an entity actually is in view or not and can make behavioral decisions for the entity based on that. I’ve found it incredibly useful to have an inCamera property available to always be able to check the current state for any entity in the game.</p><p>The next one is isHidden.</p><pre>var isHidden: Bool = false {<br>  didSet {<br>    node.isHidden = isHidden<br><br>    // Disable physicsbody while hidden to not trigger collisions.<br>    if isHidden {<br>      node.physicsBody = nil<br>    } else {<br>      if let physics = entity?.component(ofType: PhysicsComponent.self) {<br>        node.physicsBody = physics.physicsBody<br>      }<br>    }<br>  }<br>}</pre><p>This could also be a simple wrapper around the property in SKNode as the first 3 properties were. As many of my entities also have a physics component with a physics body attached to them, I&#39;ve found this to be the best location to handle that too.</p><p>Setting a sprite to hidden, does not disable its physics body. So by hooking into didSet in the isHidden property we can handle enabling and disabling the physics for the entity here, so that is taken care of automatically when we need to hide our entities for one reason or another.</p><p>PhysicsComponent is part of my core components that I include in every game, so I can pretty much assume in my other core components that the component exists.</p><h3>Layering the Sprites</h3><p>Another crucial part of working with sprites is depth sorting to let SpriteKit know, in which order to stack overlapping sprites on screen.</p><p>I’ve learned the hard way that manually assigning values to zPosition for each sprite is a sure way towards losing track of the sorting order. Instead I prefer using a Swift enum to setup predetermined sprite layers.</p><pre>/// The names and zPositions of layers in the game scene.<br>enum GameLayer: CGFloat {<br>  case bullet       = 400<br>  case pod          = 500<br>  case enemy        = 600<br>  case player       = 700<br>  case fx           = 800<br>  case hud          = 1000<br>  case debug        = 1500<br>  case touchControl = 2000<br>  case overlay      = 3000<br>}</pre><p>By using enum cases for the sprites, I ensure that a certain entity type gets consistent depth positioning, and if I want to reorder the layers, I can simply update the enum instead of having to go through every single affected entity. I might want to move bullets to be in front instead of being behind the player, which I can do directly in the enum.</p><p>The constructor of the sprite component takes GameLayer as its signature.</p><pre>init(layer: GameLayer) {<br>  super.init()<br>  node.zPosition = layer.rawValue<br>}</pre><p>We use that when we instantiate a sprite component in an entity.</p><pre>let sprite = SpriteComponent(layer: .fx)</pre><p>We pass in the game layer, using Swift’s dot syntax, to determine which layer the entity will be rendered on in our gameplay scene.</p><h3>The Life Cycle</h3><p>We are using the built-in life cycle of GKComponent that is called when the component is added and removed from an entity, to be able to do some relevant setup and cleanup.</p><pre>override func didAddToEntity() {<br>  super.didAddToEntity()<br><br>  // Assign the entity to the node&#39;s entity property.<br>  node.entity = entity<br><br>  // Set the sprite root as the entity&#39;s node for transformations.<br>  (entity as? Entity)?.transform.set(node: node)<br>}</pre><p>SKNode has an entity property that takes a reference to a GKEntity. To be able to get a reference to the entity directly from the sprite node is very convenient and useful.</p><p>So we use this location to assign our entity to SKNode so we can take advantage of that reference through the property.</p><p>Optionally, if planning to share the SKNode with the transform component, this would be a good place to handle that. In this example I update the transform component to use the node from the sprite component as the root for all transformations.</p><pre>override func willRemoveFromEntity() {<br>  super.willRemoveFromEntity()<br><br>  node.entity = nil<br>  node.removeAllActions()<br>  node.removeAllChildren()<br>  node.removeFromParent()<br>}</pre><p>Once it’s time to remove the entity and its components from the game, we are good citizens and clean up after ourselves. We remove the entity reference as we don’t want to cause any reference retain cycles. And then we stop any actions and clean up the sprite hierarchy.</p><p>That should let us leave the game world in the same pristine condition as when we entered.</p><h3>Sprite Component Methods</h3><p>With the sprite properties setup, and the life cycle management and initialization in place, we can start adding some useful methods to interact with the component.</p><p>First, we have the add() methods.</p><pre>/// Adds a node as a child to the Sprite&#39;s root node.<br>func add(node: SKNode) {<br>  self.node.addChild(node)<br>}</pre><p>This is the essential method to actually get some visuals assigned to the sprite component. I use this method to pass in the sprite to render in the component.</p><p>You can keep calling this method to stack up the visuals in side the component.</p><pre>let sprite = SpriteComponent(layer: .fx)<br>sprite.add(node: debris)<br>sprite.add(node: flame)<br>sprite.add(node: sparks)<br>addComponent(sprite)</pre><p>In the example above, when I define an entity for an explosion effect, I push in 3 different layers to my sprite node to build the entity’s visuals.</p><p>Then I’ve recently come to like to have an additional add(to:) method.</p><pre>/// Adds the sprite as a child to provided node.<br>func add(to node: SKNode) {<br>  node.addChild(self.node)<br>}</pre><p>The essential add method doesn’t build a hierarchy, and I’ve had a few cases where I need to keep nesting, and then this method does the trick of adding that option to the component.</p><p>And finally, we need to be able to adjust the hierarchy during runtime.</p><pre>/// Moves provided node from its previous parent to be a child of this root node.<br>func move(child node: SKNode) {<br>  node.move(toParent: self.node)<br>}<br><br>/// Moves the root node to be a child of the provided new parent node.<br>func move(to parent: SKNode) {<br>  node.move(toParent: parent)<br>}<br><br>/// Moves the root node to be a child of the root node in another entity.<br>func move(to parent: Entity) {<br>  // Get the SpriteComponent of the Entity to move to.<br>  if let sprite = parent.component(ofType: SpriteComponent.self) {<br>    // Move this root node to be a child of the other entity&#39;s root node.<br>    sprite.move(child: node)<br>  }<br>}</pre><p>The first two move methods are simply wrapping around the move method in SKNode which are useful to change the hierarchy on demand.</p><p>Then we have our own more unique move method where we can move the visuals to another Entity. So we pass in the other entity, get a reference to that entity’s sprite component, and then move our complete visual hierarchy to that entity instead.</p><p>I initially thought this was a special case scenario when I needed it in one game. But when I’ve started new projects, I’ve kept reaching for this method, so I’ve decided to make it a permanent member of the sprite component.</p><h3>Conclusion</h3><p>To place the game visuals in a dedicated sprite component helps separate concerns and keep the code decoupled.</p><p>Theoretically we should be able to add a Swift protocol for rendering, RenderingProtocol, that the sprite component would conform to and we should then be be able to implement a mesh component and swap the game play over to using 3D meshes instead of sprites, without having to modify any other logic in our game entities. Well, theoretically.</p><p>Anyway, to have a dedicated component for the sprite, we get a logical place where to house things like the in camera property.</p><p>Continuing on, the sprite component would pair up nicely with an animation component that would manage animating the textures or handling flip book like animations on top of the sprite component.</p><p>And of course, a physics component that manages the physics properties of the entity and that grabs a reference to the sprite component to add and remove itself to the physicsBody property of the root node of the sprite component.</p><p><em>Originally published at </em><a href="https://blog.bitbebop.com/swift-gameplaykit-sprite-component/"><em>https://blog.bitbebop.com</em></a><em> on May 1, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89c3b7f46076" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Game Input System in Swift]]></title>
            <link>https://medium.com/@johansteen/game-input-system-in-swift-237cef5f8da6?source=rss-2550414c666e------2</link>
            <guid isPermaLink="false">https://medium.com/p/237cef5f8da6</guid>
            <category><![CDATA[gamedev]]></category>
            <category><![CDATA[game-controllers]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Johan Steen]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 08:42:00 GMT</pubDate>
            <atom:updated>2023-05-09T07:34:48.393Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Build a rock solid and reusable game input system in Swift. It works with all of Apple’s game frameworks and is device agnostic.</em></p><figure><img alt="Game Input System in Swift" src="https://cdn-images-1.medium.com/max/1024/1*dmCgVvsnlMWcsR4XmZbWaQ.jpeg" /></figure><p>Handling player input can be disproportionally difficult. One could think writing complex game algorithms would be the biggest challenge when it comes to game development. Writing an input system that can handle anything from touch to game controllers, mouse and keyboards combined with different devices and operating systems can be a whole mess of edge cases, gray hair, and trial and error.</p><p>I decided to come up with a system once and for all that I could simply drop in to new game projects together with a configuration for how I want the input to work for that game, and then be done with it.</p><p>These are the goals I wanted to achieve with the input system.</p><ul><li>Completely decoupled from the game code.</li><li>Highly reusable, preferably a separate package.</li><li>Handle any kind of input device or screen.</li><li>Work for both UI and Gameplay.</li><li>Game code should not depend on which input is currently being used.</li><li>Handle game controllers with relevant related events.</li><li>Not be tied to a specific game framework.</li><li>Have a “swifty” feel when configuring a game’s input.</li><li>Layout system to define touch input virtual controller.</li><li>Apply custom artwork for thumbsticks and buttons in the virtual controller.</li></ul><p>We want to achieve a system that under the hood takes care of all the input handling and completely abstracts it away from the game.</p><p>That is an end to switch or if conditions that checks for keypresses, mouse buttons, touch input and other devices wired up in the actual game code. It should also automatically handle game controller detection and all related events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*DtbgTNURKm7PBFfM.jpg" /></figure><p>And of course, we are also going to want to ensure that the input system handles everything required to have the Game Controllers supported badge in Apple’s App Store.</p><h3>Game Input Actions</h3><p>After trying some different concepts and ideas, I ended up going with an action-based approach. The concept is that the game polls or listens to actions instead of directly having to check for device input.</p><p>Examples of actions can be “Jump” or “Move”. The game only has to care about if a “Jump” action happened, and does not need to know what button or device that triggered the action to happen.</p><p>The game defines a list of actions it needs for its gameplay and then the input system generates the actions for the game.</p><p>When setting up a new game, each device the game supports is configured how it triggers the actions in the appropriate way for that kind of device.</p><p>Once implemented, I’ve found this to be a solid approach for a highly decoupled system that ends up with very clean and easy maintainable code when used in a game project.</p><h3>Game Input Groups</h3><p>With the concept of Input Actions for a game, we have immediately solved many of the initial list of bullet points that I wanted to achieve.</p><p>We have decoupled the input code from the game code so it can be reused and not tied specifically to a certain game framework. As the game only cares about actions, it does no longer depend on which device is currently generating the input.</p><p>Next, we want to solve different input scenarios. A thumbstick or a D-pad on a game controller might need to be associated with more than one action. During gameplay it is associated with a “Move” action, while when we are displaying a UI to the player we want it to be associated with a “Navigation” action.</p><p>This is the requirement that the system should work for both the UI and Gameplay. We handle that by introducing Input Groups.</p><p>Each action will belong to a group, and only one group can be active at a time. And by switching which input group that is currently active, we can immediately change the input behavior of the game.</p><p>We can have one group of actions for the UI and one group of actions for the gameplay. Then we can simply switch between the UI and Gameplay groups depending on which state the game is in.</p><p>I like to use an approach where I have a finite state machine that tracks the overall game state. By default I set the input system to UI and then I use the enter and exit transitions for my Gameplay state to change the input group. Whenever the game enters GameplayState I enable the Gameplay input group and whenever it exits GameplayState I enable the UI input group.</p><h3>Configure the Input System</h3><p>Now we have an idea of how the input system should work. Now it’s time to deal with the “Swifty” configuration. It was very important for me to come up with an API that I felt comfortable with. Maybe one of the most important aspects of the system, as I wanted it to feel logical and easy to setup the input for each new game.</p><p>I decided on using one struct, InputConfig, that I will add to each game and this strict will hold the entire input configuration for the game by binding devices with actions.</p><p>So during the game’s initialization, preferably when my GameManager starts up, I&#39;ll simply have to create the config, and then the game is ready to use the actions.</p><pre>final class GameManager {<br>  init() {<br>    // Configure input mapping.<br>    InputConfig()<br>  }<br>}</pre><p>We’ll keep it simple, all right.</p><p>Then let’s take a look at how we define the struct with all the game input mappings. I start by defining the input groups and input actions the game will use.</p><pre>/// Registers all input actions for the game.<br>struct InputConfig {<br>    // `Input Group` identifiers.<br>    static let gameplay: String = &quot;Gameplay&quot;<br>    static let ui: String = &quot;UI&quot;<br><br>    // `Input Action` identifiers.<br>    static let moveAction = &quot;move&quot;<br>    static let fireAction = &quot;fire&quot;<br>    static let jumpAction = &quot;jump&quot;<br>    static let pauseAction = &quot;pause&quot;<br><br>    static let menuNavigate = &quot;menu navigate&quot;<br>    static let menuSelect = &quot;menu select&quot;<br>    static let menuExit = &quot;menu exit&quot;<br><br>    #if DEBUG<br>    static let debugKill = &quot;debug kill&quot;<br>    static let debugNextLevel = &quot;debug next level&quot;<br>    static let debugDropItem = &quot;debug drop item&quot;<br>    #endif<br>}</pre><p>I initially wanted to be able to use an enum for the identifiers, but I couldn’t come up with a solid solution when the config also needs to be accessible and parsed by the separate input package. By using static let we overcome that while still being able to reference them by dot syntax, so we can for instance listen to .moveAction.</p><p>In the above example we define two groups that we are going to use, then four different gameplay actions, three UI actions, and finally some additional actions only included in DEBUG builds that can be useful during play testing.</p><p>This covers everything this example game is supposed to be able to do.</p><p>Up next, we are going to map our actions to different devices. Let’s check out the .moveAction bindings.</p><pre>let moveAction = InputAction(name: Self.moveAction, type: .stick, bindings: [<br>    GamepadBinding(.leftStick),<br>    CompositeKeyBinding(keySet: .wasd)<br>])</pre><p>InputAction is a core class of my game input system and it does most of the heavy lifting to be the bridge between the game and the input devices. So the InputAction takes three parameters; we need an identifier, a type, and the bindings.</p><p>By identifying it with the static let name we defined earlier, we get an association between the input action and that name, so we later on always can refer to it with .moveAction syntax. Then we need to let the action know what kind of input control this is.</p><p>I’ve added four different types of control to my InputAction class at this time.</p><ul><li>.stick : A analog stick control like the thumbsticks on gamepads.</li><li>.button : A button expressed as a floating-point value.</li><li>.d-pad : A digital button control like the D-pad on gamepads.</li><li>.cursor : A position on the screen like a mouse pointer or Apple Pencil.</li></ul><p>Then we have the bindings, which I provide as an array. In this example I provide bindings for Game controllers and keyboards. Each binding type adopts to an InputBinding protocol and has its own custom set of possible controller elements relevant for that device binding.</p><p>The GamepadBinding has elements like .leftStick, .rightStick, .buttonNorth and so on.</p><p>While the keyboard has bindings for different keys like p or shift. For convenience I added a CompositeKeyBinding on top of KeyBinding as I found myself often needing that setup. So above I use a composite key binding and pass in the .wasd keys.</p><p>And of course, as it is an array, we can use multiple bindings from the same device type for one action. So to expand on the .moveAction.</p><pre>let moveAction = InputAction(name: Self.moveAction, type: .stick, bindings: [<br>  GamepadBinding(.leftStick),<br>  CompositeKeyBinding(keySet: .wasd),<br>  CompositeKeyBinding(keySet: .cursor)<br>])</pre><p>We now have a second composite binding with the cursor keys, so the player can use any of those keys, according to what they prefer. I use this in other places too, like the .pauseAction.</p><pre>let pauseAction = InputAction(name: Self.pauseAction, type: .button, bindings: [<br>  GamepadBinding(.buttonMenu),<br>  KeyBinding(key: &quot;p&quot;),<br>  KeyBinding(key: Character(UnicodeScalar(0x1b)))<br>])</pre><p>Here we assign pause to both the p key and to the esc key.</p><p>Another example with multiple bindings would be the UI navigation.</p><pre>let navigateAction = InputAction(name: Self.menuNavigate, type: .dpad, bindings: [<br>  GamepadBinding(.leftStick),<br>  GamepadBinding(.dpad),<br>  CompositeKeyBinding(keySet: .wasd),<br>  CompositeKeyBinding(keySet: .cursor)<br>])</pre><p>Here we are giving the player four different options that all work at the same time to navigate the game’s menu screens. And the system also handles using an analog left thumb stick as a directional pad input type, like in this case.</p><p>With all the different actions for the game configured, all that remains is to group them.</p><pre>// Assign the actions to an input group.<br>Input.shared.add(inputGroup:<br>  InputGroup(name: Self.gameplay, actions: [<br>    moveAction,<br>    jumpAction,<br>    fireAction,<br>    pauseAction<br>  ])<br>)</pre><p>The input system is at its core a singleton, so we easily can access it without having to create an instance. We use that to our advantage, so when the configuration adds its groups to the input system, the system gets automatically initialized and brought alive to start listening for input and invoking actions.</p><p>The game does not need to track an instance of its own for input handling. Setting up the config is all the game needs to do.</p><h3>Handling Touch Input</h3><p>In the previous example I didn’t touch on the subject of assigning any bindings for touch controls, no pun intended.</p><p>Binding actions to touch controllers works just the same. In the most basic setup, using the built-in default flat shapes as art, it would be added exactly like any other binding, with the addition of positioning the button on screen.</p><pre>let fireAction = InputAction(name: Self.fireAction, type: .button, bindings: [<br>  TouchButtonBinding(<br>    position: Position(<br>        horizontal: .right,<br>        vertical: .bottom<br>    )<br>  )<br>])</pre><p>While this works and the layout system takes things like margins and safe area into account, its still too limited. I want to be able to make much more custom layouts with custom artwork.</p><p>In a real scenario, I need a setup more like this, which is a controller from a game I’m currently working on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*xUX773xqQX66y0wq.jpg" /></figure><p>To make a layout like this happen, the TouchInputBinding struct have quite a few more parameters than the keyboard and mouse have.</p><p>Setting up the previous devices has turned out to be quite a nice and neat piece of configuration code that is easy to overview. I didn’t want to visually pollute the code with the touch bindings. So I added a method where I can add more bindings to an existing input action.</p><p>By that I can make a choice, if I want to add the touch input bindings together with the other devices, or tag them on separately at the end. So far I’ve always tagged them on separately, so I can deal with layout, art, and so on in the same location.</p><p>So in reality, when I do a full layout the configuration for a touch element will need an artwork reference, position, and size.</p><pre>// Size shared by all buttons.<br>static let buttonSize = CGSize(width: 32, height: 32)<br><br>// Setup the texture reference<br>let fireButtonGlyph = TouchControllerTexture(<br>  name: &quot;Fire Button&quot;, size: buttonSize,<br>  asset: .image(named: &quot;Fire Button&quot;))<br><br>  // Add the binding to an existing action.<br>  fireAction.add(<br>    binding: TouchButtonBinding(<br>      position: Position(<br>        horizontal: .right(buttonSize.width / 2),<br>        vertical: .top(buttonSize.height / 2)),<br>      button: TouchButton(<br>        symbol: fireButtonGlyph,<br>        background: TouchControllerTexture(<br>            name: &quot;&quot;, size: .zero, asset: .none),<br>        pressedColor: .white<br>  )))</pre><p>The layout system still has room for improvements and is not yet as sophisticated as it could be. On the top of my list is to add a rule system so one element can be placed in relation to another element, and specify a vector with an offset.</p><p>That would make tweaking and rearranging the layout much easier. But for now I’ve got by with these options where I can set the major screen location and then tweak that position that can take an additional adjustment value.</p><p>Every touch element can take a background texture, which I in this example do not use, as the element provided its own.</p><p>Once all elements are registered with the system, all assets are combined into one single texture in memory during runtime to reduce draw calls and batching for optimal performance.</p><h3>Using the Input System in a Game</h3><p>With the configuration done it’s time to use the actions in our game. This is where we get rewarded. Not only is it easy to use the actions from this point on, we can also remap actions to new buttons or add new bindings without having to touch any of the game code.</p><p>I prefer to use patterns in the line of delegates, so we are listening for events and don’t do any kind of processing until an event actually occurs.</p><p>In opposite to a polling system where we need to do some tiny processing on each update loop to see if an event has occurred.</p><p>I implemented both options in the input system as I find them both useful for different reasons. I want to listen to the action event once I’m done implementing an input-dependent feature. At the same time, I find it convenient to have a polling option when I just quickly want to test something without having to add code for delegates or listen to an event.</p><p>I also added support for analog events on everything. So I can always choose if I want to get a digital value or an analog value. That is, I can get a value that the button was pressed, or if needed I can also get the value of how hard the button was pressed.</p><p>Taking the .button input type as an example, we&#39;ve 3 possible states to query about.</p><ul><li>triggered: Triggered is set on the frame, the button is pressed down.</li><li>released: Released is set on the frame, the button is released.</li><li>value: Value always holds the value of how much the button is pressed down, in the 0.0 - 1.0 range.</li></ul><h3>Polling for Input Actions</h3><p>Let’s start by looking at an example where we poll an input action for an event.</p><pre>class InputComponent: Component {<br>  let fireAction = Input.shared.getAction(map: InputConfig.gameplay, name: InputConfig.fire)<br><br>  override func update(deltaTime seconds: TimeInterval) {<br>    if fireAction.triggered {<br>      // Do something...<br>    }<br>  }<br>}</pre><p>We grab a reference to the action we are interested in, then we use the game’s update loop to check the state of that action.</p><p>As soon as some form of input device makes the input system trigger a fire action event, our condition will be true and we can run the code relevant for a fire action in out game.</p><p>If I’m more interested in getting the analog value for an action I can use the getValue() method.</p><pre>if let fireValue: CGFloat = fireAction.getValue() {<br>  print(&quot;fire:&quot;, fireValue)<br>}</pre><p>Different input types return different value types. A .stick input will return a CGVector while a .button input will return a CGFloat. The getValue() method is a generic method, so we have to cast it to the type we expect the action to return.</p><h3>Listen for Input Actions</h3><p>Polling is nice and convenient to make quick tests or prototype things. In the end, listening to actions is what I most likely will use, which is also supported by the input system.</p><p>Each action can be assigned a delegate, so it’s actually more or less dead simple to set up a listener.</p><pre>class SomeComponent: Component {<br>  init() {<br>    Input.shared.getAction(map: InputConfig.gameplay, name: InputConfig.moveAction).delegate = moveDidChange<br>  }<br><br>  func moveDidChange(_ inputAction: InputAction) {<br>    let movement: CGVector = inputAction.getValue()<br><br>    // Do something with the movement value.<br><br>  }<br>}</pre><p>We get a reference back to the InputAction when the action is triggered, so we can cast and read the value and update our game state based on the input value.</p><h3>Switching Input Group</h3><p>And finally, we are going to look at switching groups. As discussed earlier, we most likely are going to want to switch between UI input and gameplay input whenever we change between a gameplay state and the other states the game can be in.</p><p>I prefer to handle that with a state machine for my game states.</p><pre>class PlayingState: GameSceneState {<br>  override func didEnter(from previousState: GKState?) {<br>    Input.shared.enableActionMap(name: InputConfig.gameplay)<br>  }<br><br>  override func willExit(to nextState: GKState) {<br>    Input.shared.enableActionMap(name: InputConfig.ui)<br>  }<br>}</pre><p>In this example we change the input group each time we enter and exit the playing state of the game. Easy!</p><p>And that’s all the code to get all the input setup in a game that I need. All the remaining code from dealing with game controllers to keyboards to actually handling input and interaction with devices, lives in my reusable Swift package.</p><h3>Under the Hood</h3><p>We have now looked at the concepts and ideas of how to make a rock-solid, decoupled and device-independent input system for games that is easy to interact with and setup from the game’s code base.</p><p>The actual inner workings that provide the different classes and value types we use are contained in my Game Input System Swift Package. To dive into the core of my library would be a bit too much for an article like this, we would turn it into a book.</p><p>Instead, I hope my walkthrough how I’ve set up my system. My thinking behind the different choices I made and how I interact with the system is enough so you can build an input system and fill in the blanks to build it in your own way with how you prefer to interact with your system.</p><p>And that my system can serve as a starting point to get your ideas flowing, and that you might get some insight to do things in ways you might not have thought of otherwise.</p><h3>The Core Structure</h3><p>My core structure is built around protocols and value types so I can easily extend it with new features and add new devices in the future.</p><p>The most important protocols, classes and value types that could be useful to consider if building an input system with a similar approach as I’ve done.</p><ul><li>InputDevice: This is a protocol that provides the basic ins and outs to communicate with any kind of input device. So any new device type implements this protocol and makes it possible for the system to interact with the device. So any class like Gamepad, Mouse or Touch adapts to this protocol and this is where the unique code is to translate between the device and the input system.</li><li>InputBinding: Is a protocol that holds a reference to the InputAction it belongs to and is adapted by Input devices to provide the unique elements. This is the bridge to how the input device passes along an event to an InputAction so the event can be triggered for the game to use. We have things like GamepadBinding and KeyInputBinding that provide their own unique implementation to bridge between the device and the action.</li><li>InputAction: This is the working class hero. This is where all device events end up; the values are processed and also transformed when necessary. For instance, there can be processing of input smoothing or calculation of analog values on digital-only devices based on time since triggered. This is where the game can query for current values and check the state of actions at any time.</li><li>InputGroup: This value type organizes and toggles the actions associated with the group.</li></ul><p>These four are the core functionality of the system. On top of them is the Input singleton that makes it easy to interact with the package, and that&#39;s pretty much it.</p><p>Then there are quite a lot of additional code to handle special cases like laying out the virtual touch input controller and everything related to that.</p><h3>Conclusion</h3><p>Making the gameplay logic and algorithms is the easy part of game development. Making input systems is hard, but it pays off and is well worth the time to get it done right.</p><p>Then there’s always the management of UI states… But that’s a story for another day.</p><p><em>Originally published at </em><a href="https://blog.bitbebop.com/swift-game-input-system/"><em>https://blog.bitbebop.com</em></a><em> on April 24, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=237cef5f8da6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transform Component in GameplayKit]]></title>
            <link>https://medium.com/@johansteen/transform-component-in-gameplaykit-29b394da1fa2?source=rss-2550414c666e------2</link>
            <guid isPermaLink="false">https://medium.com/p/29b394da1fa2</guid>
            <category><![CDATA[gameplaykit]]></category>
            <category><![CDATA[spritekit]]></category>
            <category><![CDATA[gamedev]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Johan Steen]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 05:08:00 GMT</pubDate>
            <atom:updated>2023-05-09T07:37:32.871Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Create a transform component for GameplayKit in Swift to get a clean and robust API for everything related to position, rotation, and scale.</em></p><figure><img alt="Transform Component in GameplayKit" src="https://cdn-images-1.medium.com/max/1024/0*vGyI2o1N2qJIMCM0.jpg" /></figure><p>In every new game project I have a few components which are part of my reusable core functionality that I always include. To have a set of GameplayKit based components that provide common functionality most games require can save a great deal of time once implemented.</p><pre>+-- Shared<br>  +-- Entities<br>  +-- Components<br>    +-- Core<br>          InputComponent.swift<br>          PhysicsComponent.swift<br>          RemoveComponent.swift<br>          SpriteComponent.swift<br>          TransformComponent.swift</pre><p>Last time we looked at implementing a <a href="https://blog.bitbebop.com/gameplaykit-remove-component/">GameplayKit Remove Component</a> and now the time has come to see how we can implement a transform component.</p><p>Almost every entity I create needs transformations in one way or another, so to have a rock-solid and robust transform component that is easily accessible everywhere where it makes sense, has turned out to be incredible helpful.</p><p>The purpose of the transform component is to give ourselves a clean and logical API that wraps around useful transform related functions similar to how the major game engines do it.</p><p>This will provide us with a system where the transform interaction is fully decoupled from the visual representation of the game entity. Clean, single responsible components, help us to get better structured and more maintainable code.</p><p>Apart from handling the obvious properties position, rotation and scale, we also get a location in the game code where we can put anything related to overall transformation handling that is useful for more than one entity.</p><h3>The Transform Component</h3><p>To start off the transform component we will have an empty node that will serve as a container that holds the transform properties.</p><pre>/// Handles transformations for an `Entity`.<br>class TransformComponent: GKComponent {<br>    /// Reference to the node that holds the transformations.<br>    ///<br>    /// We assign an empty node by default so an entity can have transformations<br>    /// without having a sprite node assigned to it.<br>    private lazy var node = SKNode()<br>}</pre><p>To ensure that our transform component can always hold transformations, we instantiate an empty SpriteKit SKNode by default. We do it lazily as we only want to create the empty node if we actually need it.</p><p>The node property can be used differently, depending on the game and the entities needs. Many times I let my SpriteComponent set itself as the node in the transform component, which is the reason why we want it to be lazy.</p><p>Other times I might keep the empty SKNode and use it as a parent for the sprites it transforms. So it&#39;s a case-by-case scenario.</p><h3>Transform Properties</h3><p>Let’s move on to the basic properties, where we wrap the transform component around the properties of SKNode with some added sugar on top.</p><p>First, we have the position.</p><pre>/// The position of the entity&#39;s node in its parent&#39;s coordinate system.<br>var position: CGPoint {<br>  get { node.position }<br>  set { node.position = newValue }<br>}<br><br>/// Computed world position from parent&#39;s coordinate system.<br>var worldPosition: CGPoint {<br>  get {<br>    guard let parent = node.parent,<br>          let entity = self.entity as? Entity,<br>          let scene = entity.scene<br>    else { return position }<br><br>    /*<br>      Use parent&#39;s coord system.<br>      Convert this node&#39;s local position to the world node&#39;s coord system.<br>      */<br>    return parent.convert(node.position, to: scene.world)<br>  }<br>  set {<br>    guard let parent = node.parent,<br>          let entity = self.entity as? Entity,<br>          let scene = entity.scene<br>    else { return }<br><br>    node.position = scene.world.convert(newValue, to: parent)<br>  }<br>}</pre><p>The position property is simply a wrapper around the position property in SKNode.</p><p>More interesting is the world position. I use the worldPosition property all the time and I find it very useful to have a wrapper around reading and setting the position in world space.</p><p>So by having both a position and a worldPosition property as part of the transform component, it becomes dead simple to work with the position of entities in both local and world space.</p><p>Next, moving on to rotation.</p><pre>/// The Euler rotation about the z axis (in radians).<br>var rotation: CGFloat {<br>  get { node.zRotation }<br>  set { node.zRotation = newValue }<br>}</pre><p>Not much to say here; the rotation property simply wraps around the zRotation property in SKNode. I haven&#39;t yet had any reason to add any other options here.</p><p>If you prefer working with degrees instead of radians, you could add a conversion for doing that here.</p><p>And finally, we have the scale.</p><pre>/// A scaling factor that multiplies the size of an entity.<br>var scale: CGSize {<br>  get {<br>    return .init(width: node.xScale, height: node.yScale)<br>  }<br>  set {<br>    node.xScale = newValue.width<br>    node.yScale = newValue.height<br>  }<br>}<br><br>/// Get accumulated size of the entity.<br>var size: CGSize { node.calculateAccumulatedFrame().size }</pre><p>I prefer to work with scale by having it contained in one CGSize value instead of working with each axis separately. So the scale property wraps a CGSize value around xScale and yScale in SKNode.</p><p>Then the additional size attribute calculates the total size of everything added to the hierarchy of the node. One use for this is to get the size in Physics Component when setting up the physics properties.</p><h3>Transform Methods</h3><p>With the transform properties setup, we can start adding useful methods to interact with the component.</p><p>I’ve a set(node:) method that I use for updating which node that the transform component uses for holding its properties.</p><pre>/// Set the node that holds the transformation values.<br>func set(node: SKNode) {<br>  // Transfer attributes from the previous referenced node to the new.<br>  node.position = position<br>  node.zRotation = zRotation<br>  node.xScale = scale.width<br>  node.yScale = scale.height<br><br>  // Set self.node to reference the new node.<br>  self.node = node<br>}</pre><p>The transform component might already have values assigned to its properties, so when setting a new node I transfer the properties from the node that previously was responsible for holding the properties to the new node.</p><p>This is a design consideration that I’ve been juggling a bit back and forth with. And I’m still not 100% sure if this is the way I’m going to keep it or if I might revise it in the future.</p><p>I’ve been considering using another approach where the transform class has its own properties for position, rotation and scale instead of using a node to hold those properties. But so far I’ve found it more useful to have it in the node, and also simpler to work with. So for now, I’ll stick to this approach.</p><p>And then finally, we can start decorating the component with useful methods to simplify making transforms on our game entities.</p><pre>/// Moves the transform in the direction and distance of translation.<br>func translate(_ direction: CGVector) {<br>  node.position += direction<br>}<br><br>/// Run an animation SKAction on the node.<br>func run(_ action: SKAction) {<br>  node.run(action)<br>}</pre><p>With the structure for the transform component in place, there is no limit to different methods that are useful for transformations in game development that we can keep adding to this class.</p><p>I’ll get the ball rolling with two example methods.</p><p>In any component that handles movement logic for our game entities, we can use the translate method to quickly execute the movement on screen. If the component has a direction and speed, we can simply pass in the formula to the transform component.</p><pre>transform.translate(direction * speed * Time.deltaTime)</pre><p>This is something I use all the time. To be able to simple get the delta time anywhere in your game code as in my example above, you can check out my article on writing a class for <a href="https://blog.bitbebop.com/deltatime-spritekit-swift/">Game Time in Swift</a>.</p><p>Another method that I find useful is to have a run() method where I can execute SKActions on the entity.</p><pre>transform.run(.sequence([actionA, actionB]))</pre><p>I use this for animations, but I also use it quite often to quickly be able to run time-based logic on a game entity. For instance, on an explosion entity I would start a run action with a completion action that adds a remove component when the explosion is done.</p><h3>Accessing the Transform Component</h3><p>With the transform component done and ready to be used in our game entities, we need to make sure we can easily get hold of a reference to it.</p><p>The transform component is something I use all the time. Not only for moving the objects on the screen, but I also need to read the transformation data for all kinds of different logic. It could be anything from a behavior system to handling trigger-based events.</p><p>More or less every game entity will require the transform component, so I’ve made it a part of my base class for entities. Which ensures that the rest of the game systems can count on that there will always be a transform component available.</p><p>I create my own base class for that all game entities inherit from, which is on top of GKEntity in GameplayKit.</p><pre>class Entity: GKEntity {<br>  /// Transform Component.<br>  let transform = TransformComponent()<br><br>  override init() {<br>    super.init()<br><br>    // Every entity has a transform component.<br>    addComponent(transform)<br>  }<br>}</pre><p>As every entity in the game inherits this Entity class instead of using GKEntity directly, they all automatically get the transform component added.</p><p>We also want to make sure that every game component has quick and easy access to its entity’s transforms. So just as we did our own Entity class instead of using GKEntity, we will use our own Component class instead of using GKComponent in GameplayKit directly.</p><pre>class Component: GKComponent {<br>  /// Hold a reference to the entity&#39;s TransformComponent.<br>  lazy var transform: TransformComponent = {<br>    guard let entity = entity as? Entity<br>      else { fatalError(&quot;The component must be added to an Entity.&quot;) }<br><br>    return entity.transform<br>  }()<br>}</pre><p>We want it to be dead simple to get hold of the transform component everywhere where it makes sense, and that is in other game components.</p><p>By having a lazy property we get the reference to the transform component first time it’s used, and then the reference is kept for in the property, which is good for performance.</p><p>Now every component in an entity has direct access to its transform, and we can write code like this anywhere without having to first find the transform component or having to worry about which SpriteKit node to interact with.</p><pre>transform.position = newPosition</pre><p>Powerful and convenient at the same time.</p><h3>Where to Next</h3><p>With the basic structure for the transform component in place, we can continue decorating it with methods to keep increasing its usefulness. We’ve just scratched the surface of what methods to include.</p><p>I’ll put some ideas on the table that I believe would be useful. What first comes to mind would be to add a property and related methods to simplify the handling of the parent-child relationship between game entities.</p><p>I can also see that including methods for both local and world space operations for rotations and scale would be of use. It would probably also be convenient to add methods that rotate towards a direction and/or move towards a specific position. And the list could go on.</p><p>Enjoy leveling up your gamedev with a powerful transform component.</p><p><em>Originally published at </em><a href="https://blog.bitbebop.com/gameplaykit-transform-component/"><em>https://blog.bitbebop.com</em></a><em> on April 17, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29b394da1fa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Batch Remove System for GameplayKit Entities]]></title>
            <link>https://medium.com/@johansteen/batch-remove-system-for-gameplaykit-entities-1b7065dbd980?source=rss-2550414c666e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b7065dbd980</guid>
            <category><![CDATA[spritekit]]></category>
            <category><![CDATA[gamedev]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[gameplaykit]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Johan Steen]]></dc:creator>
            <pubDate>Sun, 10 Apr 2022 07:42:00 GMT</pubDate>
            <atom:updated>2023-05-09T07:39:30.688Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Flag and batch remove objects from the game world by using a GameplayKit component and component system with Swift.</em></p><figure><img alt="Batch Remove System for GameplayKit Entities" src="https://cdn-images-1.medium.com/max/1024/0*ghIo-fpnwwDi7abo.jpg" /></figure><p>In most games, objects are being added and removed from the game world as the game progresses. This is an operation that affects memory usage and also triggers possible garbage collection.</p><p>I was looking for a solution to be able to remove objects in batches instead of having custom code that handles removal of objects scattered throughout my games.</p><p>I came up with a solution based on using a component together with a component system in GameplayKit.</p><p>By removing objects in batches I get control of exactly then during the game’s update loop removal of objects are happening and also get the code better structured and performant to do these operations that affects memory in one go instead of being fragmented during the frame cycle.</p><p>It has also allowed me to get cleaner and more consolidated code with a single location that handles the removal of objects.</p><h3>The Remove Component</h3><p>The remove component is super simple; all it does is add itself to a component system, so it can be processed later.</p><pre>import GameplayKit<br><br>/// Flags an entity to be removed from the game.<br>class RemoveComponent: Component {<br>    // MARK: Component Life Cycle<br><br>    override func didAddToEntity() {<br>        super.didAddToEntity()<br><br>        // Register with the removeComponentSystem.<br>        scene?.removeComponentSystem.addComponent(self)<br>    }<br>}</pre><p>We use didAddToEntity() to run our code automatically as soon as we add the component to an entity.</p><p>The component system the remove component adds itself to is defined in the scene class where the game runs. As almost all my entities and their added components needs to reference the scene file, I’m letting all my entities have a reference to the scene, and then I don’t use GKComponent directly but an extended version with a helper property so I always can reference the scene from components.</p><p>It looks something like this.</p><pre>class Component: GKComponent {<br>    // MARK: Convenience Properties<br><br>    /// The scene the owning entity is added to.<br>    var scene: GameScene? { (entity as? Entity)?.scene }<br>}</pre><p>The RemoveComponent is a child of my Component and not GKComponent so I can use the scene property in didAddToEntity() method.</p><h3>The Component System</h3><p>In my game scenes where I define my different component systems, I’ve setup a dedicated GKComponentSystem which only has the purpose of handling removals of entities from the game.</p><pre>class GameScene: SKScene {<br>  // MARK: Component Systems<br><br>  /// Component System to remove entities from the game.<br>  let removeComponentSystem = GKComponentSystem(componentClass: RemoveComponent.self)<br>}</pre><p>In the life cycle of SKScene didFinishUpdate() is the last method called just before the wait for the next frame begins. That method should be a great choice for us to use for the removal of our objects from the game.</p><p>At this time everything in the game is done executing during this update loop, so we end this cycle by batch removing all objects flagged for removal.</p><pre>override func didFinishUpdate() {<br>  super.didFinishUpdate()<br><br>  // Remove entities flagged for removal.<br>  for component in removeComponentSystem.components {<br>    if let entity = component.entity as? Entity {<br>      // Remove the entity and it&#39;s resources.<br>      remove(entity: entity)<br>    }<br>  }<br>}</pre><p>When iteration through the remove component system to get a reference for each entity that has the RemoveCompenent added, we call a remove method that has the actual logic to remove each entity from the game world.</p><p>A remove() method would most likely be unique for each game project. For me, I usually end up with something like this.</p><pre>/// Removes an entity from the game world.<br>func remove(entity: Entity) {<br>  // Remove sprite component as that removes the nodes from the scene.<br>  entity.removeComponent(ofType: SpriteComponent.self)<br><br>  // Remove the reference from the entities set.<br>  entities.remove(entity)<br>}</pre><p>I use a GKComponent that handles the sprite and it knows how to visually remove itself from the game world in the willRemoveFromEntity() method that is automatically called when a component is removed.</p><p>I keep a set with references to all entities currently in the game world, which I remove the entity from.</p><h3>Using the Remove Component</h3><p>That’s basically it; the only thing that remains is to actually start using the RemoveComponent when we need to flag an object for removal.</p><p>All we have to do to remove an object from the game is to add the RemoveComponent to the entity.</p><p>Let’s say that we have a bullet in the scene and we want to remove it when it hits its target. Then we simply can add the RemoveComponent in the contactDidBegin method.</p><pre>func contactDidBegin(with other: GKEntity, contact: SKPhysicsContact) {<br>  // Flag the bullet for removal.<br>  addComponent(RemoveComponent())<br>}</pre><p>Or we might have a particle emitter with a lifetime of 1.5 seconds that we want to remove when done playing. Then we could add the RemoveComponent by using an SKAction.</p><pre>// remove emitter when done<br>let wait = SKAction.wait(forDuration: 1.5)<br>let remove = SKAction.run { [weak self] in<br>    self?.addComponent(RemoveComponent())<br>}<br><br>run(SKAction.sequence([wait, remove]))</pre><p>We use the run SKAction and a sequence to add the RemoveComponent after the specified time has elapsed.</p><h3>Where to Next</h3><p>With this structure in place where we have a separate system that tracks objects for removal, it would be interesting to keep building on this concept to separate some of this logic away from the game loop.</p><p>For instance, we could potentially see if it was possible to use a background thread to iterate through the component system to get more time left on the main thread used by the game for a performance increase.</p><p>But that’s a project for another day.</p><p><em>Originally published at </em><a href="https://blog.bitbebop.com/gameplaykit-remove-component/"><em>https://blog.bitbebop.com</em></a><em> on April 10, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b7065dbd980" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Better Time Management in SpriteKit]]></title>
            <link>https://medium.com/@johansteen/better-time-management-in-spritekit-3b659e21a08?source=rss-2550414c666e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b659e21a08</guid>
            <category><![CDATA[gamedev]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[gamedevhq]]></category>
            <category><![CDATA[spritekit]]></category>
            <dc:creator><![CDATA[Johan Steen]]></dc:creator>
            <pubDate>Sat, 02 Apr 2022 08:57:00 GMT</pubDate>
            <atom:updated>2023-05-09T07:41:31.157Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Setup a ticker with Swift and SpriteKit to have relevant relevant time information like delta time available anywhere in your game code.</em></p><figure><img alt="Better Time Management in SpriteKit" src="https://cdn-images-1.medium.com/max/1024/0*DKkda9sGmnfn9At9.jpg" /></figure><p>Time management and the usage of delta time is one of the most important and fundamental parts for most game projects as it ensures consistency of any on-screen transforms no matter what the device’s frame rate is that the game runs on.</p><p>More or less any form of movement, rotation or time-related calculation should take delta time into account to ensure it’s not dependent on the frame rate.</p><p>Without using delta time, a bullet in a game, as an example, would move at a different speed on a 120 fps device compared to a 60 fps device.</p><h3>Delta Time in SpriteKit</h3><p>SpriteKit does not give us a delta time value out of the box, which is unfortunate considering how useful it is.</p><p>It’s not that the game framework engineers at Apple are not aware of delta time, as the GKComponent in GameplayKit requires delta time in its update(deltaTime:) method. But you have to calculate the value yourself.</p><p>At the same time as it’s unfortunate that SpriteKit does not provide delta time out of the box, it’s also understandable that the GameplayKit engineers deemed deltaTime as a requirement when calling the update method, as a component will most likely need to use delta time in one way or another.</p><p>And of course, if not using GameplayKit but only plain SpriteKit, you are going to need to use a delta time for your on-screen calculations to ensure consistency no matter what frame rate the device runs on.</p><p>SKScene provides the current time value, so most likely you are using or have seen solutions similar to this to get the delta time value.</p><pre>class GameplayScene: SKScene {<br>  /// Keeps track of how much time has passed since last game loop update.<br>  var lastUpdateTime: TimeInterval = 0<br><br>  override func update(_ currentTime: TimeInterval) {<br>    super.update(currentTime)<br><br>    // Get delta time since last time `update` was called.<br>    let deltaTime = calculateDeltaTime(from: currentTime)<br>  }<br><br>  /// Calculates time passed from current time since last update time.<br>  private func calculateDeltaTime(from currentTime: TimeInterval) -&gt; TimeInterval {<br>    // When the level is started or after the game has been paused, the last update time is reset to the current time.<br>    if lastUpdateTime.isZero {<br>      lastUpdateTime = currentTime<br>    }<br><br>    // Calculate delta time since `update` was last called.<br>    let deltaTime = currentTime - lastUpdateTime<br><br>    // Use current time as the last update time on next game loop update.<br>    lastUpdateTime = currentTime<br><br>    return deltaTime<br>  }<br>}</pre><p>In the life cycle of this SKScene we get the current time provided in the update method. By storing the current time value in the class property lastUpdateTime, we are able to keep track of how much time that has elapsed since the last time the update method was called, and by that we have our delta time value.</p><p>We can then take this value and keep passing it along to other methods or systems that need to use delta time for their calculations.</p><p>Which could look something like this.</p><pre>override func update(_ currentTime: TimeInterval) {<br>  super.update(currentTime)<br>  let deltaTime = calculateDeltaTime(from: currentTime)<br><br>  // Update the bullet system that handle movement of all bullets on screen.<br>  bulletSystem.update(deltaTime: deltaTime)<br><br>  // Update each GameplayKit component system.<br>  for componentSystem in componentSystems {<br>    componentSystem.update(deltaTime: deltaTime)<br>  }<br>}</pre><p>Each system, component or object that uses delta time will then have to accept the value in its method signature, and then pass it along further down the chain to its own methods that relies on delta time. You most likely will not want to keep all your logic in the update method, as it could grow massive, but structure the logic in dedicated methods.</p><p>We then end up with components like this.</p><pre>class MoveComponent: GKComponent {<br>  // ... Initialization and references to other components of the entity here ...<br><br>  override func update(deltaTime seconds: TimeInterval) {<br>    super.update(deltaTime: seconds)<br><br>    move(deltaTime: seconds)<br>  }<br><br>  private funct move(deltaTime seconds: TimeInterval) {<br>    entity.position += speed * direction * CGFloat(seconds)<br>  }<br>}</pre><p>Here we have a move method in the component that moves the entity’s position at a speed and direction that is not dependent on the device frame rate as we multiply the resulting velocity with our delta time value. As delta time is passed as a TimeInterval we have to cast it to an appropriate format, like CGFloat.</p><p>Most games will of course not only use the update method in SKScene, but will need to use the other methods in the life cycle, such as didSimulatePhysics or didFinishUpdate.</p><p>Those methods do not get the current time injected, so we are going to have to promote the deltaTime property to a class property to be able to access and use delta time in those scenarios.</p><pre>class GameplayScene: SKScene {<br>  var deltaTime: TimeInterval = 0<br><br>  override func update(_ currentTime: TimeInterval) {<br>    deltaTime = calculateDeltaTime(from: currentTime)<br>  }<br><br>  override func didSimulatePhysics() {<br>    // Update camera movemement.<br>    camera?.entity?.update(deltaTime: deltaTime)<br><br>    // Update each &#39;after physics&#39; component system.<br>    for componentSystem in afterPhysicsComponentSystems {<br>      componentSystem.update(deltaTime: deltaTime)<br>    }<br>  }<br>}</pre><p>While this is an approach that does the job, and SpriteKit provides us with the necessary data to deal with delta time, it’s quite convoluted.</p><p>We are mixing the time logic with the scene logic. And as every calculation that affects what happens on the screen, which is a lot in most games, relies on delta time, we are going to have to keep passing the value around between systems, classes and methods.</p><p>We might also have multiple scenes, even running at the same time, which happens when transitioning between scenes, which would create multiple delta time calculations at the same time.</p><p>The more complex a game becomes, with more systems and classes, the more this approach will feel to start falling apart. Let’s find a better way.</p><h3>Game Engines</h3><p>Looking at modern game engines such as Unity and Unreal, they calculate delta time as a core functionality and the value is made available to use where you need it. It makes sense that any framework that targets game development makes this available.</p><p>If we for instance take a closer peek at Unity, it provides a <a href="https://docs.unity3d.com/ScriptReference/Time.html">Time class</a> that has static properties containing time-related data.</p><p>By that, you never have to pass any time information around in your game code. Instead, you can at any time do a calculation like this, by just statically accessing the deltaTime property of Time.</p><pre>var position += speed * direction * Time.deltaTime;</pre><p>It’s apparent that they decided that something so crucial and that is used so often in game development should be calculated under the hood and be easily available at any time, which making it static solves.</p><p>The time class in Unity does not only provide deltaTime as a static property but has a ton of different useful time-related information.</p><h3>Swift Class for Static Time</h3><p>We have now examined the ordinary approach to dealing with delta time in SpriteKit as well as taken a peek at how modern game engines handle it. So let’s aim for a similar approach in SpriteKit for a better way to easily get access to time information via static properties.</p><p>We’ll take inspiration from Unity and see how we can have a Time class available in SpriteKit with static properties that are not tied to the current scene&#39;s update loop.</p><p>The static class will need to hold relevant properties together with an update() method to keep the values current.</p><pre>/// Tracks the game&#39;s time-related information.<br>public enum Time {<br>  /// The time given at the beginning of this frame.<br>  public private(set) static var time = TimeInterval(0.0)<br><br>  /// The interval in seconds from the last frame to the current one.<br>  public private(set) static var deltaTime = TimeInterval(0.0)<br><br>  /// Called on the device&#39;s frame update to track time properties.<br>  static func update(at currentTime: TimeInterval) {<br>    //  If `time` is 0.0 the game has just started, so set it to `currentTime`.<br>    if time.isZero {<br>      time = currentTime<br>    }<br><br>    // Calculate delta time since `update(at:)` was last called.<br>    deltaTime = currentTime - time<br><br>    // Set `time` to `currentTime for next game loop update.<br>    time = currentTime<br>  }<br>}</pre><p>That gives us the Time class with the static properties and a method to keep them up to date. Now we just need a place to call the update() method. The first thought might be to call it from update() in SKScene. Which would work most of the time.</p><p>We do get one problem if we do it from SKScene, at some times we might have more than one scene running, for instance when transitioning between two scenes. That would cause a race condition when then they would both update Time, which will give us an incorrect deltaTime for one of the scenes.</p><p>We also want to keep our code clean and not have to remember to call Time.update() in every scene class we create, as well as we want to avoid polluting the scene class with code that doesn&#39;t have to be there.</p><p>Luckily SKView has a delegate property that we can use for this. The delegate property takes an SKViewDelegate object, which gives us the hook we need to have a place to calculate time values outside the scene class.</p><p>Let’s create our own Ticker class, which is an SKViewDelegate so we can update our Time class. The view() method in SKViewDelegate is called just before the update() method in SKScene, so it&#39;s a perfect place for us to use to update time properties.</p><pre>/// Assign to the `SKView` to update game time properties for each frame.<br>public class Ticker: NSObject, SKViewDelegate {<br>  public func view(_ view: SKView, shouldRenderAtTime time: TimeInterval) -&gt; Bool {<br>    // Update time properties.<br>    Time.update(at: time)<br><br>    // By returning true the game runs at the full frame rate specified with preferredFramesPerSecond.<br>    return true<br>  }<br>}</pre><p>And finally, we need to assign the delegate to the SKView, during the game’s initialization process.</p><p>I prefer to have a GameManager class where I do all my early initialization. I instantiate my GameManager immediately from my ViewController where I pass in the SKView that will present my different game scenes.</p><p>That is the perfect spot to assign the custom delegate that will ensure that the time properties stay up to date without having to manage that on a per-scene basis.</p><pre>class GameManager {<br>  /// Ticker that updates game time properties.<br>  let ticker = Ticker()<br><br>  init(view: SKView) {<br>    // Assign the game time ticker to the view.<br>    view.delegate = ticker<br><br>    // ... Other game setup code would go here...<br>  }<br>}</pre><p>And there we have it, a rock-solid reusable solution that gives us easy access to time properties like delta time from anywhere in our game code.</p><p>Whenever we need to do a delta time based calculation, we can now at any time use Time.deltaTime as part of the calculation.</p><h3>Further Improvements</h3><p>With a central location for our time properties, it doesn’t have to end with delta time. There are plenty of time-related properties that are useful for game development. If we look at Unity’s Time class as a reference, we could replicate more of the properties there and keep decorating our own Time class.</p><p>Let’s say we also want to have access to the frame count in our game code.</p><pre>public enum Time {<br>  /// The total number of frames since the start of the game.<br>  public private(set) static var frameCount = 0<br><br>  static func update(at currentTime: TimeInterval) {<br>    // ... previous code in the update method here ...<br><br>    // Increase frame count since game started.<br>    frameCount += 1<br>  }<br>}</pre><p>We can now at any time access Time.frameCount if we need to read this value.</p><p>The final tweak, let’s extend our value types operators to handle TimeInterval.</p><p>Previously in this post we multiplied speed with delta time and had to cast the time value to CGFloat, CGFloat(seconds). As we are going to use the delta time value in many places, it would be convenient if we didn&#39;t have to cast it every time. Instead, we can extend types we are going to use with delta time, such as CGFloat and CGVector to use TimeInterval.</p><p>Here’s an example of extending CGFloat so we can multiply a CGFloat value directly with a TimeInterval without having to cast it every time.</p><pre>public extension CGFloat {<br>  static func * (lhs: CGFloat, rhs: TimeInterval) -&gt; CGFloat {<br>    return lhs * CGFloat(rhs)<br>  }<br>}</pre><p>By that, we are now able to write clean game code like this.</p><pre>movement = speed * Time.deltaTime</pre><p>What a beauty!</p><p><em>Originally published at </em><a href="https://blog.bitbebop.com/deltatime-spritekit-swift/"><em>https://blog.bitbebop.com</em></a><em> on April 2, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b659e21a08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trail VFX with SpriteKit]]></title>
            <link>https://medium.com/@johansteen/trail-vfx-with-spritekit-a704bd27ef4b?source=rss-2550414c666e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a704bd27ef4b</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[spritekit]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[gamedev]]></category>
            <dc:creator><![CDATA[Johan Steen]]></dc:creator>
            <pubDate>Wed, 30 Mar 2022 08:57:00 GMT</pubDate>
            <atom:updated>2023-05-09T07:43:42.381Z</atom:updated>
            <content:encoded><![CDATA[<h3>Trail VFX with Swift and SpriteKit</h3><p><em>Create a common Game VFX with SpriteKit, useful for trailing effects like projectiles and magic. Based on the less used components SKCropNode, SKEffectNode, and SKWarpGeometryGrid.</em></p><figure><img alt="Trail VFX with SpriteKit" src="https://cdn-images-1.medium.com/max/1024/1*w5KrVFyhJrq3WydNQkeWJA.jpeg" /></figure><p>Visual Effects are an important part of making pleasing effects in games. Commonly, VFX is used for things like bullets, projectile trails, magic, portals, and countless other things.</p><p>I was doing research some time ago on how to be able to replicate some common VFX techniques in SpriteKit. More specifically, I wanted to be able to make trailing effects to spice up the look of bullets as the player upgraded them while progressing through the game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*J4SsHRPEUNQhNhLVyqesCA.gif" /></figure><p>This is the kind of effect I ended up with, using only the functionality provided by SpriteKit.</p><h3>Trailing VFX Breakdown</h3><p>Let’s start by breaking down how an effect like this is usually constructed, and then we continue on how to implement those techniques using SpriteKit.</p><p>The effect is based on having a seamless trail texture. This can be created in Photoshop quite easily with some random strokes and then matching up the edges with the offset filter to make it seamless. But that’s out of the scope of this article.</p><h3>Moving the Trail Independently</h3><p>We are going to apply this texture on a plane, which is the VFX object that we will add to and move around in our game world. To make the texture feel dynamic instead of static, we are going to tweak the UV coordinates, which controls how the texture maps to the plane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*rxznHegzt4aAW1Dr.jpg" /></figure><p>When we compress the V position of the coordinates on one edge of the UV, we effectively squeeze the texture located on the opposite edge, so we get a tapered effect on the texture from one edge to the other.</p><p>And here comes the beauty, if we move this plane over the scene, and at the same time we also move the U position of the texture, at a different speed than the plane is using, the texture “comes alive” and we get a sense that the texture constantly evolves and animates during its lifetime instead of just statically move over the scene.</p><p>Working with a UV like this, the possible effects can be taken much further. We could alter the UV using a curved shape instead of a linear falloff, or segment it up and randomly adjust each segment’s size slightly to break up the movement and move it even further away from a static texture.</p><h3>Fading Out the Trail Edge</h3><p>Next, we are going to need to fade out the edge of the trail so it doesn’t cut off abruptly. We will do that with the help of a gradient map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*EhVAMe717RHwa-Rh.jpg" /></figure><p>The gradient map is the top layer of the stack which we are using to control the opacity of the effect. This layer will remain in place and not move over the UV like the trail texture does. By doing a multiply blend of the top gradient layer with the layers below, we end up with a nice fade out at the edge of the trail.</p><h3>Additional Tweaks</h3><p>To give the trails a bit more flare and depth, we are going to duplicate the trail texture two or three times and stack them on top of each other. Each copy will have the texture slightly offset and move over the UV at a slightly different speed.</p><p>This gives us tons of dynamic variation as the effect moves over the game scene. In the video of my SpriteKit effect above, I’ve layered the trail texture two times and each layer moves with different speed values and is then blended together.</p><p>And for the final touch to make it glow, top it off with a bit of bloom.</p><h3>SpriteKit Implementation</h3><p>That was it for the theory and how one would achieve this kind of effect in most graphics and game systems. So let’s see how we can approach this using SpriteKit and get into the nitty gritty details with some code.</p><p>The biggest challenge is that we don’t have access to manipulate UV coordinates when we map textures to nodes in SpriteKit. With SceneKit it would have been a different story, but oh well. As game VFX is often heavily based on manipulating UVs, we have to come up with some workarounds to achieve similar outcomes.</p><h3>The Trail Setup</h3><p>The trail layer would usually rely heavily on manipulating UVs. As we don’t have access to UVs in SpriteKit, let’s see what we would need the UVs to do, and then find SpriteKit solutions.</p><ul><li>With UVs textures can easily be repeated, so when the texture leaves the surface on one edge, it wraps around, and comes in on the opposite edge.</li><li>UVs allow us to compress and resize parts of the texture independently of how the displayed surface is sized.</li></ul><p>As SKSpriteNode does not have functionality to move and wrap a texture applied to it, we&#39;ll solve it by repeating the texture ourselves, parent the repeated setup to a container node, and then crop out the visible area.</p><p>We’ll have to handle the wrapping ourselves.</p><p>We will need three repetitions of the texture, which is enough no matter at what position we are observing it, to have enough repeating texture on each side to always be covered.</p><p>This setup will allow us to move the projectile texture independently of the parent node.</p><p>So let’s begin with setting up the trail. I put this into it’s own method so we can potentially create multiple layers of the same trail and stack for variation.</p><pre>func makeTrail() -&gt; SKNode {<br>  let trailC = SKSpriteNode(imageNamed: &quot;trailTexture&quot;)<br>  let trailL = SKSpriteNode(imageNamed: &quot;trailTexture&quot;)<br>  let trailR = SKSpriteNode(imageNamed: &quot;trailTexture&quot;)<br><br>  trailL.position.x = -512<br>  trailR.position.x = 512<br><br>  let trails = SKNode()<br>  trails.addChild(trailC)<br>  trails.addChild(trailL)<br>  trails.addChild(trailR)<br><br>  return trails<br>}</pre><p>We simply create the three instances we need of the texture. We have one centered, and then we move one to the left of it and one to the right of it.</p><p>In the example above, the texture is 512 points wide, so I’ve hard-coded the values 512 and -512 to move each segment to the left and right. We could have got this value from the texture itself, to make it more reusable.</p><p>We then parent all the segments to an SKNode and return this hierarchy. This trail object is basically what we need to be able to move and wrap the trail texture independently.</p><p>Now we can call makeTrail() whenever we need a new trail to build and layer up an effect.</p><pre>override func didMove(to view: SKView) {<br>  // Get 2 wrapable trails.<br>  let trail1 = makeTrail()<br>  let trail2 = makeTrail()<br><br>  // Make the second trail slightly taller and change the blend mode to `add`.<br>  trail2.zPosition = 1<br>  trail2.yScale = 1.25<br>  for child in trail2.children {<br>    if let child = child as? SKSpriteNode {<br>      child.blendMode = .add<br>    }<br>  }<br><br>  // ... Setup continues ...<br>}</pre><p>In this example we create two trail objects, so we can layer them on top of each other for more variation that will help sell the effect as a non-static texture.</p><p>The second trail object is made slightly larger by scaling it to 1.25 on the y-axis. The second trail is placed on top of the first, so each child of the second trail has its blendMode changed to add.</p><h3>Move and Wrap the Texture</h3><p>Time to get the texture moving. We will use the SKCropNode to get a window that we can observe our trail object through, and then give the trail object that holds the texture its own movement loop.</p><p>The crop node can then move around on the screen while the trail texture moves and wraps independently beneath it.</p><pre>override func didMove(to view: SKView) {<br>  // ... Setup continued ...<br><br>  // Create a huge hidden background.<br>  // This is explained further in the taper part. We need this for the warpGeometryGrid.<br>  let bg = SKSpriteNode(color: .black, size: .init(width: 4000, height: 95))<br>  bg.zPosition = -1<br>  bg.isHidden = true<br><br>  // Mask with the crop node.<br>  let mask = SKSpriteNode(color: .red, size: .init(width: 400, height: 95))<br>  let crop = SKCropNode()<br>  crop.maskNode = mask<br>  crop.addChild(bg)<br>  crop.addChild(trail1)<br>  crop.addChild(trail2)<br><br>  // ... Setup continues ...<br>}</pre><p>The <em>huge</em> background we create here is a story by itself that is related to SpriteKit’s geometry warping behavior. So it will be explained further once we get to the taper section. We add it here as it needs to be a child to the crop node.</p><p>SKCropNode needs a mask that defines our cropping area. The mask is basically our window where we can see what&#39;s inside the crop node, and the size of the mask becomes the size of our effect. So the mask is of the same height as the trail texture so we can fully see it, but much less wide, as we will keep moving the trail texture and only want to see a part of it horizontally.</p><p>So after setting the mask, we just keep adding children (the trails and the background) that we want to see through the crop node.</p><pre>override func didMove(to view: SKView) {<br>  // ... Setup continued ...<br><br>  // Keep moving the trails through the crop node.<br>  let move1 = SKAction.moveTo(x: 512, duration: 0)<br>  let move2 = SKAction.moveTo(x: -512, duration: 2)<br>  trail1.run(.repeatForever(.sequence([move1, move2])))<br>  let move3 = SKAction.moveTo(x: 512, duration: 0)<br>  let move4 = SKAction.moveTo(x: -512, duration: 2.5)<br>  trail2.run(.repeatForever(.sequence([move3, move4])))<br><br>  // ... Setup continues ...<br>}</pre><p>We then need to move the trail texture. We use SKAction.moveTo(x:duration:) to add the texture movement. Each trail needs two move actions. The first action has a duration of 0 as it moves the texture back to its starting position. This is basically the wrap around.</p><p>And the second move action animates the texture to move to the other side of the visible area. The duration value here sets the speed. We put both move actions into a sequence that we repeat forever.</p><p>In this example we use two trails stacked on top of each other, so we move the second trail with a different duration to get a different speed so it adds visual variation.</p><p>Potentially, we could also offset the move x value for one of the trails for even more variation.</p><p>And there we have it, a parent node (the crop node) that can be moved in the game scene while a texture moves independently inside it that wraps around. This setup gives us the same behavior as the first of the two UV bullet points.</p><h3>Fade the Edge</h3><p>To fade out the edge of the effect, we will do pretty much exactly as theorized above. We’ll take a gradient map image and multiply it on top of the effect.</p><pre>override func didMove(to view: SKView) {<br>  // ... Setup continued ...<br><br>  let opacity = SKSpriteNode(imageNamed: &quot;trailTexture-gradient&quot;)<br>  opacity.blendMode = .multiplyAlpha<br>  opacity.zPosition = 2<br><br>  // ... Setup continues ...<br>}</pre><p>We prepare an object with the gradient texture and set its blendMode appropriately so we can fade out the edge of the effect. We will add the node to the effect hierarchy together with the taper effect in the next step.</p><p>Another approach I’ve been considering is to use an SKShader that should be able to do the same thing, but which would be cleaner and more efficient.</p><h3>Taper the Texture</h3><p>It’s time to deal with the tapering of the trail effect by using a SpriteKit implementation for the second bullet point from the list with UV behaviors we are trying to replicate.</p><p>The closest I’ve got is to use an SKEffectNode with warpGeometry.</p><pre>override func didMove(to view: SKView) {<br>  // ... Setup continued ...<br><br>  // The effect node to warp.<br>  let effect = SKEffectNode()<br>  effect.addChild(crop)<br>  effect.addChild(opacity)<br><br>  // Create the tapered coordinates.<br>  let destinationPositions: [vector_float2] = [<br>    vector_float2(0, 5),   vector_float2(0.5, 0.9), vector_float2(1, -2.5),<br>    vector_float2(0, 0.5), vector_float2(0.5, 0.5), vector_float2(1, 0.5),<br>    vector_float2(0, -4),  vector_float2(0.5, 0.1), vector_float2(1, 3.5)<br>  ]<br>  let warpGeometryGrid = SKWarpGeometryGrid(columns: 2, rows: 2)<br><br>  // Apply the tapered effect.<br>  effect.warpGeometry = warpGeometryGrid.replacingByDestinationPositions(positions: destinationPositions)<br>  // Control the quality of the distortion effect.<br>  effect.subdivisionLevels = 4<br><br>  // ... Setup continues ...<br>}</pre><p>We distort the trail by using SKWarpGeometryGrid. Basically, we just create a grid of coordinates where we can squeeze the right side of the node together, so when the trail moves over the effect node, it gets compressed on the right side while it spreads out and widens on the left side.</p><p>This approach works fine if used isolated, but as with many SpriteKit things, it gets a tad more complicated when combining parts together.</p><p>Use the subdivisionLevels property of the effect node to get rid of distortion blockiness and get a much smoother and crisper look. Higher values do affect performance.</p><p>Do you remember this from before, when we created the huge background?</p><pre>let bg = SKSpriteNode(color: .black, size: .init(width: 4000, height: 95))<br>bg.isHidden = true</pre><p>Now is the time to talk about it. The huge, hidden, background is there to ensure that the warpGeometryGrid coordinates stay in put.</p><p><em>The warp does not respect the cropped area.</em></p><p>By having a larger than we need background, the warp will not move around. Otherwise, as the trails move over the node, it instead calculates the unit coordinates based on how large it sees all nodes added together for each frame. The large background counters that behavior and helps it keep consistent.</p><p>It’s not a pretty solution, but that’s how far I’ve been able to take it with SpriteKit alone. Using a CIFilter might be worth exploring as an alternative option, a transform there might behave more consistent than using warpGeometry.</p><p>Talking about CIFilter, as we have an effect node created already, why not keep using it.</p><pre>override func didMove(to view: SKView) {<br>  // ... Setup continued ...<br><br>  // Add an additional bloom on top of the effect.<br>  let bloomFilter = CIFilter(name: &quot;CIBloom&quot;)!<br>  bloomFilter.setValue(5, forKey: &quot;inputRadius&quot;)<br>  bloomFilter.setValue(1, forKey: &quot;inputIntensity&quot;)<br>  effect.filter = bloomFilter<br><br>  // ... Setup continues ...<br>}</pre><p>The effect node can take a CIFilter among its properties, so let’s go ahead and use it to add a bloom filter to enhance the effect further.</p><h3>Move the Full Trail Effect</h3><p>With the entire effect layered up and organized in a hierarchy under the effect node, we can now simply move the trail wherever we need it to be my moving the effect node around.</p><pre>override func didMove(to view: SKView) {<br>  // ... Setup continued ...<br><br>  // Move the entire projectile over the screen.<br>  effect.run(SKAction.moveTo(x: 700, duration: 3))<br><br>  effect.addChild(crop)<br>}</pre><p>And that’s all there is to it. We start an animation where we want the projectile to go and then add it to the scene.</p><p>In this article I’ve out of convenience, just added the setup inside the didMove(to:) method. It would make more sense to have this functionality in a trailEffect()-&gt;SKNode method that would setup the trail and return its node to have it instantiated on demand.</p><p>The returned node can then get the appropriate movement action assigned and then added to the scene.</p><p>Performance wise using SKEffectNode and SKCropNode can be heavy. Keeping the dimensions down on the effect should have a positive effect on performance.</p><h3>Next Steps</h3><p>Even though the fact that this solution can not compete with what you can do with the modern game engines out there, and also that the solution uncovers a few flaws (aka bugs) with SpriteKit, it can still provide a lot of power and usefulness for SpriteKit projects.</p><p>A dynamic trail VFX can be the building block and foundation of many different effects. Continuing building on the trails in this example, I’ll add a head to the trails using something like an animated flare. On top of that, a small particle emitter could be added as the final layer, emitted some sparkling texture to help bring the effect to life.</p><p><em>Originally published at </em><a href="https://blog.bitbebop.com/spritekit-trail-vfx/"><em>https://blog.bitbebop.com</em></a><em> on March 30, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a704bd27ef4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visual Debugging of GameplayKit GKComponent]]></title>
            <link>https://medium.com/@johansteen/visual-debugging-of-gameplaykit-gkcomponent-5de92db6a39b?source=rss-2550414c666e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5de92db6a39b</guid>
            <category><![CDATA[gameplaykit]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[gamedev]]></category>
            <category><![CDATA[spritekit]]></category>
            <dc:creator><![CDATA[Johan Steen]]></dc:creator>
            <pubDate>Thu, 03 Mar 2022 09:52:00 GMT</pubDate>
            <atom:updated>2023-05-09T07:45:00.055Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Use Swift protocols together with GameplayKit’s GKComponents for a convenient and flexible way to add all kinds of optional visual debug info during gameplay.</em></p><figure><img alt="Visual Debugging of GameplayKit GKComponent" src="https://cdn-images-1.medium.com/max/1024/1*zJgfdwlnOCaqB4berDNvBg.jpeg" /></figure><p>When coding games, it can be useful to be able to visualize values in real-time to monitor that algorithms behave as expected and that data is generated correctly. You don’t want to feel that you are working against a black hole, hoping for the best that every part of the game works as intended.</p><p>Writing a test suite can help somewhat with this, or even sometimes just printing data to the console will do the trick. As games most of the time are a visual experience, getting visual feedback of behaviors during play testing can be extremely useful and time saving and to help feel confident that the implementations are solid.</p><p>If you use a game engine like Unreal or Unity, you get some stuff like this “for free” but when we code our own games with Swift in Xcode, we have to implement our own systems to handle the visualizing of crucial values in our games to check that all the parts work as intended.</p><h3>Use Cases</h3><p>As this is only intended to be used during development and testing, and will never be shipped to the players in release builds, there is no need to make something pretty.</p><p>The point of these visualizations is to simply show the data in an easy to understand manner so it can be analyzed that it works as intended.</p><figure><img alt="GKComponent Visual Debugging Examples" src="https://cdn-images-1.medium.com/max/750/0*lmCfCRNkngD48OPg.jpg" /></figure><p>I’ve been building systems for this to keep track of values like enemy healthpoints, simulated input pressure, generated movement paths and many more things.</p><h3>Implementation Example</h3><p>Let’s study a concrete example, how this can be implemented using the Swift programming language. I’m basing this on using GameplayKit and SpriteKit, but it can easily be adopted to other frameworks.</p><h3>Visual Debug Protocol</h3><p>I rely heavily on the Entity Component System provided with GameplayKit, so most of my logic is contained within GKComponents. I’m using a custom protocol with GKComponent that I can implement for components that contain values that I need to analyze visually.</p><pre>#if DEBUG<br>/// Protocol to enable/disable visualization of debug info in `GKComponent` objects.<br>protocol GKComponentDebuggable {<br>  /// Enable display of debug info.<br>  func enableDebugInfo()<br><br>  /// Disable display of debug info.<br>  func disableDebugInfo()<br><br>  /// Update loop to run debug specic logic.<br>  func debugUpdate(deltaTime seconds: TimeInterval)<br>}<br>#endif</pre><p>With these three methods in my GKComponentDebuggable protocol I&#39;ve been able to handle all my visualization needs I&#39;ve had so far. enableDebugInfo() allows me to do any initialization, in disableDebugInfo() I do the cleanup and in debugUpdate() I can handle any changes needed on a frame by frame basis.</p><h3>Debug Core Setup</h3><p>I handle the setup to enable, disable, and update the components that implement the GKComponentDebuggable in my main GameplayScene class. That is the class that takes care of all the core management of my game systems.</p><pre>class GameplayScene {<br>  #if DEBUG<br>  /// Tracks the state if debug info shall be displayed.<br>  var debugInfoEnabled = true {<br>    didSet {<br>      debugInfoEnabledDidChange()<br>    }<br>  }<br><br>  /// Root layer of nodes to display movement graphs for debugging.<br>  let debugGraphLayer = SKNode()<br>  #endif<br><br>  override func didMove(to view: SKView) {<br>    // ... other initialization code would be here ...<br><br>    #if DEBUG<br>    // Add layers to display debug info to the scene.<br>    debugGraphLayer.zPosition = LevelLayer.debug.rawValue<br>    worldNode.addChild(debugGraphLayer)<br><br>    // Call didChange once so it can start with debug mode on if enabled.<br>    debugInfoEnabledDidChange()<br>    #endif<br>  }<br><br>  // ... And here continues the rest of my GameplayScene class ...<br>}</pre><p>I’m using two properties. debugInfoEnabled allows me to define if I should start the game with debug info in an enabled state. When the value is changed, I call a dedicated debugInfoEnabledDidChange() method that handles all states when it comes to visual debug info. This is not limited to the things I show with GKComponentDebuggable as I also have other debug info I enable that are not related to specific components.</p><p>debugGraphLayer is a sub-root node that is available in the GameplayScene when making a Debug build, that all GKComponentDebuggable implementations can use to add their visuals to. This is set to a Z depth above everything else in the scene.</p><p>During the scene’s life cycle, I initialize the debugGraphLayer node at the end of didMove(to:).</p><p>Okay, let’s move on to interacting with the protocol.</p><pre>#if DEBUG<br>// Extend GameplayScene to add methods to display debug info.<br>extension GameplayScene {<br>  /// Toggle display of debug overlay metrics.<br>  func debugInfoEnabledDidChange() {<br>    // ... other debug info handling....<br><br>    // Toggle debug info in components.<br>    for componentSystem in componentSystems {<br>      toggleDebugInfo(for: componentSystem.components)<br>    }<br>  }<br><br>  /// Toggles debug info for provided array of components.<br>  func toggleDebugInfo(for components: [GKComponent]) {<br>    for case let component as GKComponentDebuggable in components {<br>      if debugInfoEnabled {<br>        component.enableDebugInfo()<br>      } else {<br>        component.disableDebugInfo()<br>      }<br>    }<br>  }<br><br>  /// Update loop to run debug specic logic.<br>  func debugUpdate(deltaTime seconds: TimeInterval) {<br>    // Exit right away if we don&#39;t display debug info.<br>    if !debugInfoEnabled { return }<br><br>    // Update component systems.<br>    for componentSystem in componentSystems {<br>      for case let component as GKComponentDebuggable in componentSystem.components {<br>        component.debugUpdate(deltaTime: seconds)<br>      }<br>    }<br>  }<br>}<br>#endif</pre><p>To keep it neat and tidy, I’ve added the debug handling code in an extension to the GameplayScene class that is only included in debug builds. I&#39;ve three methods in this extension that manage the debug visualization.</p><p>debugInfoEnabledDidChange() is the method we call when we change the debugInfoEnabled property in the GameplayScene above, that handles toggling all different debug visualizations on and off.</p><p>In the method, I loop through the componentSystems property. Which is an array of [GKComponentSystem] that holds references to all currently active component systems in the game. That is the standard behavior of ECS in GameplayKit and a bit out of scope for me to go deeper into in this article.</p><p>This is the same array I loop through in my standard gameplay update loop, to update all components on each frame iteration.</p><pre>override func update(_ currentTime: TimeInterval) {<br>  // ...<br><br>  for componentSystem in componentSystems {<br>    componentSystem.update(deltaTime: Time.deltaTime)<br>  }<br>}</pre><p>Then we have toggleDebugInfo() which takes an array of GKComponents. This is the method we call from debugInfoEnabledDidChange where we pass in the components from each component system. But I also call this method manually when a new entity is added to the game during gameplay in debug mode, to enable visualization if required.</p><p>This method simply loops through the components and then calls the enableDebugInfo() or disableDebugInfo() on each component that has implemented the GKComponentDebuggable protocol.</p><p>And finally we have the debugUpdate(deltaTime:) method. Just like previous methods, this method loops through all components in each component system to see which ones implement GKComponentDebuggable, and for those that does, the debugUpdate(deltaTime:) method is called in the component.</p><p>This method is called last in the regular gameplay update loop when building a debug build.</p><pre>override func update(_ currentTime: TimeInterval) {<br>  // ...<br><br>  #if DEBUG<br>  // Run update loop for debug info and overlay.<br>  debugUpdate(deltaTime: Time.deltaTime)<br>  #endif<br>}</pre><h3>Example</h3><p>So with all this in place, let’s see an example, of an actual implementation in a component.</p><pre>#if DEBUG<br>// MARK: - Debug<br><br>extension EnemyAIComponent: GKComponentDebuggable {<br>  func enableDebugInfo() {<br>    guard let scene = renderComponent.node.scene as? GameplayScene else { return }<br><br>    // Configure path display<br>    let shape = SKShapeNode(path: self.path)<br>    shape.lineWidth = 3<br>    shape.strokeColor = .red<br>    shape.name = NodeName.componentDebug<br>    shape.position = startPos!<br><br>    // Store a reference to the entity in the path so we can find it later as it is displayed directly in the scene and not as a child of anything relating to the entity.<br>    shape.userData = [&quot;entity&quot;: entity!]<br><br>    scene.debugGraphLayer.addChild(shape)<br>  }<br><br>  func disableDebugInfo() {<br>    guard let scene = renderComponent.node.scene as? GameplayScene else { return }<br><br>    // Find and remove the path in the graph layer.<br>    scene.debugGraphLayer.enumerateChildNodes(withName: NodeName.componentDebug) { [weak self] (node, _) in<br>      guard let entity = node.userData?[&quot;entity&quot;] as? GKEntity else { return }<br><br>      if entity == self?.entity {<br>        node.removeFromParent()<br>      }<br>    }<br>  }<br><br>  func debugUpdate(deltaTime seconds: TimeInterval) {<br>    // Not needed in this component.<br>  }<br>}<br>#endif</pre><p>In this example, I extend EnemyAIComponent to visualize the path on screen that an enemy gets assigned when spawned. So during the enableDebugInfo() phase, I take the path property already available in the component and draw the path to screen with a SKShapeNode.</p><p>I use disableDebugInfo() to remove the path when the entity is removed.</p><p>In this case the path does not change during the component’s life cycle, so I don’t need to call debugUpdate(deltaTime:). Otherwise, I&#39;d have used this method to update the drawn path during the life span of the component.</p><h3>Conclusion</h3><p>There are of course many ways to skin a cat, but for me, I’ve found that this protocol-based approach together with the ECS system of GameplayKit has worked out great while keeping the code clean and easy to navigate.</p><p>While I just scratched the surface here of what one can do, I can imagine taking the concept further to a full-blown in-game console to be able to interact with the protocol and even other game data live during gameplay for even faster iterations.</p><p>And other times, a simple print statement to the Xcode console might be enough. I’d put my solution above somewhere in between, which fulfills the purpose fast and efficiently in many day to day scenarios to analyze game data.</p><p><em>Originally published at </em><a href="https://blog.bitbebop.com/gameplaykit-gkcomponent-visual-debug/"><em>https://blog.bitbebop.com</em></a><em> on March 3, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5de92db6a39b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>