<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: zigzagoon1</title>
    <description>The latest articles on DEV Community by zigzagoon1 (@zigzagoon1).</description>
    <link>https://dev.to/zigzagoon1</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F993039%2Fb735a3fc-cabb-4b89-bb63-599bef4b1be0.jpeg</url>
      <title>DEV Community: zigzagoon1</title>
      <link>https://dev.to/zigzagoon1</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/zigzagoon1"/>
    <language>en</language>
    <item>
      <title>Using Phaser.js In Your React/Rails Webapp</title>
      <dc:creator>zigzagoon1</dc:creator>
      <pubDate>Thu, 01 Feb 2024 22:28:56 +0000</pubDate>
      <link>https://dev.to/zigzagoon1/using-phaserjs-in-your-reactrails-webapp-42eb</link>
      <guid>https://dev.to/zigzagoon1/using-phaserjs-in-your-reactrails-webapp-42eb</guid>
      <description>&lt;h4&gt;
  
  
  Before We Start
&lt;/h4&gt;

&lt;p&gt;When I was researching how to do this for my game, I noticed a lot of blogs about it didn't specify their setup or versions, which meant that their solutions might not work but I didn't know until I tried. So: I'm using React version 18.2.0, Phaser 3.70.0, and Ruby 2.7.4. We'll go through setup, EventEmitters, and some other small things. This method does not use Redux, although using Redux is a useful way for managing state that is shared by Phaser and React. &lt;/p&gt;

&lt;h4&gt;
  
  
  Still Here
&lt;/h4&gt;

&lt;p&gt;So, you got through the fun setup for creating a webapp with a React frontend and Ruby on Rails backend- congrats! I like this combination for managing websites as well. &lt;/p&gt;

&lt;p&gt;Now you want to add a game made with Phaser.js to your site. I had to do that myself, so I thought I'd share my process in case it can help others get their games on their websites. Fortunately, it's not too difficult. &lt;/p&gt;

&lt;p&gt;I'll also go over setting up a Phaser EventEmitter that can be used to communicate between your React components and your Phaser game, so you can save data like user scores and other things in your backend. But first things first!&lt;/p&gt;

&lt;h3&gt;
  
  
  Installing Phaser.js Into Your React/Rails Webapp
&lt;/h3&gt;

&lt;p&gt;Your setup may be slightly different than mine, so I'll show what mine looks like to help clarify where things go.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Root
  -app
    -channels
    -controllers
    -jobs
    -mailers
    -models
    -serializers
    -views
  -client
    -node_modules
    -public
    -src
    -package-lock.json
    -package.json
  -config 
    -environments
    ...
    -routes
  -db
  -lib
  -node_modules
  -storage
  -tmp
  -config.ru, Gemfile, package-lock.json, package.json,
    Procfile, Rakefile, webpack.config.js are all on this
    level too, among others.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that all Rails API related folders are contained within the &lt;code&gt;app&lt;/code&gt; folder, and all frontend-related folders are in &lt;code&gt;client&lt;/code&gt;. The only backend things that are separate from &lt;code&gt;app&lt;/code&gt; are the db (database) and config folders; db is where you would have your migrations and schema and seeds.rb file, and config contains your routes.rb file.&lt;/p&gt;

&lt;p&gt;In order to use phaser, you need to install it using &lt;code&gt;npm install phaser&lt;/code&gt; in your terminal. Make sure to do this within the &lt;code&gt;client&lt;/code&gt; folder, as Phaser will run in the frontend, or alternatively you can run the command while in your root folder by doing &lt;code&gt;npm install --prefix client&lt;/code&gt;. Next, navigate to your index.html file (you can also add this next bit to your App.js if you'd prefer). Once there, create a div. This will be the container for your Phaser game, so give it an id of "phaser-container". You'll need to reference this element by it's id later to tell Phaser which element is its parent element. &lt;/p&gt;

&lt;p&gt;Next we can set up our Phaser game config. I chose to make my game config a React component, so I imported React and &lt;code&gt;useEffect&lt;/code&gt;. You'll also need to import Phaser, and any game scenes that you need. This is what my Phaser game config looks like in my project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const PhaserGameConfig = ({gameType, onGamePlayed}) =&amp;gt; {
    useEffect(() =&amp;gt; {
      const config = {
        type: Phaser.AUTO,
        width: 700,
        height: 500,
        backgroundColor: '#ffffff',

        physics: {
            default: 'arcade',
            arcade: {
                gravity: {y: 0}, 
                debug: true,
            },
        },
        parent: 'phaser-game', 
        scene: 'TicTacToe' //or, in my case, getScene()
      };
    new Phaser.Game(config);
    }, []);

    return &amp;lt;div id="phaser-game"&amp;gt;&amp;lt;/div&amp;gt;;
}

export default PhaserGameConfig;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, you may have noticed that I passed the prop &lt;code&gt;gameType&lt;/code&gt; to my component (there's also another prop, &lt;code&gt;onGamePlayed&lt;/code&gt;, which I'll get to shortly). In my case, my site has multiple games on it, so I created a &lt;code&gt;getScene&lt;/code&gt; method within my component, which returned a different Phaser scene depending on the value of gameType. &lt;/p&gt;

&lt;p&gt;Now, wherever you want your Phaser game or games to be displayed, you can simply return a PhaserGameConfig component, and in my case, pass the game's name as a prop to the component. &lt;/p&gt;

&lt;p&gt;To have access to any assets, such as images or audio, in your Phaser scene, simply put the assets into the public folder that's within the client folder. &lt;/p&gt;

&lt;p&gt;The communication between Phaser and React that I used involves the use of Phaser's &lt;code&gt;EventEmitter&lt;/code&gt;. The example I'm going to show worked for my game, but it may take some tinkering to get it working in yours depending on what your needs are for communicating between the two. I hope showing how I did it is helpful. If anyone has an idea for a better way of solving the problem below, I'd love to hear about it in the comments! &lt;/p&gt;

&lt;p&gt;For me, I simply needed a way to detect when a user had played an entire game of TicTacToe so that I could add to a count of the number of games the user has played so far. &lt;/p&gt;

&lt;p&gt;In my project, I added a few lines to my &lt;code&gt;PhaserGameConfig&lt;/code&gt; component that allowed me to achieve this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//PhaserGameConfig component as shown above...
//after the useEffect 

const handler = () =&amp;gt; {
    onGamePlayed();

eventEmitter.on("gameEnd", handler);

return &amp;lt;div id="phaser-game"&amp;gt;&amp;lt;/div&amp;gt;
} //bracket marking the end of the PhaserGameConfig component

export const eventEmitter = new Phaser.Events.EventEmitter();

export default PhaserGameConfig;
} 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, in my Phaser scene for TicTacToe, I import that eventEmitter like this: &lt;code&gt;import {eventEmitter} from '../PhaserGameConfig'&lt;/code&gt; (in my case, my phaser scenes are not in the same folder as my components). Then, at the start of &lt;code&gt;create()&lt;/code&gt;, I added &lt;code&gt;this.eventEmitter = eventEmitter&lt;/code&gt;. Voila! Now, after a game finishes in my TicTacToe scene, I can simply emit my event like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;this.eventEmitter.emit("gameEnd);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And my &lt;code&gt;PhaserGameConfig&lt;/code&gt; component calls the callback function passed as a prop to the component, adding to the count of the number of games played by the user. &lt;/p&gt;

&lt;p&gt;Now, for more complicated event handling where you have more than one or two events, or events that need to be handled differently depending on the game, I would create my &lt;code&gt;eventEmitter&lt;/code&gt; as a context to be used with &lt;code&gt;useContext&lt;/code&gt;. This helps to avoid lots of prop drilling, and decouples the event handling from the &lt;code&gt;PhaserGameConfig&lt;/code&gt; component itself. This would probably require the use of &lt;code&gt;useMemo&lt;/code&gt;, &lt;code&gt;useCallback&lt;/code&gt; and &lt;code&gt;React.memo&lt;/code&gt; where appropriate to optimize a bit and avoid a lot of unnecessary re-renders.&lt;/p&gt;

&lt;p&gt;Have a better idea for how to handle communication between React and Phaser? Let me know in the comments! &lt;/p&gt;

</description>
      <category>phaser</category>
      <category>react</category>
      <category>rails</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Programming Patterns for Games: Command - Evaluating Unity's Input Handling Options</title>
      <dc:creator>zigzagoon1</dc:creator>
      <pubDate>Thu, 25 Jan 2024 22:16:30 +0000</pubDate>
      <link>https://dev.to/zigzagoon1/programming-patterns-for-games-command-evaluating-unitys-input-handling-options-1dee</link>
      <guid>https://dev.to/zigzagoon1/programming-patterns-for-games-command-evaluating-unitys-input-handling-options-1dee</guid>
      <description>&lt;p&gt;When first reading about this pattern, I found it difficult to picture what the pattern was actually doing or what kinds of situations it would be useful for. I know a lot of people are confused by this one too- who has yet to use Unity's new input system in order to avoid the setup for it? So, I decided to write a blog post about it to really delve in and understand it! I hope my journey of understanding the command pattern can help you to understand it better, too, as it's quite a useful one for cross-platform and multiplayer games!&lt;/p&gt;

&lt;h3&gt;
  
  
  The Problems
&lt;/h3&gt;

&lt;p&gt;There are a few problems that this pattern can help with that I'd like to mention, though it should be noted that this is not a complete list of situations where the command pattern is useful. &lt;/p&gt;

&lt;p&gt;To start, one major factor in game development today is making your game compatible across platforms so that you can play it on a computer, a console such as the Nintendo Switch, or even a phone, and not have to create separate source code for each platform. First of all, if you're trying to make your game compatible cross-platform, how do you account for the different kinds of controllers and buttons for each system? If you make it so that the player jumps when the &lt;code&gt;space&lt;/code&gt; key is pressed on a keyboard, that won't translate to any button on a Nintendo Switch controller or the touch screen on a phone, and your game would only be playable on a device with a keyboard.&lt;/p&gt;

&lt;p&gt;The command pattern offers a way to separate the action performed in the game from the button that causes the action to happen, allowing you to map it to whatever button makes the most sense for the target platform, and if there's more than one target you simply map that action to different buttons depending on what your user is playing on.&lt;/p&gt;

&lt;p&gt;Another issue that comes up has to do with multiplayer games. When playing a live multiplayer game, what happens in the game needs to happen synchronously for every player in the game, though they may be on different devices and spread all around the world. To make sure the games are kept in sync without using the command pattern, you may have to send lots of detailed information when communicating data about a player's actions to the other players' devices. This would be very inefficient and could create a lag, as the more data you send the longer it will take for the other device to be able to download and interpret that data. For example, "the player does a jump animation and then does x-type of attack with its respective animation and hits the enemy, causing y damage and the enemy to do its being-hit animation". &lt;/p&gt;

&lt;p&gt;Without the command pattern, you need to send such detailed information in order to make sure each instance of the game stays in sync. This can get quite complicated, and there's a much better way to keep the games in sync. With the command pattern, you can simply share the name or type of actions themselves, in the order they happen, and each game instance will have that action mapped to produce the same outcome; this way, without needing to send the details, the same things will happen in both games.&lt;/p&gt;

&lt;p&gt;It's important to note that the command pattern is not the only thing involved in synchronizing game states for multiplayer gameplay, but those aren't the topic of this blog post. &lt;/p&gt;

&lt;h3&gt;
  
  
  The Command Pattern
&lt;/h3&gt;

&lt;p&gt;I've already given some common problems and how the command pattern can solve them, but what's the actual definition of the pattern? If you look it up, you'll see definitions such as "a request encapsulated as an object" or "a reified method call". Maybe that's all you need to see to understand it, but my response was "huh?". &lt;/p&gt;

&lt;p&gt;My best explanation for the command pattern is that it is a way of separating the logic for a command or request from the logic that actually executes commands or requests. &lt;/p&gt;

&lt;p&gt;Let's take a look at an example of controlling a player GameObject's behavior through user input in Unity. We'll look at Unity's old Input Manager, and then go over the new system.&lt;/p&gt;

&lt;h4&gt;
  
  
  Old Input Manager
&lt;/h4&gt;

&lt;p&gt;Previously in Unity, in order to have objects in your game respond to user input, you would do something similar to the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Player : MonoBehaviour
{
    Rigidbody rb;
    float jumpForce = 5f;
    void Start()
    {
        rb = GetComponent&amp;lt;Rigidbody&amp;gt;();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Jump();
        }
    }

    void Jump() 
    {
        rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This script is pretty straightforward. In the Update function, we listen for when the user presses the &lt;code&gt;Space&lt;/code&gt; key, and when that happens we call &lt;code&gt;Jump()&lt;/code&gt;, which adds an upward force to the player's rigidbody component, making the player character jump. Very simple and easy to use, with no setup required. &lt;/p&gt;

&lt;p&gt;This is a quick and convenient way of processing player input and it can be really useful to quickly test something without having to setup a proper action. For some very small and simple projects that aren't meant to be multiplayer, cross-platform or expanded on, handling input this way is manageable and can even make more sense for simplicity. However, in general it is better to use Unity's new input system for handling input, even though it takes a little bit more work to set it up. &lt;/p&gt;

&lt;p&gt;For example, imagine using this approach for input handling in a cross-platform game. A PlayStation controller does not have a space key- in order to have this work on PlayStation, we would need to change our code to account for the PlayStation buttons instead. &lt;/p&gt;

&lt;p&gt;While this isn't necessarily terrible, and is how Unity's Input Manager worked for a long time, it does have some downsides. For one, it adds complexity and makes it harder to manage user input across devices. To maintain one version of source code regardless of platform, you can use compiler directives to ignore code depending on which platform the user is playing the game on, but this means more work for the developer and more opportunities for errors and bugs to be introduced, requiring more thorough testing on all platforms to ensure everything is working correctly.  As your game grows in scale, so too will the types of input you need mapped to actions, and you will have to write out all the logic for each type of controller. And what about games where a button can cause more than one type of response in the game, depending on the context? There is no built-in way with this type of input management to change the behavior depending on the context. Furthermore, there is no support for gestures, touch input, or more advanced features such as haptic feedback or gyroscopic controls that are available on modern devices.&lt;/p&gt;

&lt;p&gt;Again, the Input Manager is not inherently a bad choice for your game- it truly depends on the game you're making and if you plan to grow it or make it cross-platform at any point. If not, and it's just a simple game intended to be played only on one device, the Input Manager works just fine. &lt;/p&gt;

&lt;p&gt;Now, let's look at how Unity's new input system works. &lt;/p&gt;

&lt;h4&gt;
  
  
  New Input System Package
&lt;/h4&gt;

&lt;p&gt;I'll briefly go over setting up the input system, but I'm not going to go over every step and won't be going over it in detail. If you need a more thorough walk through, &lt;a href="https://gamedevbeginner.com/input-in-unity-made-easy-complete-guide-to-the-new-system/" rel="noopener noreferrer"&gt;this detailed guide&lt;/a&gt; goes over using both the old and new ways of handling user input, and &lt;a href="https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/QuickStartGuide.html" rel="noopener noreferrer"&gt;Unity's official manual&lt;/a&gt; also has a quick start guide you can follow. &lt;/p&gt;

&lt;p&gt;In order to use Unity's new input system, you have to download the input package from the package manager. You then need to create an Input Actions object through the create menu (it's at the bottom if you right click and go to create). You can name it whatever you like; I tend to call it Controls. You then need to create a Control Scheme. Each control scheme can represent a different platform or device that your game can be played on. Next you add an Action Map. In a game I'm currently working on, I have an Action Map for any actions associated with the player, another for the main camera controls, and one for the game manager GameObject. You can also organize it by "Gameplay" or "UI", or separate devices and shared actions across devices, or anything that makes the most sense for your game. &lt;/p&gt;

&lt;p&gt;Next, you add an Action to your action map. We'll go over the same Jump action example from the previous section. Name your new action "Jump", and then add a key binding to it. To do this, expand the arrow next to your action to see "" below. Click on that, and you will see the menu on the right side change, and it will have a Path option that is set to blank. Click that, and either start typing the name of the key or button, or you can have it listen for a key/button press and it will capture the next one you use. We'll use the &lt;code&gt;Space&lt;/code&gt; key for our Jump Action, so navigate to that however you prefer. You'll also see a couple sections below the Path option; interactions are where you would control whether the Action is fired only when the button is pressed for a certain duration, or if it is tapped multiple times, and processors can help you control how this key press in interpreted; we won't be using them here though.&lt;/p&gt;

&lt;p&gt;Next we write out the logic for what happens when the key or button that's bound to our Action is pressed. There are a few ways to connect your Action to a method within a script. One way is to attach a PlayerInput component to your GameObject that should be listening for input. Let's look at the code for this setup:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Player
{
    InputActionAsset playerInput;
    Rigidbody rb;
    float jumpForce = 5f;

    void Start()
    {
        rb = GetComponent&amp;lt;Rigidbody&amp;gt;();
        playerInput = GetComponent&amp;lt;PlayerInput&amp;gt;().actions;
        playerInput.Enable();
    }

    public void OnJump()
    {
        rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Looks pretty similar! The difference is that we must reference our &lt;code&gt;PlayerInput&lt;/code&gt; component, enable it, and then follow Unity's naming convention by adding the word "On" before the name of our Action. This will automatically connect our Jump Action to the OnJump method in the script. &lt;/p&gt;

&lt;p&gt;Alternatively, you can attach logic from any script to an action by subscribing to that actions' &lt;code&gt;started&lt;/code&gt;, &lt;code&gt;performed&lt;/code&gt; or &lt;code&gt;cancelled&lt;/code&gt; events. Here's how you would do this (note that here we assume that the input actions are already enabled elsewhere):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Player
{
    InputActionAsset playerInput;
    InputAction jumpAction;
    Rigidbody rb;
    float jumpForce = 5f;

    void OnEnable()
    {
        jumpAction = playerInput.FindAction("Jump");
        if (jumpAction != null)
        {
            jumpAction.performed += _ =&amp;gt; OnJump();
        }
    }
    void Start()
    {
        rb = GetComponent&amp;lt;Rigidbody&amp;gt;();
    }

    void OnJump()
    {
        rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
    }

    void OnDisable()
    {
        if (jumpAction != null)
        {
            jumpAction.performed -= _ =&amp;gt; OnJump();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With this setup, we must grab a reference to the action we want using the name we gave it in our input action asset, making sure it matches exactly. If we find it, we subscribe (and unsubscribe!) to its &lt;code&gt;performed&lt;/code&gt; event, which occurs immediately after &lt;code&gt;started&lt;/code&gt;. This is similar to &lt;code&gt;GetButtonDown&lt;/code&gt; vs. &lt;code&gt;GetButtonUp&lt;/code&gt;, though it should be noted that there are more nuances to &lt;code&gt;.performed&lt;/code&gt; that can be affected by the any interactions assigned to the action. &lt;/p&gt;

&lt;p&gt;My syntax subscribing to the event includes what is known as a discard variable, which refers to the _ or underscore symbol. The &lt;code&gt;performed&lt;/code&gt; event provides a &lt;code&gt;InputAction.CallbackContext&lt;/code&gt; that we would want to pass along to our method in some cases, as this is what would allow us to grab specific values and other info. In the case of &lt;code&gt;Jump&lt;/code&gt;, we only need to know that the button was pressed; specific values are not necessary, so we use the underscore to signal that the context parameter can be safely ignored. &lt;/p&gt;

&lt;p&gt;Looking at the difference between Unity's old and new input systems, you can see how the new system is different in that it encapsulates an Action as an object. This object is bound to a key or button press, and this is all separate from the logic for what happens when the action is performed. This decoupling of the command issuer from the command executor is what allows for the benefits the command pattern brings in cross-platform and multiplayer games. &lt;/p&gt;

</description>
      <category>gamedev</category>
      <category>programming</category>
      <category>learning</category>
      <category>csharp</category>
    </item>
    <item>
      <title>Intro to Creating Cookies in a Rails Application</title>
      <dc:creator>zigzagoon1</dc:creator>
      <pubDate>Tue, 07 Nov 2023 16:46:21 +0000</pubDate>
      <link>https://dev.to/zigzagoon1/intro-to-creating-cookies-in-a-rails-application-4c4p</link>
      <guid>https://dev.to/zigzagoon1/intro-to-creating-cookies-in-a-rails-application-4c4p</guid>
      <description>&lt;p&gt;I've been learning web development with React and Ruby on Rails, and decided to share some of what I've learned about creating cookies for your site. Let's get right to it.&lt;/p&gt;

&lt;h3&gt;
  
  
  Intro to Cookies
&lt;/h3&gt;

&lt;p&gt;Cookies are often a vital part of a user's experience of the web- they enhance convenience and allow the user to have a more customized experience on a site. They can be used to persist a user's login so that they don't have to login again when they refresh the page; they can also be used to store user preferences and settings, keep track of items in a shopping cart, track user behavior for analytical purposes, and target personalized ads to the user, among other things.&lt;/p&gt;

&lt;h3&gt;
  
  
  So what exactly are cookies, and how do they work?
&lt;/h3&gt;

&lt;p&gt;Cookies are actually small pieces of data that are stored on the user's computer by a web browser while a user is browsing a website. When a user visits a website, the browser sends a request to the server. The server's response can include a &lt;code&gt;Set-Cookie&lt;/code&gt; header which will include the cookie's name, value, and attributes such as expiration date, or security flags. The browser then stores this cookie in a small text file on the user's computer. Then, as the user navigates the site, sending HTTP requests to the server, the browser automatically includes all the associated cookies in the request. Each cookie is associated with a specific domain, and the browser ensures that cookies are only sent back to the domain that sent them. Then, in the backend, the server reads the cookie data from the request and uses the information to identify the user and apply their preferences, among other tasks. &lt;/p&gt;

&lt;h3&gt;
  
  
  Main types of cookies
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Session Cookies
&lt;/h4&gt;

&lt;p&gt;There are a few different types of cookies that a developer can use on their site. The first is a session cookie; these cookies are temporary and expire after the browser is closed, but are useful for data that's needed for a single browsing session. Here's how you would make a session cookie to store a user's login info in Rails:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class SessionsController &amp;lt; ApplicationController

    # '/login' routes to the create method in SessionsController

    def create

        # Find the user in the database using the given username 
        # when they attempted to login

        user = User.find_by(username: params[:username])

        # If the user exists and they gave the correct password, 
        # store the user id in the session to persist login

        if user&amp;amp;.authenticate(params[:password])
            session[:user_id] = user.id
            render json: user, status: :created
        else
            render json: {error: "Unauthorized"}, 
            status: :unauthorized
        end
    end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It's really that simple to create a session cookie! Now, even when the user refreshes a page on the website, the frontend can request relevant settings and data for the user that is logged in, and the backend will then check if the given user is actually logged in and, if so, return the requested information. In this example, if the user gives an incorrect username or password, we instead render an error message to let the frontend know that the login failed or there is no user logged in. &lt;/p&gt;

&lt;p&gt;If you tried to recreate this example in your own project and it didn't work, you'll need to make sure you have the Active Record and BCrypt gems installed in your project, and to add the code &lt;code&gt;has_secure_password&lt;/code&gt; to your user.rb model. &lt;/p&gt;

&lt;h4&gt;
  
  
  Persistent Cookies
&lt;/h4&gt;

&lt;p&gt;Making a persistent cookie is also easy! It's important to note that you should also clear persistent cookies when the user logs out, which is normally handled in &lt;code&gt;destroy&lt;/code&gt; in the &lt;code&gt;SessionsController&lt;/code&gt;. Let's look at the same situation, storing the &lt;code&gt;user_id&lt;/code&gt; to a cookie upon login, but with persistent cookies instead:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class SessionsController &amp;lt; ApplicationController

    def create
        user = User.find_by(email: params[:email])

        if user&amp;amp;.authenticate(params[:password])
            cookies.permanent[:user_id] = user.id
            render json: user, status: :created
        else
            ...
        end
    end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;.permanent&lt;/code&gt; method on &lt;code&gt;cookies&lt;/code&gt; will automatically set the cookie to expire in 20 years. To specify an expiration, you would use a cookie without &lt;code&gt;.permanent&lt;/code&gt; and specify a duration, such as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cookies[:user_id] = { value: user.id, expires: 2.weeks.from_now }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can replace &lt;code&gt;2.weeks.from_now&lt;/code&gt; with any other ActiveSupport::Duration method to suit your specific needs.&lt;/p&gt;

&lt;p&gt;To clear the cookie, you would have this destroy method in the sessions controller:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def destroy
    cookies.delete(:user_id)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Easy peasy! &lt;/p&gt;

&lt;h4&gt;
  
  
  Zombie Cookies
&lt;/h4&gt;

&lt;p&gt;Zombie cookies are so called because they are usually stored in multiple locations and will recreate themselves even after the user deletes all their stored cookies. For this reason, zombie cookies are controversial, and their use is seen as a way to circumvent a users preferences relating to privacy and cookie management. &lt;/p&gt;

&lt;h3&gt;
  
  
  Cookie security and best practices
&lt;/h3&gt;

&lt;p&gt;Because cookies can be used for nefarious purposes, it's best to follow standard best practices when using cookies on our own sites. Keeping up with security can help protect your users, so it's of vital importance when creating cookies! For example, for our server-side cookie we set earlier, we could do the following to make them more secure:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class SessionsController &amp;lt; ApplicationController
    def create
        ...
        cookies.signed[:user_id] = {
          value: user.id,
          httponly: true,
          secure: Rails.env.production?
        }
        ...
    end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In our create method, we create a cookie using cookies.signed, for extra security. We then set httponly to true, which prevents access to cookie data via Javascript. The secure flag, which we set to be true only if the environment is in a production setting, means that cookies can only be sent over HTTPS connections. We keep this flag set to false in a development environment, as cookies will not be set when secure is true in development since it is not using HTTPS. &lt;/p&gt;

&lt;p&gt;Another very important piece of security for cookies is to not store any sensitive data in the cookie itself, but rather session identifiers. &lt;/p&gt;

&lt;p&gt;I highly recommend checking the &lt;a href="https://guides.rubyonrails.org/v5.2/security.html"&gt;Rails Security Guide&lt;/a&gt;, for a more comprehensive overview of how to ensure your cookies are secure in your rails backend and can't be used to harm or steal information from your users. &lt;/p&gt;

&lt;p&gt;For more information on creating cookies in a Rails application, please visit the official documentation on cookies &lt;a href="https://api.rubyonrails.org/v5.2.8.1/classes/ActionDispatch/Cookies.html"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If you have any feedback, suggestions, or noticed any errors in this post, please leave a comment letting me know! Thanks for reading, I hope it helps. &lt;/p&gt;

</description>
      <category>webdev</category>
      <category>beginners</category>
      <category>rails</category>
      <category>react</category>
    </item>
    <item>
      <title>Programming Patterns for Games: Observer</title>
      <dc:creator>zigzagoon1</dc:creator>
      <pubDate>Fri, 27 Oct 2023 23:06:31 +0000</pubDate>
      <link>https://dev.to/zigzagoon1/programming-patterns-for-games-observer-325b</link>
      <guid>https://dev.to/zigzagoon1/programming-patterns-for-games-observer-325b</guid>
      <description>&lt;p&gt;Next up in programming patterns for games is the Observer pattern.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Problem
&lt;/h3&gt;

&lt;p&gt;In games, objects need to "talk" to other objects all the time. Most of the time, when a player character takes damage, multiple objects must react; the health bar must register the damage taken and decrease its value accordingly, which must cause the visual component to change; Enemies may need to know the player took damage- maybe your enemy's strength increases when it lands an attack, or there is a cooldown period where the enemy cannot attack you again. If you've ever tried to create a game, you've probably come across this type of problem before- it's an essential part of creating a game if you want your objects to interact in some way. &lt;/p&gt;

&lt;p&gt;The problem is, what is the best way to create that communication between scripts? You could have a variable in your players' script that references an enemy script, and directly call a method on the enemy script when the player is hit by or hits the enemy, like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Player
{
     //reference the enemy script

    Enemy enemyInstance = GameObject.FindObjectOfType&amp;lt;Enemy&amp;gt;();

    //player attacks enemy- you can imagine the enemy script
    //has a method called TakeDamage() that takes in an Int 
    //argument and subtracts that value from its health value

    void Attack()  
    {
        enemyInstance.TakeDamage(5);
    }  

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If your game only ever has one instance of an enemy that stays the same the whole game, that solution &lt;em&gt;could&lt;/em&gt; work (although it still tightly couples our code and is not ideal). However, most of the time, we have many instances of an enemy. It would be a bit ridiculous to create a reference in our player script to every single enemy instance (there might be thousands!) And how would we account for those instances that are instantiated at runtime? &lt;/p&gt;

&lt;p&gt;Not only that, but as I mentioned, this kind of solution tightly couples our code- the player script has a direct reference to an enemy object. This is bad for maintainability, testing, code reusability, and scalability. If you're not sure why coupling would be bad in these areas, check out &lt;a href="https://www.infoworld.com/article/3632143/how-coupling-impacts-software-quality.html#:~:text=Tight%20coupling%20makes%20it%20challenging,test%20them%20after%20a%20change."&gt;this&lt;/a&gt; source that goes into more detail on code coupling. &lt;/p&gt;

&lt;p&gt;It also means your game would be consuming more memory than necessary- if an enemy game object is destroyed, normally the garbage collector would dispose of it, but since the player script references the enemy script, the garbage collector cannot destroy it when it should otherwise be able to. &lt;/p&gt;

&lt;p&gt;Imagine if, instead of traffic lights or stop signs, each car was responsible for coordinating directly with the cars around it. It would be chaos! Code coupling and direct references to communicate between objects has a similar effect. As you can see, this isn't really a good solution for many reasons. &lt;/p&gt;

&lt;p&gt;The observer pattern allows for our scripts to communicate, but decouples our code so our game objects don't have to be directly tied to the objects they are interacting with. &lt;/p&gt;

&lt;h3&gt;
  
  
  The Observer Pattern
&lt;/h3&gt;

&lt;p&gt;With the observer pattern, an object, known as the subject, keeps a list of dependents, known as the observers. When something happens in the game that you need other objects to know about, your subject object can invoke a function that the observers all subscribe to. You may be familiar with events systems, which are themselves using the observer pattern. In Unity, there are a few ways to create an event and its listeners. Let's go over one of them by looking at a ScoreManager script with an event to update other scripts when there is a change in score.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ScoreManager : MonoBehaviour
{
    private int currentScore = 0;

    // Declare an event to notify when the score is updated.

    public delegate void ScoreUpdatedEventHandler(int newScore);
    public event ScoreUpdatedEventHandler ScoreUpdated;

    private void Start()
    {
        // Initialize the score (for demonstration purposes).
        currentScore = 0;
    }

    // Function to update the player's score.
    public void UpdateScore(int scoreChange)
    {
        currentScore += scoreChange;

        // Notify subscribers that the score has been updated.
        ScoreUpdated?.Invoke(currentScore);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this script, we create a delegate function that returns nothing and takes in an argument of the new score value. Delegate functions allow us to define a functions basic signature, or the "shape" or kind of function it is, to allow us to pass a function as an argument without actually calling the function. We then create an event of the type of our delegate and call it &lt;code&gt;ScoreUpdated&lt;/code&gt;. Now, in any scripts that need to be updated when the score changes, they simply have to subscribe to that event, and the line &lt;code&gt;ScoreUpdate?.Invoke(currentScore)&lt;/code&gt; will invoke the event and all functions/methods that are subscribed to it, regardless of the script they're in.&lt;/p&gt;

&lt;p&gt;This is how the observer scripts would subscribe to the event.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ScoreDisplay : MonoBehaviour
{
    public Text scoreText;

    private void Start()
    {
        // Find the ScoreManager in the scene.
        ScoreManager scoreManager = FindObjectOfType&amp;lt;ScoreManager&amp;gt;();

        // Subscribe to the ScoreUpdated event.
        scoreManager.ScoreUpdated += UpdateScoreText;
    }

    // This method updates the UI text with the current score.
    private void UpdateScoreText(int newScore)
    {
        scoreText.text = "Score: " + newScore.ToString();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, in the &lt;code&gt;Start&lt;/code&gt; method, we grab a reference to the script containing the event definition (another way to reference the script is to use a Singleton, which you can read more about &lt;a href="https://dev.to/zigzagoon1/programming-patterns-for-games-singleton-1be1"&gt;here&lt;/a&gt;). Next, we create a method in the observer class to handle the logic of updating score for that particular object, and subscribe that method to the event in the ScoreManager script. &lt;/p&gt;

&lt;p&gt;If you're coming from a web development background, imagine you're creating a &lt;code&gt;&amp;lt;button&amp;gt;&lt;/code&gt; element. In order to have that button respond to a click, you have to create a function that handles what happens when the button is clicked, and you have to subscribe that function to the &lt;code&gt;onClick&lt;/code&gt; event. Then, when the button is clicked, the &lt;code&gt;onClick&lt;/code&gt; event is invoked, and any functions that are subscribed to the event are called. All these examples are using the Observer pattern! &lt;/p&gt;

&lt;p&gt;In Unity, while the above example works, what you will most often see is an observer subscribe to an event in Unity's &lt;code&gt;OnEnable&lt;/code&gt; method rather than &lt;code&gt;Start&lt;/code&gt;, and then unsubscribe from the same event in the &lt;code&gt;OnDisable&lt;/code&gt; method. This way, the script is only subscribed to any events while the game object it's attached to is active, therefore it does not retain any connection with the events when the object is disabled or destroyed, again helping the garbage collector do it's job. &lt;/p&gt;

&lt;p&gt;To summarize, the Observer pattern offers an elegant solution to a common challenge in game development— efficient communication between objects. We've explored how tightly coupling code can lead to issues in maintainability and scalability, and we've introduced the Observer pattern as a decoupled alternative.&lt;/p&gt;

&lt;p&gt;By using events and subscribers, as demonstrated in our Unity examples, developers can create flexible and extensible systems that allow game objects to communicate without the need for direct references. This not only enhances code organization but also improves memory management.&lt;/p&gt;

&lt;p&gt;As you delve deeper into game development, or even in different domains of software development, mastering common programming patterns like the Observer pattern becomes increasingly valuable. &lt;/p&gt;

&lt;p&gt;For more information, &lt;a href="https://gameprogrammingpatterns.com/observer.html"&gt;this&lt;/a&gt; site has a great overview of the Observer pattern if you'd like to learn more.&lt;/p&gt;

</description>
      <category>gamedev</category>
      <category>beginners</category>
      <category>csharp</category>
      <category>programming</category>
    </item>
    <item>
      <title>ORM: Object Relational Mapping with Ruby</title>
      <dc:creator>zigzagoon1</dc:creator>
      <pubDate>Wed, 02 Aug 2023 22:56:59 +0000</pubDate>
      <link>https://dev.to/zigzagoon1/orm-object-relational-mapping-with-ruby-3dd8</link>
      <guid>https://dev.to/zigzagoon1/orm-object-relational-mapping-with-ruby-3dd8</guid>
      <description>&lt;p&gt;I'm going to discuss the concept of Object Relational Mapping, or ORM, using Ruby examples. I will briefly introduce Active Record, but this article is mostly about learning to create our own ORM system to show how they work and why we need them. &lt;/p&gt;

&lt;h3&gt;
  
  
  Uhh... ORM?
&lt;/h3&gt;

&lt;p&gt;ORM stands for Object Relational Mapping. But what actually is an ORM? &lt;/p&gt;

&lt;p&gt;An ORM is the link or bridge between our object-oriented language and our database.&lt;/p&gt;

&lt;p&gt;When creating a website, or a game, or an app, etc., there's a front end, which contains all the code for handling user interaction and UI/UX, and a back end, which handles the storing of relevant information. This information can range from a high score in a game, or whether or not an item is in stock for a store's website- basically, the sky's the limit. These data points are stored in a database in the back end, along with some Ruby (or language of your choice) scripts to interact with that database in order to send data to the front end when it's requested. &lt;/p&gt;

&lt;p&gt;Let's say we're using SQLite for our database. In order to store information, we need to create tables for that data. Because a website is (usually) not static but changes constantly depending on user interaction, we also need our database to be dynamic, which means being able to create, read, update, and delete both tables and rows within tables. These are known as CRUD operations, and they're the core operations necessary for building an interactive website. &lt;/p&gt;

&lt;p&gt;Without using ORM, we would need to write out SQLite queries for each CRUD operation every time we need to use or save the data in our database. This can get very tedious very fast, and there's a lot of opportunity for errors. Fortunately, there's a better way.&lt;/p&gt;

&lt;h3&gt;
  
  
  Making Our Own ORM
&lt;/h3&gt;

&lt;p&gt;One way we can speed things up and reduce errors in our CRUD operations using Ruby, or any other object-oriented lanuage, is to create a class (an &lt;em&gt;object&lt;/em&gt;) that shares the same properties as a table in the database. If that's at all unclear, let's look at an example class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Cat
    attr_accessor :id, :name, :color, :age
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using the &lt;code&gt;Cat&lt;/code&gt; class, we would create a table in our database called &lt;code&gt;cats&lt;/code&gt;. The &lt;code&gt;cats&lt;/code&gt; table would have a column for id, name, color, and age. Now, every instance of the &lt;code&gt;Cat&lt;/code&gt; class has all the information necessary to create a row in our &lt;code&gt;cats&lt;/code&gt; table in the database! &lt;/p&gt;

&lt;p&gt;In Ruby, it is convention to name our class a singular word, such as Cat, and the corresponding database table the lowercase plural of the same word, such as cats. With the relationship between our class and its properties and the table and columns, we can now create some class functions to perform each CRUD operation to our database, all from OOP Ruby!&lt;/p&gt;

&lt;p&gt;For example, let's look at our Triangle class with some ORM capabilities.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Cat
    attr_accessor: :id, :name, :color, :age

    #Upon a new cat instance being created, initialize its 
    #attributes. Note that we assume id is an autoincrementing
    #primary key, so we set it to nil initially
    def initialize(id: nil, name:, color:, age:)
        @id = id
        @name = name
        @color = color
        @age = age
    end

    #class method to create the cats table 
    def self.create_table
        sql = &amp;lt;&amp;lt;-SQL
          CREATE TABLE IF NOT EXISTS cats (
            id INTEGER PRIMARY KEY,
            name TEXT,
            color TEXT,
            age INTEGER
            )
            SQL
        DB[:conn].execute(sql)
    end

    #class method to create a new instance of a cat, and save that  
    #cat to the database
    def self.create(name:, color:, age:)
        cat = Cat.new(name: name, color: color, age: age)
        cat.save
    end

    #instance method to call on an instance of cat that saves the    
    #cat as a row in the cats table
    def save
        sql = &amp;lt;&amp;lt;-SQL
          INSERT INTO cats (name, color, age)
          VALUES (?, ?)
          SQL
        DB[:conn].execute(sql, self.name, self.color, self.age)
        self.id = DB[:conn].execute("SELECT last_insert_rowid() 
          FROM cats")[0][0]
        #return the newly created instance
        self
    end

    #create a new cat instance from a row in the database
    def self.new_from_db(row)
        self.new(id: row[0], name: row[1], color: row[2] age: 
          row[3])
    end

    #search the database for a single cat with the matching name,     
    #and create an instance that corresponds to the row
    def self.find_by_name(name)
        sql = &amp;lt;&amp;lt;-SQL
          SELECT *
          FROM cats
          WHERE name = ?
          LIMIT 1
          SQL

        DB[:conn].execute(sql, name).map do |row|
            self.new_from_db(row)
        end.first
    end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Okay, so that was a lot at once! The comments explain what each function does, but there are a few things there that may not be familiar. &lt;/p&gt;

&lt;p&gt;First of all, you may have noticed that in those methods we call &lt;code&gt;DB[:conn].execute(sql)&lt;/code&gt;. In order to query the database, we have to establish a connection to the database. Most commonly, that connection is defined in a file called &lt;code&gt;environment.rb&lt;/code&gt; that is in a folder called &lt;code&gt;config&lt;/code&gt;. In &lt;code&gt;environment.rb&lt;/code&gt;, we can create the connection with the database with the following line of code:&lt;br&gt;
&lt;br&gt;
 &lt;code&gt;DB = {conn: SQLite3::Database.new("db/cats.db") }&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;In order to do this, SQLite3 must be installed in your project. &lt;/p&gt;

&lt;p&gt;By the way, in case you were wondering what &lt;code&gt;sql = &amp;lt;&amp;lt;-SQL...&lt;/code&gt; does, well &lt;code&gt;&amp;lt;&amp;lt;-&lt;/code&gt; is called a heredoc. It's a way for us to have a multi-line string that keeps the format we supply it. Whatever immediately follows the &lt;code&gt;&amp;lt;&amp;lt;-&lt;/code&gt; is what signals that it's the end of the string. So in our case, the indicator is SQL, and we must put &lt;code&gt;SQL&lt;/code&gt; at the end of the string query we write when using a heredoc.&lt;/p&gt;

&lt;p&gt;Now, our &lt;code&gt;Cat&lt;/code&gt; class can easily create Cat instances that can be saved to the &lt;code&gt;cats&lt;/code&gt; table in the database as a new row. All we have to do is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cat = Cat.new(name: "Ziggy", color: "orange", age: 7)
cat.save
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can imagine, this is much simpler and easier to work with than it would be without the mapped relationship between a Ruby class and SQLite table. For one, not having to write out the SQL query multiple times can save a lot of time and reduce the chance for errors!&lt;/p&gt;

&lt;h3&gt;
  
  
  Active Record
&lt;/h3&gt;

&lt;p&gt;If you were already thinking that these ORM things were pretty useful for saving time and reducing complexity, I've got some great news for you. If you use Ruby, there's a very handy little &lt;a href="https://guides.rubygems.org/what-is-a-gem/"&gt;Gem&lt;/a&gt; called Active Record that makes everything we did in the previous section even easier! While there are still cases where a custom ORM or a different ORM gem would be useful, most of the time Active Record can be a great asset for your project. &lt;/p&gt;

&lt;p&gt;I'm not going to too much in to Active Record, but it provides ORM methods for CRUD operations like the ones we created in the example so we don't even have to write out those methods in each class we want mapped to our database. We simply follow a few Active Record conventions, and it'll do all the work for us! &lt;/p&gt;

&lt;p&gt;If you're working with Ruby and databases for a back end and aren't using Active Record, I highly recommend switching to it. It's easy to add to your project and isn't difficult to learn how to use it. I recommend checking out the official guides at &lt;a href="https://guides.rubyonrails.org/active_record_basics.html"&gt;this link&lt;/a&gt; to learn the ins and outs of how to use it, and you can thank me later!&lt;/p&gt;

&lt;p&gt;That's all for this article; however, there's a lot more to learn about ORMs! For example, often we would have error handling built in to our methods, as well as data validation to ensure that the correct type of data is being saved, or to prevent null entries. Active Record includes some data validation methods, which you can read about &lt;a href="https://guides.rubyonrails.org/active_record_validations.html"&gt;here&lt;/a&gt;.&lt;br&gt;
You can learn more about error handling &lt;a href="https://medium.com/rails-ember-beyond/error-handling-in-rails-the-modular-way-9afcddd2fe1b"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Please feel free to comment if you noticed any mistakes or have any questions! Until next time :) &lt;/p&gt;

</description>
      <category>beginners</category>
      <category>ruby</category>
      <category>sql</category>
      <category>orm</category>
    </item>
    <item>
      <title>Programming Patterns for Games: State</title>
      <dc:creator>zigzagoon1</dc:creator>
      <pubDate>Tue, 01 Aug 2023 18:17:30 +0000</pubDate>
      <link>https://dev.to/zigzagoon1/programming-patterns-for-games-state-2eop</link>
      <guid>https://dev.to/zigzagoon1/programming-patterns-for-games-state-2eop</guid>
      <description>&lt;h3&gt;
  
  
  Welcome back!
&lt;/h3&gt;

&lt;p&gt;It's been a little while, so hopefully my writing gears aren't too rusty. Next up in my series of programming patterns for games, I'm going to talk about State. &lt;/p&gt;

&lt;h3&gt;
  
  
  Introduction - What Do You Mean by "State"?
&lt;/h3&gt;

&lt;p&gt;The formal definition for the state programming pattern is: "State is a behavioral design pattern that lets an object alter its behavior when its internal state changes. It appears as if the object changed its class." &lt;/p&gt;

&lt;p&gt;To understand state in programming, let's look at some other uses of the word 'state'. For example, you might say you're in a state of utter joy and happiness; or maybe you're in the state of California. In either case, the state you're in, whether physical or emotional, comes with a set of rules. For example, if you're in Chico, California and you just love going bowling on the sidewalk, I'm sorry to tell you &lt;a href="https://www.stupidlaws.com/laws/united-states/california/chico/"&gt;you're out of luck&lt;/a&gt; . If you're in a state of joy, you really wouldn't be able to start screaming in anger at someone and still claim to be in a state of joy. &lt;/p&gt;

&lt;p&gt;Using 'state' in programming is similar, only we, as programmers, are creating the rules for each type of state, and the objects we're creating are abiding by them. The behavior of objects in your game can be dictated by what state is active, or what state they're in; they could follow a completely different set of rules for each state. &lt;/p&gt;

&lt;h3&gt;
  
  
  Why It's Useful
&lt;/h3&gt;

&lt;p&gt;As game developers, we often write code that controls the behavior of an object; we make our objects move through space, use items, and take damage, but only when the circumstances are right within the game environment. To illustrate this, let's start with a classic example- jumping. Say you're working on a main character for your game, and you're trying to implement jumping. When the user presses, say, the 'A' button, you want your character to jump. A simple Unity example would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Player : MonoBehaviour 
{
    void Update() 
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Jump();
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Assuming the code for the method &lt;code&gt;Jump&lt;/code&gt; works correctly, we've got ourselves a character that can jump! However, that character doesn't have any limitations on when it can jump- if a user were to keep pressing the space button over and over, our character would jump higher and higher. We would have to introduce a variable that keeps track of when the character is on the ground, and only allow the player to jump when the character is grounded. &lt;br&gt;
That's an easy enough solution, and it works perfectly well to solve the problem. However, as our game gets more and more complicated, having to create variables to keep track of when each behavior is allowed can quickly lead to a confusing jumble and odd behavior. &lt;/p&gt;

&lt;p&gt;Imagine if we introduced flying, ducking, and running behaviors. We would have to set a bool variable to not allow jumping when flying or ducking, but make sure it does allow jumping when running, but only when grounded. Having to keep track of the &lt;em&gt;state&lt;/em&gt; of multiple variables each time we want to have our character perform an action can easily lead to bugs and errors, and a big headache. That is just a relatively simple set of behaviors to manage; the more complicated your game, the bigger the chance for something to go wrong and potentially lead to some frustrating debugging sessions. While using a boolean value to dictate when an action can be performed, like with jumping, can be thought of as a simple form of state (the state being "grounded"), that method of controlling state is not ideal for more complicated gameplay. If we find ourselves creating a lot of these bool variables to control behavior in our script, it might be worth using a finite state machine instead.&lt;/p&gt;
&lt;h3&gt;
  
  
  Finite State Machine
&lt;/h3&gt;

&lt;p&gt;With a finite state machine, or FSMs, we define different states that our object can be in throughout the game and the rules for their behavior in each state. The key is that only one state can be active at a time. With a FSM, we could create a Flying, Ducking and Running state for our player character and control variables for speed or animation differently depending on the state the player object is in. Let's look at an example FSM script created for Unity to see how this works:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class FSM 
{
      public enum Step
    {
        Enter, 
        Update, 
        Exit
    }
    public delegate void State(FSM fsm, Step step, State state);
    State currentState;

    public void StartFSM(State startState)
    {
        TransitionTo(startState);
    }

    public void OnUpdate()
    {
        currentState.Invoke(this, Step.Update, null);
    }

    public void TransitionTo(State state)
    {
        if (currentState != null)
        {
        currentState.Invoke(this, Step.Exit, state);
        }
        var oldState = currentState;
        currentState = state;
        currentState.Invoke(this, Step.Enter, oldState);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a basic FSM pattern that I've used in my own projects- let's break it down! &lt;/p&gt;

&lt;p&gt;An FSM should have a transition period between states so that the switch is not instantaneous. If we didn't have a transition period it would be easy for any state to transition to any other state, and part of the purpose of using our FSM is to be able to control if a transition from one state to another is even allowed, such as with the no-jumping-while-flying example. So, we first create an enum &lt;code&gt;Step&lt;/code&gt; that will allow us to divide our State into three parts- Enter, for any code we may need to run or initialize for use while in the state; Update, for any state specific behaviors that need to be called from an update function; and Exit, to clean up after, such as resetting variables or deactivating components. &lt;/p&gt;

&lt;p&gt;Next, we create a &lt;a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/using-delegates"&gt;delegate&lt;/a&gt;  State function that takes in 3 arguments; the FSM, the step, and the state. We can use this to create our own functions that act as a State. In our character's class, we would simply have to create a function that shares this signature. &lt;/p&gt;

&lt;p&gt;The first method of our FSM starts the finite state machine running. The object using the FSM is not in any state until this method is called. For a class that uses our FSM to determine a game objects behavior, we would normally want that to be active as soon as possible after the game object is spawned. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;OnUpdate&lt;/code&gt; is what you'd expect- it invokes any behavior specified in the Update section of an FSM State function. What this means for our character's class is that we want to be calling our &lt;code&gt;fsm.onUpdate&lt;/code&gt; function in one of the &lt;code&gt;Update&lt;/code&gt; functions provided to us by Unity.&lt;/p&gt;

&lt;p&gt;Finally, as you also might have guessed, TransitionTo exits from the current state, then grabs the new state and transitions to it, which will run any of the code defined in the new state's Enter section before it reaches the code in that state's Update section.&lt;/p&gt;

&lt;p&gt;That's all we need for our own finite state machine! &lt;/p&gt;

&lt;p&gt;To create a class that uses our FSM, in our script we would create an instance of FSM and set it equal to a new FSM, and call its &lt;code&gt;StartFSM&lt;/code&gt; function with an argument of the state to start in, like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Player
{
    FSM fsm;
    FSM.State walking;

    void Awake()
    {
        fsm = new FSM();
        walking = FSM_Walking;
    }
    void Start() 
    {
        fsm.StartFSM(walking);
    }

    void FSM_Walking(FSM fsm, Step step, State state)
    {
        if(step == FSM.Step.Enter)
        {
             //setup code for the state
        }
        else if (step == FSM.Step.Update) {...}
        //and so on with exit
    }

    void FixedUpdate()
    {
        fsm.OnUpdate();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  The State pattern
&lt;/h3&gt;

&lt;p&gt;FSMs like the one in the example above are very useful, and they're definitely a step above creating tons of variables that must be set and reset multiple times throughout a script. However, using our FSM comes with its own problems. For one, if we wanted to add, say, a Swimming state to our character, we would have to reevaluate our entire state system to determine allowed transitions to and from the swimming state, which means messing with our Enter and Exit code for each state. It would be better if we could add or remove a state without having to redo a bunch of code to account for the new or removed state. Also, in our game objects script, we may have a lot of variables that are specific to a state, which makes our character script have a lot of responsibility. In Unity, and in object-oriented languages like C# or Ruby, it's often better to use a single-responsibility or component system where each class has one specific responsibility. Controlling for many states in a class sounds like a great candidate for separating some of that logic out of the Player class and into their own more specialized classes. &lt;/p&gt;

&lt;p&gt;This is a better State pattern. Instead of many little FSM's running around in each game object containing the same repeated state logic, each state becomes its own class that implements an interface which provides all the step methods we named in our original FSM script, like &lt;code&gt;onUpdate&lt;/code&gt;. The individual game objects only have to worry about which state they are in rather than all the possible states they can be in. Any variables that are only used while in a certain state can be moved to that state's class and out of the Player script. &lt;/p&gt;

&lt;p&gt;To do this, we first need to create an interface for all of our state's to implement, like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface IStateMachine 
{
    void Enter(Player player);
    void Update(Player player);
    void Exit(Player player);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And this is an example for a State class that implements the &lt;code&gt;IStateMachine&lt;/code&gt; interface:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class JumpingState : PlayerStateMachine
{
    public void EnterState(Player player)
    {
        Debug.Log("Entering Jumping State");
        // Any setup or initialization code for jumping state goes here
    }

    public void UpdateState(Player player)
    {
        // Update logic for jumping state
        // For example, apply jump force, handle jump duration, etc.
        Debug.Log("Jumping...");
    }

    public void ExitState(Player player)
    {
        Debug.Log("Exiting Jumping State");
        // Any cleanup or reset code for jumping state goes here
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Assuming we have created a walking and jumping state, this is how we might write our code to utilize the different states and switch between them:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Player : MonoBehaviour
{
    private IStateMachine currentState;

    private void Start()
    {
        // Initialize the player with the Walking state
        currentState = new WalkingState();
        currentState.EnterState(this);
    }

    private void Update()
    {
        // Check for input or any other conditions to change states
        if (Input.GetKeyDown(KeyCode.Space))
        {
            // Switch to Jumping state if the player presses the jump button
            currentState.ExitState(this);
            currentState = new JumpingState();
            currentState.EnterState(this);
        }

        // Update the current state
        currentState.UpdateState(this);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It's that easy! This makes our &lt;code&gt;Player&lt;/code&gt; script much cleaner. And it's now very easy to add or remove different states if our game changes. &lt;/p&gt;

&lt;h3&gt;
  
  
  That's it!
&lt;/h3&gt;

&lt;p&gt;And there you have it: the State pattern. It's a pretty handy pattern for controlling the behavior of the various game objects in our game in a modular and easy to manage way. &lt;/p&gt;

&lt;p&gt;It's important to point out that this pattern isn't always necessary; it depends on what you're making, how complex it is, and what your needs are. A simple FSM or even a few boolean values can work for a small project. It's important to understand the differences between them to determine which solution is best for you given the circumstances! Also, feel free to comment if you have additional info, or if I got something wrong. &lt;/p&gt;

&lt;p&gt;If I was unclear or if you'd like to read more about the State pattern, I definitely recommend checking out &lt;a href="https://gameprogrammingpatterns.com/state.html"&gt;this&lt;/a&gt; resource for an overview of the State pattern, and &lt;a href="https://gamedevbeginner.com/state-machines-in-unity-how-and-when-to-use-them/"&gt;this&lt;/a&gt; one for another really thorough explanation. &lt;a href="https://aliemreonur.medium.com/state-pattern-in-unity-973ea0b6ddef"&gt;This&lt;/a&gt; one is great if you want to know more about having State classes inherit from a BaseState class, if you'd rather go that route. &lt;/p&gt;

</description>
      <category>gamedev</category>
      <category>beginners</category>
      <category>designpatterns</category>
      <category>unity3d</category>
    </item>
    <item>
      <title>Level Up Your React Projects: A Beginner's Guide to Custom Hooks</title>
      <dc:creator>zigzagoon1</dc:creator>
      <pubDate>Fri, 31 Mar 2023 22:24:45 +0000</pubDate>
      <link>https://dev.to/zigzagoon1/level-up-your-react-projects-a-beginners-guide-to-custom-hooks-2m77</link>
      <guid>https://dev.to/zigzagoon1/level-up-your-react-projects-a-beginners-guide-to-custom-hooks-2m77</guid>
      <description>&lt;h2&gt;
  
  
  Brief Intro to Hooks In React
&lt;/h2&gt;

&lt;p&gt;For those of you who know or are learning React, you likely already know about React hooks. We use the &lt;code&gt;useState&lt;/code&gt; hook in order to create variables that trigger a re-render of the component should they be changed. We use the &lt;code&gt;useEffect&lt;/code&gt; hook to run code after the initial render, often to fetch data from an API and then trigger a re-render once the data is received. And there many more. But you may not know that you can create custom hooks, or it may not be clear when a custom hook would be useful. Hopefully this article helps you understand some good cases to use a custom hook. First, I'm going to go over how hooks work to help us to better understand how to create our own, then we can get to the examples.   &lt;/p&gt;

&lt;h2&gt;
  
  
  How Hooks Work
&lt;/h2&gt;

&lt;p&gt;Hooks work by taking advantage of the concept of &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures"&gt;closure&lt;/a&gt;. Closure is a feature of JavaScript that allows functions to remember and access their surrounding scope (variables declared outside the function) even when they are called outside of that scope. Closures can be confusing to understand at first. If you aren't quite sure what closure is and the above doesn't help, please check out &lt;a href="https://tkdodo.eu/blog/hooks-dependencies-and-stale-closures"&gt;this&lt;/a&gt; source which describes closure with an analogy of taking a photo, which could really help make it click. Also, &lt;a href="https://dmitripavlutin.com/react-hooks-stale-closures/"&gt;this&lt;/a&gt; one that goes over stale closure and how to avoid it. &lt;a href="https://www.netlify.com/blog/2019/03/11/deep-dive-how-do-react-hooks-really-work/"&gt;This&lt;/a&gt; source also goes over creating our own implementations of existing React hooks in depth, so we can see closure in action in the context of React hooks specifically.&lt;/p&gt;

&lt;p&gt;Hooks use closure in a few different ways, depending on the hook. For example, the useState hook works by creating stateful variables and state update functions. When the state update function is called, it has access to the current state value through closures, which allows it to update the state correctly even though it's outside of the component's local scope. The reason we pass a function to hooks like &lt;code&gt;useEffect&lt;/code&gt; is to create a closure of the necessary variables in the local component scope that can then be used in the scope of the &lt;code&gt;useEffect&lt;/code&gt; hook. While they may seem similar, Props passed from a parent to a child component do not directly use closure. However, it is sometimes the case that we define a function in the parents scope that references local variables and then pass that function to a child component as a callback. In this case, the child then has access to any of the parents variables from within the function. In this case, Props do take advantage of closure. &lt;/p&gt;

&lt;p&gt;It is important to mention that while closure is an important feature in most hooks, our custom hooks can call other hooks- that means that instead of creating our own closure around variables and functions, we can also call &lt;code&gt;useState&lt;/code&gt; in our custom hook to create stateful variables for us. Also, if we are considering code for a custom hook and it has any JSX in it, that code is not suited for a custom hook and should remain as a component. &lt;/p&gt;

&lt;p&gt;Another important feature about hooks to remember is that they must always be called in the same order, or they won't work. That is why you must place calls to a hook in the top-level of the component, and not inside any conditionals or statements. If one call is inside a conditional that no longer executes after the first render, React will still be expecting that call and assign it to the next call instead, creating errors. &lt;/p&gt;

&lt;h2&gt;
  
  
  Custom Hooks
&lt;/h2&gt;

&lt;p&gt;Now that we have a better idea of what makes React hooks work, you may be asking when and why we might want to create our own custom hooks. As for &lt;em&gt;why&lt;/em&gt; to create them, custom hooks are great for logic that we use multiple times throughout our components. By moving that logic to a custom hook, we can reuse the logic instead of writing it out each time we need it, reducing the length of our components and improving their readability. However, even if that logic isn't reused multiple times, the code may still be a candidate for being a hook if removing that logic from a component makes that component easier to read and understand.&lt;/p&gt;

&lt;p&gt;When creating a custom hook, we must follow a rule in React for naming them: they must all begin with "use", such as in the first example, &lt;code&gt;useQuery&lt;/code&gt; below. This lets React know that the component should be treated as a hook and follow hook rules. &lt;/p&gt;

&lt;p&gt;The following examples demonstrate great cases of &lt;em&gt;when&lt;/em&gt; to use them, I hope they come in handy and inspire you to find other ways of using custom hooks in your own projects! &lt;/p&gt;

&lt;h2&gt;
  
  
  Examples
&lt;/h2&gt;

&lt;p&gt;The examples I will cover in this article will provide a basic understanding of the logic behind each type of hook. However, you may want to make additional adjustments to tailor each hook to your specific needs. I will also mention potential enhancements for each example to help you get started. If you have any suggestions on how to further improve these examples, please feel free to leave a comment!&lt;/p&gt;

&lt;h4&gt;
  
  
  useQuery
&lt;/h4&gt;

&lt;p&gt;One common potential use case for a custom hook is to separate out our logic for fetching data into its own hook. Here's how our &lt;code&gt;useQuery&lt;/code&gt; hook might look:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;useEffect&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;react&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;useQuery&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;url&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setData&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;([]);&lt;/span&gt;

  &lt;span class="nf"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;fetch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;url&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
      &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;r&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;r&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;json&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
      &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nf"&gt;setData&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
      &lt;span class="p"&gt;});&lt;/span&gt;
  &lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;url&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;

  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="nx"&gt;useQuery&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In our components, we could then simply call this hook with an argument for the URL to use in the fetch, and we'll get back our data. This saves us from having to write out a fetch request every time we need to get data from a server throughout our components. This example isn't perfect, but it shows the general idea. To improve it, we could add handling of errors with &lt;code&gt;.catch&lt;/code&gt;, cache our fetched data to prevent unnecessary network requests, or setup a canceling of the fetch should the component un-mount before the fetch is complete.&lt;/p&gt;

&lt;h4&gt;
  
  
  useTitle
&lt;/h4&gt;

&lt;p&gt;Often, when a user navigates to a new page in our React app, we want to change the title displayed in the tab. While this is a simple to create in each component that needs it, it's a good candidate for being its own hook. Here's how we could make it as a custom hook:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;react&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;useTitle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;title&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nf"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;title&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;title&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;title&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="nx"&gt;useTitle&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pretty straightforward, I hope. The next one I'll talk about is a hook for keeping track of the mouse position within the browser window.&lt;/p&gt;

&lt;h4&gt;
  
  
  useMousePosition
&lt;/h4&gt;

&lt;p&gt;Sometimes it's useful to know the mouse position, such as when placing tooltips relative to the mouse position, or drag and drop functionality. The mouse position is also important for zooming in and out on a specific area of interest, or when creating drawing applications, and many other situations. Here's a custom hook to keep track of its position, and it will update as that position changes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;useEffect&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;react&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;useMousePosition&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;mousePosition&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setMousePosition&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;x&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;y&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="p"&gt;});&lt;/span&gt;

  &lt;span class="nf"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;handleMouseMove&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nf"&gt;setMousePosition&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;x&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;clientX&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;y&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;event&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;clientY&lt;/span&gt; &lt;span class="p"&gt;});&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;addEventListener&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;mousemove&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;handleMouseMove&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;return &lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;removeEventListener&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;mousemove&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;handleMouseMove&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;};&lt;/span&gt;
  &lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;[]);&lt;/span&gt;

  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;mousePosition&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using this custom hook to keep track of mouse position saves us from having to re-write the same logic over and over as well as reducing clutter in our components. &lt;/p&gt;

&lt;h4&gt;
  
  
  useToggle
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;useCallback&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;react&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;useToggle&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;initial&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;  
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;open&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setOpen&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;initial&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;   

  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;open&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;useCallback&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;setOpen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;status&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;status&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;[])];&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="nx"&gt;useToggle&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, for any components that use &lt;code&gt;useToggle&lt;/code&gt;, we return a bool of whether the toggle is open or not, as well as a function to set the status of the toggle to open or closed depending on its state at the time. Notice we wrapped the returned function in a &lt;code&gt;useCallback&lt;/code&gt; hook. The &lt;code&gt;useCallback&lt;/code&gt; hook memoizes the callback function, and only re-creates the function if any dependencies specified in the dependency array have changed. In this case, we have no dependencies, so we provide an empty array.&lt;/p&gt;

&lt;p&gt;However, React ensures that the value of &lt;code&gt;status&lt;/code&gt; in our setter function is always the current value for &lt;code&gt;open&lt;/code&gt;, due to us passing a function to &lt;code&gt;setOpen&lt;/code&gt; rather than directly providing a value. This is called a functional state update, and you can read more about how it works &lt;a href="https://betterprogramming.pub/you-dont-know-usestate-until-you-ve-used-functional-updates-5da52117620f#:~:text=Functional%20update,called%20a%20%E2%80%9Cfunctional%20update.%E2%80%9D"&gt;here&lt;/a&gt;. And for more information on memoization and how it works, check out &lt;a href="https://codeburst.io/understanding-memoization-in-3-minutes-2e58daf33a19"&gt;this&lt;/a&gt; helpful article. &lt;/p&gt;

&lt;h3&gt;
  
  
  Wrapping Things Up
&lt;/h3&gt;

&lt;p&gt;I hope my overview of how hooks worked and the examples I provided helped you in understanding both hooks overall as well as how and when custom hooks can come in handy. There are many, many more uses for custom hooks- the possibilities are endless! I highly recommend checking out some of the links below for some great, ready-made custom hooks that you can use in your projects. The examples I provided are really only the tip of the iceburg! If you're a beginner, some may seem too complicated and you may have no use for them at this point, but I highly recommend bookmarking the pages for later use! &lt;/p&gt;

&lt;h3&gt;
  
  
  Further reading:
&lt;/h3&gt;

&lt;p&gt;For an extensive list of use cases for custom hooks, I recommend checking out &lt;a href="https://github.com/streamich/react-use"&gt;streamich&lt;/a&gt;'s GitHub page, where you can get a bunch of custom hooks already made! For even more, check out &lt;a href="https://betterprogramming.pub/react-custom-hooks-with-real-life-examples-c259139c3d71"&gt;this&lt;/a&gt; and &lt;a href="https://usehooks.com"&gt;this&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;For more information on hooks themselves, I recommend &lt;a href="https://codersociety.com/blog/articles/react-hooks"&gt;codersociety's&lt;/a&gt; post on the benefits of React hooks over class components. &lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>programming</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Programming Patterns for Games: Singleton</title>
      <dc:creator>zigzagoon1</dc:creator>
      <pubDate>Wed, 15 Mar 2023 22:39:04 +0000</pubDate>
      <link>https://dev.to/zigzagoon1/programming-patterns-for-games-singleton-1be1</link>
      <guid>https://dev.to/zigzagoon1/programming-patterns-for-games-singleton-1be1</guid>
      <description>&lt;h2&gt;
  
  
  Welcome back!
&lt;/h2&gt;

&lt;p&gt;This is post number two of my introduction to programming patterns for games. This time I'm going to focus on a pattern known as singleton. &lt;/p&gt;

&lt;h4&gt;
  
  
  Introduction to the Singleton Pattern
&lt;/h4&gt;

&lt;p&gt;The singleton pattern is used to create a public script in such a way that there is only ever one &lt;em&gt;instance&lt;/em&gt; of it. This allows any other script to reference it, but ensures that it is always the same instance, as there can never be more than one in a game's scene. But be warned- there are very specific situations where using singletons is a good idea, but it can do more harm than good when used incorrectly; often, another solution should be used instead. I will cover some of the good and the bad of singletons in this post. &lt;/p&gt;

&lt;h4&gt;
  
  
  Example of a Singleton in Unity
&lt;/h4&gt;

&lt;p&gt;To explain the usefulness of a singleton, let's get ourselves in the shoes of a developer. Imagine you're trying to have different characters play different sounds when triggered. Let's say this game has a player character that makes a sound when it jumps, there's a cat that meows, and enemies that go "grrr" normally, but when they're killed, go "eurgh". In order to play these different audio clips, we could have a script on each separate character that controls when it's own sound is played. This is valid, and games sometimes use this solution, but it does have drawbacks. For one, if each enemy script controls its own sound, and there are hundreds or thousands of enemies, this could lead to duplicate code and performance issues. It can also be trickier to debug any problems with the sounds being played if the control of audio is spread out across multiple scripts. Instead, let's see if we can have one manager script which contains our sound effects and is responsible for playing them when asked. One of the &lt;em&gt;easiest&lt;/em&gt; ways to do this is to use a singleton. A basic singleton in the Unity game engine, using our audio example, looks something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class AudioManager
{
    public static AudioManager instance;

    //Awake is called at the start of the game loop, see my post 
    //about the Game Loop pattern for more info! 
    void Awake() {
       if (instance != null &amp;amp;&amp;amp; instance !== this) 
       { 
           Destroy(gameObject);
       }
       else 
       {
           instance = this;

           //the line below isn't necessary for singletons, but I 
           //added it as it is often the case that we want our 
           //singletons to persist throughout all game scenes! 
           DontDestroyOnLoad(gameObject);
       }
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I'll break it down. We have a class called AudioManager. The first line in the code block creates a public static object of class AudioManager that I called instance, which is a common name you'll see for singletons, though not the only one. Being public and static means that other scripts can easily access our &lt;code&gt;instance&lt;/code&gt; through the Audio Manager class. Then, in &lt;code&gt;Awake()&lt;/code&gt;, we check if instance is equal to null. If you're not sure what &lt;code&gt;Awake()&lt;/code&gt; is, &lt;a href="https://dev.to/zigzagoon1/programming-patterns-for-games-game-loop-4goc"&gt;here&lt;/a&gt; is my post explaining it and the rest of Unity's game loop. If our instance isn't null &lt;em&gt;and&lt;/em&gt; it isn't equal to the instance that we're in, that means that there is already an instance of our AudioManager out there. Since the point of a singleton is to only ever have one, we destroy the current one to avoid having a duplicate. If, however, instance is equal to null, then we create this script as our one instance of the Audio Manager. &lt;code&gt;DontDestroyOnLoad&lt;/code&gt; is a useful addition if we would like our script to persist across all scenes in the game, such as with a GameManager script. However, not all cases of the singleton pattern will need this part of the script. &lt;/p&gt;

&lt;p&gt;An even better implementation of our singleton class would be to make our instance variable a property, like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static AudioManager Instance {get; private set;}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This makes our &lt;code&gt;Instance&lt;/code&gt; a public property, so it's still accessible to other scripts, but having a private set ensures that only the AudioManager script can set itself as Instance, and no other script can change it on us. &lt;/p&gt;

&lt;p&gt;By ensuring there is only ever one of its class in our game's scene, we avoid unpredictable behavior and bugs that come from scripts accessing different instances of our AudioManager script. And instead of hundreds or thousands of references to the same audio clips on each enemy script, we're now down to one single reference that can be used from any script by referencing &lt;code&gt;AudioManager.instance&lt;/code&gt;. In this way, any methods or variables available in our &lt;code&gt;AudioManager&lt;/code&gt; script become available through &lt;code&gt;AudioManager.instance&lt;/code&gt;. This way, we can store a reference to our 'eurgh' sound in AudioManager, and then when one of the enemies dies, we can simply do &lt;code&gt;AudioManager.instance.PlaySound(AudioManager.instance.eurgh)&lt;/code&gt;. Easy as ...eurgh! (Let's just assume that makes sense).&lt;/p&gt;

&lt;p&gt;As you can see, a singleton is essentially a global variable of a class that there is only one instance of at any time. This is extremely useful for accessing scripts that you &lt;em&gt;know&lt;/em&gt; you only ever want one of and a great way to solve a common problem that regularly comes up in game development: our scripts often need to interact with each other. Think about it- when your player uses a weapon to attack an enemy, you need to have a player script that tells a projectile script to go in the direction the player script aimed it, and if that projectile hits an enemy, you need that enemy script to know to take damage to its health and display some kind of visual effect or animation in response, or play a sound, sometimes using other scripts to do so. What a given object needs to do at any given time heavily depends on its interactions with other objects and their scripts. The problem is determining how to efficiently communicate with the correct script in order to update its behavior, and that is why singletons can be very useful.&lt;/p&gt;

&lt;p&gt;This may make it tempting to use the singleton pattern for any such problem. But you must resist that temptation! Singletons should only be used in relatively rare circumstances, if at all. In fact, if you were to Google the singleton pattern, a lot of the results will be people telling you to not use them &lt;em&gt;ever&lt;/em&gt;. I err on the side of use-with-caution rather than not at all. For example, I think the singleton pattern is a great choice for Manager scripts where you know you only ever want one of and that control a specific area of your game, such as AudioManagers, SaveManagers, and the like, but there are plenty out there who would disagree with even that use case. &lt;/p&gt;

&lt;h4&gt;
  
  
  The Problems With Using the Singleton Pattern
&lt;/h4&gt;

&lt;p&gt;A good example of a case where the singleton pattern would not likely be a good choice is with a player's script. Often in games, many scripts need to interact with the player script in some way. With our handy-dandy singleton pattern, we could make that easy! However, if we were to make our player script into a singleton, our game becomes far less flexible. Once we've decided to make a class a singleton, it becomes very difficult and tedious to change that should we want to. If, down the road, we decided to implement a multiplayer feature, we would run into problems with our singleton class only allowing one instance of a player at a time. We would have to completely change how our player script interacts with all other scripts to even begin implementing multiplayer functionality, which would be a time-consuming task that could have been avoided. It takes many months or years to make a game- imagine having to redo how the main game object gets and shares its information with all other scripts. Yikes! This is why it's important to be sure there are no features you might like to add down the road that would require you to re-do your singletons before committing to using the pattern. It's worth noting that having multiple Player scripts would not be an ideal solution, either, and implementing some sort of player or multiplayer manager, which could itself then be a singleton, would be better in the case of multiplayer games.&lt;/p&gt;

&lt;p&gt;Another more obvious example would be using a singleton to make any sort of projectile or enemy script. Sure, those scripts need to communicate with other scripts and a singleton would make that easy, but then you'd be limited to only ever having one projectile or one enemy script at a time! However, a ProjectileManager or EnemyManager script would potentially be suitable scripts for a singleton pattern, so long as you carefully consider your options and recognize the potential consequences first. Whether it's a good fit will be different for every game.&lt;/p&gt;

&lt;p&gt;There are other reasons why you might not want to use a singleton pattern for a class, such as its globally accessible nature. While this may seem convenient and be a part of what attracts people to using singletons in the first place, in the long term it can make for some tedious debugging sessions. Global variables can be accessed by &lt;em&gt;any&lt;/em&gt; script- if you are running into problems with your singleton instance not behaving correctly, you have to go through and find all references to that singleton throughout your code to figure out where the problem lies; there are more opportunities for things to go wrong when anyone can use it. This global availability also makes it difficult to use with games that take advantage of multi-threading capabilities. If scripts are accessing your singleton asynchronously, there may be issues where you are getting incorrect information or unexpected behavior, known as a &lt;a href="https://www.howtogeek.com/devops/what-is-a-race-condition/" rel="noopener noreferrer"&gt;race condition&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Another feature of singletons that seems great at first, that there is only ever one instance, can also be a problem for unit testing, when you would usually need to create multiple instances.&lt;/p&gt;

&lt;p&gt;For more information about the disadvantages of singletons and ways to cope with them, see &lt;a href="https://methodpoet.com/disadvantages-of-singleton-pattern/" rel="noopener noreferrer"&gt;methodpoet's&lt;/a&gt; article about the subject, or &lt;a href="https://hackernoon.com/singleton-pattern-the-root-of-all-evil-e4r3up7" rel="noopener noreferrer"&gt;this&lt;/a&gt; article that very much discourages the use of singletons. &lt;/p&gt;

&lt;h4&gt;
  
  
  To Sum it All Up...
&lt;/h4&gt;

&lt;p&gt;The singleton pattern is best used only in circumstances where you are &lt;em&gt;sure&lt;/em&gt; you will not need to change the functionality of that class at any point later on, and even then, it doesn't hurt to evaluate your needs and see if there's a better solution. As I said before, the best use cases and the ones you would most likely see the singleton pattern used with are for various manager scripts, such as our AudioManager. Another common one used is the GameManager, which often holds the state of the game, like whether it is playing or paused, or possibly stores information that must be used across different game scenes. Speaking of scenes, another very common singleton use-case is a SceneManager, which controls transitioning between scenes. However, every game is different, and the singleton pattern may not be appropriate for even these common uses, as it can have problems that stem from its global accessibility and single-instance nature. I highly recommend doing some further research on the singleton pattern to ensure you understand the pros and cons fully to determine if it is the right choice for you and the script you're working on. In the right circumstances, the singleton pattern can be a huge help- but when used incorrectly, it's more of a huge headache!&lt;/p&gt;

&lt;h4&gt;
  
  
  Key-Takeaways
&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt;Singleton pattern is best used when you are certain that a class will not need to change its functionality later on.&lt;/li&gt;
&lt;li&gt;Common use cases for the singleton pattern include manager scripts like AudioManager, GameManager, or SceneManager.&lt;/li&gt;
&lt;li&gt;The global accessibility and single-instance nature of singletons can create problems if used incorrectly.&lt;/li&gt;
&lt;li&gt;Research the pros and cons of the singleton pattern before implementing it in your game development project.&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  Reach Out!
&lt;/h4&gt;

&lt;p&gt;Let me know in the comments if you agree or disagree, and why! I'd love to hear your experiences of when the singleton pattern was more of a nightmare than helpful. Also, feedback on the structure of this article and how I can improve is always appreciated! &lt;/p&gt;

&lt;h4&gt;
  
  
  More Resources on the Singleton Pattern
&lt;/h4&gt;

&lt;p&gt;If you're interested in reading more about the pattern, I recommend &lt;a href="https://gameprogrammingpatterns.com/singleton.html" rel="noopener noreferrer"&gt;this&lt;/a&gt; resource. For more examples of the variety of implementations of the singleton pattern, check out &lt;a href="https://www.c-sharpcorner.com/UploadFile/ff2f08/singleton-design-pattern/" rel="noopener noreferrer"&gt;C-Sharp Corner&lt;/a&gt;. You may also be interesting in &lt;a href="https://www.codeproject.com/Articles/307233/Singleton-Pattern-Positive-and-Negative-Aspects-2" rel="noopener noreferrer"&gt;this overview&lt;/a&gt; of the pattern as well. And for more info about using singletons in Unity, check out &lt;a href="https://gamedevbeginner.com/singletons-in-unity-the-right-way/#:~:text=Generally%20speaking%2C%20a%20singleton%20in,or%20to%20other%20game%20systems." rel="noopener noreferrer"&gt;GameDevBeginner&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>tutorial</category>
      <category>discuss</category>
    </item>
    <item>
      <title>Using 'innerHTML' in JavaScript</title>
      <dc:creator>zigzagoon1</dc:creator>
      <pubDate>Sun, 05 Feb 2023 18:11:21 +0000</pubDate>
      <link>https://dev.to/zigzagoon1/using-innerhtml-in-javascript-2h51</link>
      <guid>https://dev.to/zigzagoon1/using-innerhtml-in-javascript-2h51</guid>
      <description>&lt;p&gt;When working on a project recently, I stumbled on an issue where things weren't working as expected and I didn't understand why. As developers, we've all been there. Fortunately, with this particular issue I got lucky and it didn't take me very long to figure out what the problem was. I decided to share the details here to hopefully help somebody else facing similar issues!&lt;/p&gt;

&lt;p&gt;The problem had to do with me using JavaScript to access and change an HTML elements' &lt;code&gt;innerHTML&lt;/code&gt;, or more specifically, using &lt;code&gt;+=&lt;/code&gt; to update the contents of the &lt;code&gt;innerHTML&lt;/code&gt; within a &lt;code&gt;forEach&lt;/code&gt; block. &lt;/p&gt;

&lt;p&gt;I had no idea that using &lt;code&gt;+=&lt;/code&gt; to add content to an elements' &lt;code&gt;innerHTML&lt;/code&gt; could possibly cause issues, and as it turns out after doing some research, I didn't really understand that much about using the &lt;code&gt;innerHTML&lt;/code&gt; property in general. Let's go over the basics of what &lt;code&gt;innerHTML&lt;/code&gt; is now by comparing it to two other properties, &lt;code&gt;innerText&lt;/code&gt; and &lt;code&gt;textContent&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This example comes directly from W3 Schools website on their page about innerHTML, but I think it perfectly demonstrates each property so I'm going to recreate it here. To see the full example plus other information, you can visit &lt;a href="https://www.w3schools.com/jsref/prop_html_innerhtml.asp"&gt;W3Schools&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;HTML:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;p id="myP"&amp;gt; This element has extra spacing    and contains &amp;lt;span&amp;gt;a span element&amp;lt;/span&amp;gt;.&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;JavaScript:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let text = document.getElementById("myP").innerText;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This example with &lt;code&gt;innerText&lt;/code&gt; will return:&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;This element has extra spacing and contains a span element.&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let text = document.getElementById("myP").textContent;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This example with &lt;code&gt;textContent&lt;/code&gt; will return:&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;This element has extra spacing    and contains a span element.&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let text = document.getElementById("myP").innerHTML;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This example with &lt;code&gt;innerHTML&lt;/code&gt; will return:&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;This element has extra spacing    and contains &amp;lt;span&amp;gt;a span element&amp;lt;/span&amp;gt;.&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;As you can see, an elements' &lt;code&gt;innerHTML&lt;/code&gt; includes HTML tags for any children of the element, as well as any text that it or its children contains. This means that, when adding content to an elements' &lt;code&gt;innerHTML&lt;/code&gt;, it is possible to include tags to create child elements, although it's recommended to use &lt;code&gt;appendChild&lt;/code&gt; to add child elements rather than using &lt;code&gt;innerHTML&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;With &lt;code&gt;innerHTML&lt;/code&gt;,  it's even possible to include tags for a script, although W3Schools states than any script tags added to an element using their &lt;code&gt;innerHTML&lt;/code&gt; will not be executed. Unfortunately, it's possible for bad characters to get around this using, for example, an &lt;code&gt;img&lt;/code&gt; tag: they can make it so that their image will never load and provide an &lt;code&gt;onerror&lt;/code&gt; attribute that can then include malicious code that will be executed by the browser when it inevitably produces an error when trying to load the image! This makes using an elements' &lt;code&gt;innerHTML&lt;/code&gt; a security risk, so it is not advisable to add any user-generated content to your site by amending an elements' &lt;code&gt;innerHTML&lt;/code&gt; property. For example, in a comment system, users would be able to write code to hack other users' private information if the developer were to add new user comments to their websites' by adding the comment contents to an elements' &lt;code&gt;innerHTML&lt;/code&gt;! This is when using &lt;code&gt;textContent&lt;/code&gt; or &lt;code&gt;innerText&lt;/code&gt; is a better option. If you must use &lt;code&gt;innerHTML&lt;/code&gt; for some reason, you should sanitize the content before using it. MDN describes a handy function to use for exactly this purpose: &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/setHTML"&gt;&lt;code&gt;SetHTML&lt;/code&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you need to keep HTML markup that would be sanitized by the &lt;code&gt;SetHTML&lt;/code&gt; function but still want the security of knowing there's no harmful content, there is also a helper library from &lt;a href="https://github.com/cure53/DOMPurify"&gt;DOMPurify&lt;/a&gt; that will remove any HTML markup that is not whitelisted. &lt;/p&gt;

&lt;h3&gt;
  
  
  So, what about using += with &lt;code&gt;innerHTML&lt;/code&gt;?
&lt;/h3&gt;

&lt;p&gt;As concerning as the security risk with using &lt;code&gt;innerHTML&lt;/code&gt; is, it's time to get back to the reason I started researching &lt;code&gt;innerHTML&lt;/code&gt;, and the reason for this post. &lt;/p&gt;

&lt;p&gt;When appending to an elements' &lt;code&gt;innerHTML&lt;/code&gt;, the whole element is reparsed. To show what this means, let's look at my code that was not working as expected:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
const td = document.querySelector('#evo_into');
chain.forEach(el =&amp;gt; {
  td.innerHTML += ', &amp;lt;a id="' + el.species['name'] + 
  '"href="user_search_bar"&amp;gt;' + el.species['name'] + '&amp;lt;/a&amp;gt;';
 const element = document.querySelector(`#${el.species['name']}`);
  element.addEventListener('click', function() {...})
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this code, I was trying to add a click event listener for every item within the chain of evolutions (yes, it's a Pokémon project!). This is specifically for cases where one Pokémon can evolve into multiple different Pokémon. So, for each evolution, I was adding an &lt;code&gt;a&lt;/code&gt; element with the text being equal to the name of the Pokémon, and the link just bringing the user back to the top of the page. I then attempted to add an event listener on each evolutions element that would load more information about that specific Pokémon to the DOM when the link is clicked. However, I was confused to find that none of the event listeners worked except the very last one! Why might this be? Well, because appending to the innerHTML reparses the entire content of the &lt;code&gt;innerHTML&lt;/code&gt; string, each time the code in the &lt;code&gt;forEach()&lt;/code&gt; block was run and I used &lt;code&gt;+=&lt;/code&gt; to append to the &lt;code&gt;innerHTML&lt;/code&gt;, all the elements that I had created before that were essentially recreated, except, of course, the code to create their event listener was not re-executed. This is why only the last element in the evolution list had a working click event listener; there were no more additions to the &lt;code&gt;innerHTML&lt;/code&gt;, and the element was not reparsed again, leaving one intact event listener. &lt;/p&gt;

&lt;p&gt;To solve this, I simply created a string that I added to with each cycle of the &lt;code&gt;forEach()&lt;/code&gt; block, and after that block I added the entire string to the innerHTML and created the event listeners after that. This is of course just one way I could have solved this problem; another solution I might have gone with would be to make use of a handy function, &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML"&gt;&lt;code&gt;insertAdjacentHTML&lt;/code&gt;&lt;/a&gt; that would allow me to specify where in the element I wanted to insert my new HTML content, preserving the previous content as-is and therefore keeping any existing event listeners active. &lt;/p&gt;

&lt;p&gt;As developers, we often come across errors or unexpected behavior in our code that can be frustrating to say the least! But it's important to remember that these mistakes are an opportunity to learn and understand more about our code. Without this experience, I may never have done research into using &lt;code&gt;innerHTML&lt;/code&gt;, and in the future I might have misused it in a way that was dangerous to any users of my websites without realizing it! My mistake helped me grow as a developer, and I hope the experience can help other new developers out there as well. Thanks for reading! &lt;/p&gt;

</description>
      <category>html</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Programming Patterns for Games: Game Loop</title>
      <dc:creator>zigzagoon1</dc:creator>
      <pubDate>Thu, 26 Jan 2023 20:05:27 +0000</pubDate>
      <link>https://dev.to/zigzagoon1/programming-patterns-for-games-game-loop-4goc</link>
      <guid>https://dev.to/zigzagoon1/programming-patterns-for-games-game-loop-4goc</guid>
      <description>&lt;h2&gt;
  
  
  Welcome to my first blog post!
&lt;/h2&gt;

&lt;p&gt;My name is Kelly, though I often use the name zigzag online. I started teaching myself C# and JavaScript about two years ago, and in doing so found my passion. Now, I'm enrolled at Flatiron School, and working hard on achieving my dreams of being a game developer! &lt;/p&gt;

&lt;p&gt;Have you ever wondered how video games work behind the scenes? I know I did, it's why I learned programming in the first place. Games always seemed like magic, and I just had to find out the secret behind the trick. It turns out there are quite a lot of interesting things going on behind the scenes! While each game has numerous unique qualities, there are certain general patterns that pop up in many of them. Over the next few posts, I'm going to discuss a few of the programming patterns that make games what they are. Not every game uses every pattern I'll introduce, but most use at least some of them, and almost all of them use the first one I'm going to talk about - the Game Loop.&lt;/p&gt;

&lt;h5&gt;
  
  
  What are programming patterns anyway?
&lt;/h5&gt;

&lt;p&gt;Programmers are constantly solving the &lt;em&gt;problem&lt;/em&gt; of how to communicate with the computer to have it do what they want it to do. This problem solving can get quite complex, and certain features will always require unique solutions. While this is unavoidable, a developer regularly runs into problems that can be solved with the same basic solutions. These are referred to as programming patterns - generalized and reusable solutions that can be used repeatedly in different contexts. The patterns I'll discuss are most common in games, but these and other programming patterns aren't exclusive to games.&lt;/p&gt;

&lt;h5&gt;
  
  
  The Game Loop
&lt;/h5&gt;

&lt;p&gt;One major problem that is nearly universal across all games is how to present the player with a smooth, continuously moving and progressing world in real time. While games aren't the only things that can have this feature, the use of the game loop pattern is used relatively little outside of game development.&lt;/p&gt;

&lt;p&gt;While it may be rare for other programs, most of the games we know and love wouldn't exist without the use of this pattern! Don't believe me? Think of a game you like. Does this game completely stop and wait for your input to continue? Or do the characters or background scenes continue animating and moving whether you supply input or not? If your game can continue its various game behaviors, has a concept of time, allows you to pause, or plays music or sounds without your input, it's using the game loop in one way or another. If you don't pause, Mario can definitely still be killed by that Goomba whether you're at the controls or not! Games that use a game loop pattern can process user input, but don't stop and wait for it. Even turn-based games usually continue animating the scene or characters in some way and provide audio and sound effects while waiting for user input. The game loop is what allows these updates to happen continuously over time.&lt;/p&gt;

&lt;p&gt;How quickly your game goes through a complete loop is something you may have heard of before- the frames per second, or FPS. If you're playing a game at 30 FPS, without complicating things, this would mean your game is completing 30 game loops per second (I'll discuss why that's not always quite the case later!). In each loop, it updates the scene- if you press a button to jump, each loop updates the position your character is in. Even if you let go of that jump button, your character may continue to jump, or begin to fall; these are all physics calculations that are updated by steps in each loop.&lt;/p&gt;

&lt;p&gt;Even the most basic game loops include a function, often called &lt;code&gt;Update&lt;/code&gt;, or &lt;code&gt;Tick&lt;/code&gt;, which takes care of anything that needs to be updated in steps each frame. Think about the jumping character again- for it to look like it’s jumping, it must start on the ground, begin to rise, come to its apex, then fall back down to the ground. To achieve this, the jump action has to be updated in steps each frame; it has to take some &lt;em&gt;time&lt;/em&gt; in order to create the appearance of a jumping character. That's the purpose of &lt;code&gt;Update&lt;/code&gt;. If you create your own game loop, it needs an update function. If you use someone else's game engine, such as Unity's, it provides you with an update function to use as needed. Other core features of a game loop include a function to process user input, which then influences the data in the update function, and a rendering function, which draws the game at the state it's in according to the most recent update function.&lt;/p&gt;

&lt;p&gt;The simplest possible game loop looks something like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

while (true)
{
    processInput();
    update();
    render();
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;But most games won't have a simple loop like this, as it creates some pretty critical issues. With this loop, you have no control over how fast the loop runs; if you have a fast computer, updates may occur too quickly for you to see what's going on, while if you have a slow computer, updates may crawl along at a painfully slow rate. To deal with this variability, we spread loops out over a certain amount of real time, the duration of which is sometimes measured in frames per second. We must include a &lt;em&gt;variable&lt;/em&gt; or &lt;em&gt;fluid&lt;/em&gt; time step to our loop, like so:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

double previousTime = getCurrentTime();
while (true)
{
  double current = getCurrentTime();
  double elapsed = current - previousTime;
  processInput();
  update(elapsed);
  render();
  previousTime = current;
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In this game loop, before the loop begins, we get the current time and store it in a global variable that can be accessed within the loop. Then, in the loop, we get the current time again, and subtract the original time from the current time to determine how much time, in milliseconds, has elapsed. &lt;/p&gt;

&lt;p&gt;This is used in an interesting way! Notice how this elapsed time is passed as an argument to the update function. This allows the update function to calculate how big of a "step" it has to take in order to keep up with where it should be. If we know how many frames we need to have per second, say, a target of 30 FPS, we can then use the real time since the loop last ran to determine if our computer is keeping up, and adjust the size of the step accordingly. If our computer is fast, it updates normally. If our computer is slow and can't update or advance the game quickly enough - in other words, if game time is lagging behind the real time -, we can use the real amount of time passed to tell our update function it needs to take a bigger step, and advance the game further in each call to update than our fast computer. &lt;/p&gt;

&lt;p&gt;Seems easy enough, right? Well, unfortunately this loop presents its own problems. In a multiplayer game, for instance, if two characters fire a weapon from the same start location, it might end up in different locations depending on each computer being used! This is because game engines mostly use floating point numbers, which are subject to inaccuracies and rounding errors- the more calculations that are done with these slightly-off floating point numbers, the greater the error might be. In our loop, a fast computer may be calling &lt;code&gt;update&lt;/code&gt; at our desired 30 FPS (or more), while a slow computer may use fewer calls to &lt;code&gt;update&lt;/code&gt; to do the same thing. This means that with each of our 30 calls to &lt;code&gt;update&lt;/code&gt;, the calculations get more and more inaccurate, and will therefore produce a different end result than a slower computer that only uses a few calls!&lt;/p&gt;

&lt;p&gt;To fix that, we might use something like this: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

double previous = getCurrentTime();
double lag = 0.0;
while (true)
{
  double current = getCurrentTime();
  double elapsed = current - previous;
  previous = current;
  lag += elapsed;

  processInput();

  while (lag &amp;gt;= MS_PER_UPDATE)
  {
    update();
    lag -= MS_PER_UPDATE;
  }

  render(lag / MS_PER_UPDATE);
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In this version, we update lag at the beginning of the frame based on how much real time has passed. We then perform a series of calls to &lt;code&gt;update&lt;/code&gt; until we've caught up, and only then do we render the scene. Sometimes, the call to &lt;code&gt;render&lt;/code&gt; may happen in between two calls to &lt;code&gt;update&lt;/code&gt;, potentially causing an object to appear in the previous spot during an animation and not show any progression. But by passing &lt;code&gt;lag / MS_PER_UPDATE&lt;/code&gt; in to &lt;code&gt;render&lt;/code&gt;, we are telling the render function exactly how far in between the two updates we are, and the renderer can guess the position the object should be in based on interpolation. This method presents its own problems as well! For example, if our object is going to collide with something in the next frame, but our render function doesn't know that because the next update hasn't run yet, it may guess that the object is somewhere where it shouldn't be.&lt;/p&gt;

&lt;p&gt;Professional level game loops are much more complicated and must account for many other factors, such as GPUs and multithreading, and even the different ways that user input is processed across different devices. The details of every game's game loop vary greatly, but the core pattern is always there- process user input, update the scene, and render the scene for the user to see.&lt;/p&gt;

&lt;h5&gt;
  
  
  Example Game Loop- Unity Engine
&lt;/h5&gt;

&lt;p&gt;Now that we've gone over some of the essentials of a core game loop, it's time to see a real example of one that has been used by millions of people! I'll be discussing the core game loop that is used by Unity, a popular game engine for beginners and pros alike. It should be noted that while the core of Unity is written in C++, developers using Unity are generally expected to use C#, and therefore any examples I give from now on will be pseudocode based on C#.&lt;/p&gt;

&lt;p&gt;When you download Unity and begin a new project, this is the core loop that each script you create can use:  &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe4tilfa00dxkwfydyctm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe4tilfa00dxkwfydyctm.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Woah! There's a lot happening there! Our little loops seem inadequate next to Unity's. If it hasn't scared you away yet, bear with me and I'll explain what's going on in this loop. &lt;/p&gt;

&lt;p&gt;Unity designed this loop to give game developers a lot of options as to which part of the loop they want their code to execute in, and a large part of learning to use Unity is learning where different parts of your code should go within this loop. Aside from the greyed-out lines, each line you see in the above loop is a different method or event that your scripts can have access to, so long as they are derived from Unity's MonoBehaviour. So, when creating a class that you want to be able to display and update within a scene, you would simply have it inherit from MonoBehaviour, like this: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

class Example : Monobehaviour 
{
    *Example class stuff here*
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;By default, newly created scripts in Unity inherit from MonoBehaviour, and these scripts must be placed on a GameObject within the scene in order for them to be executed. &lt;/p&gt;

&lt;p&gt;At the start of Unity's loop, you can see three functions, &lt;code&gt;Awake&lt;/code&gt;, &lt;code&gt;OnEnable&lt;/code&gt; and &lt;code&gt;Start&lt;/code&gt;; these are methods that should be used within your script for initializing variables, but because they are called in the order you see in the flowchart, there are subtle differences as to the type of variable initialization to use in each. &lt;/p&gt;

&lt;p&gt;The very first method call we have access to is the &lt;code&gt;Awake&lt;/code&gt; method, which is called when Unity instantiates a GameObject with any MonoBehaviour-derived script attached to it;  as &lt;code&gt;Awake&lt;/code&gt; is called first, you should initialize variables that will be needed by either the same script or other scripts, so that they can be accessible by the time your scripts reach the &lt;code&gt;Start&lt;/code&gt; method. Using &lt;code&gt;Awake&lt;/code&gt; to access other scripts variables will often result in a null reference exception, as the other scripts' &lt;code&gt;Awake&lt;/code&gt; methods may not have been executed yet. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;OnEnable&lt;/code&gt; is called right after instantiation and the &lt;code&gt;Awake&lt;/code&gt; method so long as the script is enabled, and is best used for subscribing to events; similarly, towards the end of Unity's game loop, &lt;code&gt;OnDisable&lt;/code&gt; is best used for unsubscribing from those events. &lt;/p&gt;

&lt;p&gt;Lastly, &lt;code&gt;Start&lt;/code&gt;, the last of our initialization functions, is called just before the first call to &lt;code&gt;Update&lt;/code&gt; for that script. This is the best time to initialize those variables that are needed in the rest of the script, whether in an Update function or in other custom or Unity methods. If we initialized something in &lt;code&gt;Awake&lt;/code&gt;, on any script, we can access it in any scripts' &lt;code&gt;Start&lt;/code&gt;; the &lt;code&gt;Awake&lt;/code&gt; method for every script in the scene is called before any script's &lt;code&gt;Start&lt;/code&gt; method is called, at least for GameObjects that are created at the beginning of the scene. &lt;/p&gt;

&lt;p&gt;It's important to note that &lt;code&gt;Start&lt;/code&gt; only ever executes once for any given script. This means that even if you disable and re-enable a game object within your scene, the &lt;code&gt;Start&lt;/code&gt; function on any attached scripts will not be run again, while &lt;code&gt;Awake&lt;/code&gt; and &lt;code&gt;OnEnable&lt;/code&gt; do get called again.&lt;/p&gt;

&lt;p&gt;Unlike our simple game loop, you can see that Unity's Update methods are also split into multiple methods. The first one listed is called &lt;code&gt;FixedUpdate&lt;/code&gt;, and this function is mostly used for updating anything related to the physics in the scene, as right after &lt;code&gt;FixedUpdate&lt;/code&gt; is called, Unity performs its physics calculations and updates, as well as processing and updating animation states and properties. &lt;code&gt;FixedUpdate&lt;/code&gt; is called such because it is executed based on a timer that is independent of frame rate, meaning it is called at regular real-time intervals and it may be called more or less than once per frame. &lt;/p&gt;

&lt;p&gt;After &lt;code&gt;FixedUpdate&lt;/code&gt; and all the physics updates are finished, all user input functions are called. On computers, these functions process any keys pressed on the keyboard or any mouse clicks; on consoles, any buttons pressed on the controller; and any interaction with the touch screen on mobile devices. This is represented by the line &lt;code&gt;OnMouseXXX&lt;/code&gt; in the function execution order flowchart shown above.&lt;/p&gt;

&lt;p&gt;The next method we can utilize for updates is simply called &lt;code&gt;Update&lt;/code&gt;, which runs right after the user input events are fired. This update function handles game logic, and it's often the most frequently used update function. It is best to have our physics calculations done before reaching this method, as our &lt;code&gt;Update&lt;/code&gt; method should use the most recent physics information to accurately update the game's logic. If, for example, our physics calculations were not done beforehand, the &lt;code&gt;Update&lt;/code&gt; method could be applying game logic that doesn't take into account any changes in the physics, such as a collision that caused an object to stop its movement. After &lt;code&gt;Update&lt;/code&gt;, the loop again processes updates to the animated objects within the scene, though sometimes this update to animations coincides with the the ones after &lt;code&gt;FixedUpdate&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Finally, &lt;code&gt;LateUpdate&lt;/code&gt; is for any last minute updating that needs to happen before the scene is rendered (I know we skipped a few- I'll explain in more detail next!). The most common use for &lt;code&gt;LateUpdate&lt;/code&gt; is updating the camera's position; if we want the camera to always be looking at the user, it is best if we already processed our physics and game logic to know the location the player is going to be in before updating the camera's position! &lt;/p&gt;

&lt;p&gt;Now, about the ones I skipped; as you can see, under &lt;code&gt;Update&lt;/code&gt; is a section of four that all start with the word 'yield'. These are used in Unity's Coroutines, which are a special kind of updating method. Normally, tasks within a method stop the execution of the rest of the loop until they have finished calculating, and these tasks will happen all at once in a single frame. In a Coroutine, you would include logic for something that needs to happen in order and in steps one frame at a time, but then stop once they have completed the task. With Coroutine's, you can pause the logic from executing until the next frame or for a certain number of real-time seconds, or even until a provided expression evaluates to true! Coroutine's return an enumerable so that it can pick up right where it left off in the sequence whenever you want. &lt;/p&gt;

&lt;p&gt;Imagine you want to move a character from one position to another, and after a pause, make them move back to the first position, like they were pacing; one way to do this might be to lerp between the positions. Lerp means to go from one value to another value in a variable number of steps instead of all at once, such as going from 0 to 10 by counting 1 at a time. If you were to put the logic for using lerp to change positions in a regular method, even &lt;code&gt;Update&lt;/code&gt;, it will do all the steps of the lerp in a single frame, which would make our character appear to stay right where they started. We could use a Coroutine to go one step of the lerp at a time. Here's how that might look as a Coroutine in Unity: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

IEnumerator ChangeCharacterPosition(Vector3 newPosition) 
{
    Vector3 startPosition = transform.position;
    while(transform.position != newPosition) 
    {
        transform.position = Vector3.Lerp(transform.position, 
        newPosition, t);
        yield return null;
    }

    yield return new WaitForSeconds(1);

    while(transform.position != startPosition) 
    {
        transform.position = Vector3.Lerp(transform.position, 
        startPosition, t);
        yield return null;
    }
}



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In this example, &lt;code&gt;t&lt;/code&gt; is whatever value of change you wish to happen on each step; in our counting to 10 example, t is equal to 1. The purpose of placing &lt;code&gt;yield return null&lt;/code&gt; in the &lt;code&gt;while&lt;/code&gt; loop is to tell Unity to pause the execution, which will pick up where it left off in the next frame. The rest of Unity's loop will then execute and it will start the loop all over again, resuming the Coroutine just after the &lt;code&gt;Update&lt;/code&gt; function completes. Similarly, we can &lt;code&gt;yield return new WaitForSeconds(timeToWaitArg)&lt;/code&gt; to tell Unity how long we want the pause to be before it resumes executing our code. Pretty neat, right? After handling any running Coroutines, &lt;code&gt;LateUpdate&lt;/code&gt; is called.&lt;/p&gt;

&lt;p&gt;After &lt;code&gt;LateUpdate&lt;/code&gt;, with all the up-to-date calculations for each object in the scene, the loop goes through rendering the scene for us to see. This is also broken up into multiple callback functions. The naming of the functions pretty much sums up their purpose, so I won't go over each of them, but in case it's not clear, &lt;code&gt;OnPreCull&lt;/code&gt; is called before Unity culls, or hides, any parts of the scene that would be blocked by something in front of it to prevent unnecessary rendering of things we wouldn't even be able to see. &lt;code&gt;OnRenderImage&lt;/code&gt; is called just after the scene is fully rendered and it allows for post-processing, which applies effects to the entire image. However, each of these rendering callback functions are only available to use in Unity's standard, built-in render pipeline; these days, most developers choose to use Unity's Universal Render Pipeline, URP, or their High Definition Render Pipeline, HDRP, or even a custom pipeline, and it is likely that Unity will eventually completely remove their original built-in pipeline. Fortunately, Unity provides other ways of modifying the rendered image, and developers can still apply post-processing and other effects to the rendering of the scene.&lt;/p&gt;

&lt;p&gt;And lastly, if a GameObject is going to be destroyed in the current frame, any logic placed in the &lt;code&gt;OnDestroy&lt;/code&gt; method will be executed after all updates have been called. Sometimes, this waiting is problematic, and Unity does provide a method to immediately destroy a GameObject rather than waiting until the end of the loop. &lt;/p&gt;

&lt;p&gt;Unity's core game loop is just one example of many out there. Some developers don't like Unity's loop and claim other execution orders allow for more powerful game design, but others claim that Unity can be just as powerful when you know how to use it. In the end, whatever game engine is used, it is important to understand its' core loop and the order in which it processes different parts of the code. This can help avoid bugs, and allow developers to fully take advantage of the engine they are using to create their game. &lt;/p&gt;

&lt;p&gt;I hope you found this overview of the game loop and the examples provided interesting and helpful. Whether you were just curious, or are aspiring to be a game developer yourself, understanding what a Game Loop is and some of the ways this pattern is used is an important part of learning about how games work! &lt;/p&gt;

&lt;p&gt;Sources: &lt;br&gt;
&lt;a href="https://gameprogrammingpatterns.com/game-loop.html" rel="noopener noreferrer"&gt;https://gameprogrammingpatterns.com/game-loop.html&lt;/a&gt;&lt;br&gt;
&lt;a href="https://docs.unity3d.com/Manual/ExecutionOrder.html" rel="noopener noreferrer"&gt;https://docs.unity3d.com/Manual/ExecutionOrder.html&lt;/a&gt;&lt;/p&gt;

</description>
      <category>programming</category>
      <category>gamedev</category>
      <category>unity3d</category>
    </item>
  </channel>
</rss>
