# Question
Title: Add opacity control to SoftLight blending shader
Just a heads up: I have very little experience with shader languages so please excuse if this is a trivial question.

I got a SoftLight shader from this blog (Archived here). It blends the given sprite over the background using the SoftLight blending mode without using the GrabPass, because I'm using URP where that is not supported.

The formula on Wikipedia for Photoshop's Soft Light blend mode is:

$$f\_\text{photoshop}(a, b) = \begin{cases} 2ab + a^2(1 - 2b), & \text{if}\\, b\<0.5\\ 2a(1-b) + \sqrt a(2b -1), & \text{otherwise} \end{cases}$$

Though the article I linked uses Pegtop's formula instead:

$$f\_\text{pegtop}(a, b) = (1 - 2b)a^2 + 2 ba$$

I would like to add an opacity parameter to it, so I can tune the strength and visibility of the overlaid image, like you would adjust the opacity of the soft light layer in Photoshop. I have an accompanying script that sets the value of `_Opacity` via MaterialPropertyBlock.

However I cannot get it to work properly, the colors will either become over saturated or too dark.

How can I adjust the opacity properly?

Here is the source, the commented stuff is what I've tried so far.

1. A new pass to premultiply the alpha of the source image by the opacity.
2. Multiply the alpha of the texture before blending.
3. Multiply the alpha of the texture in the last pass (dont know exactly what that does).

```
Shader "PhotoShop/SoftLight"
{
    Properties
    {
        _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}

        [HideInInspector] _Opacity("__opacity", Float) = 1.0
    }

    SubShader
    {
        Tags{ "Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Transparent" }
        ZWrite Off Lighting Off Cull Off Fog{ Mode Off }
        LOD 110

//      Pass
//      {
//          BlendOp Add
//          Blend DstColor DstColor
//
//          CGPROGRAM
//          #pragma vertex vert
//          #pragma fragment frag
//          #pragma fragmentoption ARB_precision_hint_fastest
//          #include "UnityCG.cginc"
//
//          sampler2D _MainTex;
//
//          float _Opacity;
//          struct vin
//          {
//              float4 vertex : POSITION;
//              float2 texcoord : TEXCOORD0;
//              float4 color : COLOR;
//          };
//
//          struct v2f
//          {
//              float4 vertex : POSITION;
//              float2 texcoord : TEXCOORD0;
//              float4 color : COLOR;
//          };
//
//          v2f vert(vin v)
//          {
//              v2f o;
//              o.vertex = UnityObjectToClipPos(v.vertex);
//              o.texcoord = v.texcoord;
//              o.color = v.color;
//              return o;
//          }
//
//          fixed4 frag(v2f i) : COLOR
//          {
//              float4 color = tex2D(_MainTex, i.texcoord);
//
//              color *= _Opacity;
//              return color;
//          }
//
//          ENDCG
//      }

        Pass
        {
            BlendOp Add
            Blend DstColor DstColor

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma fragmentoption ARB_precision_hint_fastest
            #include "UnityCG.cginc"

            sampler2D _MainTex;
            float _Opacity;

            struct vin
            {
                float4 vertex : POSITION;
                float2 texcoord : TEXCOORD0;
                float4 color : COLOR;
            };

            struct v2f
            {
                float4 vertex : POSITION;
                float2 texcoord : TEXCOORD0;
                float4 color : COLOR;
            };

            v2f vert(vin v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.texcoord = v.texcoord;
                o.color = v.color;
                return o;
            }

            fixed4 frag(v2f i) : COLOR
            {
                float4 color = tex2D(_MainTex, i.texcoord);

                // color.a *= _Opacity;

                float3 desiredValue = 2.0 * color.rgb * color.a / (1.0 - 2.0 * color.rgb * color.a);
                float3 backgroundValue = (1.0 - color.a) / ((1.0 - 2.0 * color.rgb * color.a) * max(0.001, color.a));

                color.rgb = desiredValue + backgroundValue;
                return color;
            }

            ENDCG
        }

        Pass
        {
            BlendOp Add
            Blend DstColor Zero

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma fragmentoption ARB_precision_hint_fastest
            #include "UnityCG.cginc"

            sampler2D _MainTex;
            float _Opacity;

            struct vin
            {
                float4 vertex : POSITION;
                float2 texcoord : TEXCOORD0;
                float4 color : COLOR;
            };

            struct v2f
            {
                float4 vertex : POSITION;
                float2 texcoord : TEXCOORD0;
                float4 color : COLOR;
            };

            v2f vert(vin v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.texcoord = v.texcoord;
                o.color = v.color;
                return o;
            }

            fixed4 frag(v2f i) : COLOR
            {
                float4 color = tex2D(_MainTex, i.texcoord);
                color.rgb *= i.color.rgb;
                color.a *= i.color.a;// * _Opacity;
                color.rgb = (1.0 - 2.0 * color.rgb * color.a) * max(0.001, color.a);
                return color;
            }

            ENDCG
        }
    }
}

```

Image to blend:

Result:

UPDATE:

If I enable the commented shader pass and set the alpha source for the overlaid image to "Input Texture Alpha" then it at least produces a better looking result:
But is still doesn't look 100% correct.

# Answer
So despite my best efforts, I could not get DMGregorys answer to work, which is a shame!

Nonetheless, after several more hours of searching, I finally found a solution:

First I needed to upgrade my Unity to 2021, because the feature used in the following is not available in earlier versions.

Since I am using the URP, I can use its 2D Renderer. That renderer supports the so-called `Camera Sorting Layer Texture` which works a bit like a GrabPass.

So I set up 2 Sorting layers, one for the stuff below the effect (background), and one for above. In the 2D renderer settings, I then set the "ForemostSortingLayer" to the background layer.

That means the `_CameraSortingLayerTexture` is taken when all the stuff in the background layer has been rendered.

I then made a quick ShaderGraph, to blend my SoftLight image with the `_CameraSortingLayerTexture`, to achieve my desired effect.

And it works!

Important to note: The ShaderGraph must be rendered in the Transparent Queue!
> 1 votes

# Answer
# The opposite of a right answer

I initially thought I had a very neat solution to this problem. Unfortunately, halfway through typing it up I realized I'd mixed up the roles of \\$a\\$ (already-in-buffer) and \\$b\\$ (being-drawn) in the blend formulas, and computed the result of soft-light blending \\$a\\$ over \\$b\\$ instead of \\$b\\$ over \\$a\\$.

(In my defense, b for "background" or "bottom" seemed very intuitive. To avoid mixing up myself or a reader again, I'll avoid single-letter variable names for the rest of this post and go with the computer graphics convention of "dst" for the accumulated content already in the destination buffer, and "src" for the source image being blended into that buffer)

That said, there may be cases where the designer can re-order the images to be drawn to get the desired result even with this backward blending, and in such a situation this "opposite of right" answer could still be useful, so I figured I'd share it here for future reference.

We'll define our backwards-blending function with opacity \\$op\\$ as:

$$ f\_\text{light-soft}(dst, src, op) = dst + op\left(f\_\text{soft light}(src, dst) - dst\right) $$

Using the Pegtop formula, we can rearrange this to factor all the \\$dst\\$ terms to one multiplication:

$$\begin{align} f\_\text{light-soft}(dst, src, op) &= dst + op\left(2src \cdot dst + src^2 - 2 src^2 dst - dst\right)\\ &=dst\left(1 + op (2 src - 2 src^2 - 1) \right) + src^2op \end{align}$$

Now we have something that maps neatly to the GPU blending pipeline:

Pass 1:

```
Blend DstColor Zero
// ...
color.rgb = 1.0f + color.a * (2.0f * color.rgb * (1.0f - color.rgb) - 1.0f);
return color;

```

Pass 2:

```
Blend SrcAlpha One
// ...
color.rgb *= color.rgb;
return color;

```

The danger with these two-pass approaches of course is that when we have a low dynamic range frame buffer, we have to quantize to 8 bits and clamp the result in the range 0-255 in between the two passes. That's where the shader linked in the question falls over - it relies on negative intermediates and blows up for colours brighter than 50% grey.

So, I wanted to check what kinds of errors this quantization would introduce. I made a spreadsheet testing all 256 x 256 possible combinations of \\$src\\$ and \\$dst\\$ values, first computing the correct light-soft blend in one pass, and then computing it with the two passes above with rounding in between. Here's the resulting error map:

Cells in red are background-foreground pairs that give a value 1/255 lower than the ground truth. Cells in blue give a value 1/255 higher. Everything in white reproduces the correct value exactly. No pair differs from the correctly blended colour by more than one unit in last place, and the intermediate result never underflows or overflows.

So, a very good approximation... to the reverse of the function we wanted. But maybe still useful if you can re-order your layers.

Unfortunately I have not yet found a way to get the rearrangement to work as nicely for the correct original ordering, due to the squares on some of the terms. I'll post a follow-up if I think of a better way.
> 1 votes

---
Tags: unity, 2d, shaders, alpha-blending
---


# Question
Title: Several objects from another level appearing in a level that they shouldn't?
I created a project in Unreal, Top Down Character.

**By default, the scene looks like this:**

I thought of creating a main menu to take the player to the other scenes of the project I intend to do. For that I created an empty level.

**See below:**

* I created the "Level\_Menu", "BP\_Menu\_Widget" and "BP\_Menu\_ADM".
* Notice that in the hierarchy I just added the "BP\_Menu\_ADM".

**At first, visually, everything looks normal. I just created a text with the name of the project:**

**The problem is when I look at the hierarchy:**

A huge amount of objects appear. Objects that I have no idea why they appear. I imagine it has something to do with the fact that the project is initially a default project (top down) from Unreal itself.

**An important detail is that the project is not purely blueprint, I created it exactly like this:**

Before coming here (as usual), I tried to research something like this, even in English (which is not the language I speak). But I didn't find anything related (I probably don't know how to use the right terms).

I changed the gamemode, I set everything to "none", I got to the point of opening a script called "world.h", but when I went to play with it to see what happened, Visual Studio warned that it was a read-only file.

Then I finally recognized that I needed help. I would like someone to help me understand what is happening and how to solve it, without necessarily creating a project from scratch. I will only use this option as a last resort.

# Answer
> 1 votes
I researched further and found the answer on the Unreal forum.

**Link of question (question and answer from 'saldavonschwartz'):**

https://forums.unrealengine.com/t/how-to-create-a-truly-blank-empty-project/377987/2

In short, Unreal by default will always create some objects that have to be present in every scene.

**To solve the problem, just create a new 'Game Mode Base':**

**Go to the 'World Settings' window:**

**Change the 'GameMode Overrides' option (by default it will be 'none'), selecting the game mode you created:**

Even so, when you press play, several objects will be created (they are necessary and mandatory, in the link I sent above, it explains a little about). But the project's default player will not be.

---
Tags: c++, unreal-4, unreal, levels
---


title: Strange flashing cube bug in snake game

text:
# Question
Title: Strange flashing cube bug in snake game
I'm trying to make a simple snake game in C and OpenGL, and I have this at the moment, which runs *almost* perfectly:

```
#include "glad/glad.h"
#include <GLFW/glfw3.h>

#include "stb/stb_image.h"

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

#include "cglm/cglm.h"
#include "cglm/call.h"

#include "apple.h"
#include "snake.h"

struct Snake snake;
snakeDir dir;

void initSnake() {
    dir = Up; //Initilize direction

    snake.speed = 15;
    snake.size = 1;

    snake.body[0].x = -1.0f;
    snake.body[0].y = -1.0f;

    snake.head = snake.body[0];

    snake.ticks = 0;
}

static void _drawSnake() {

    snake.ticks++;

    if (glfwGetKey(window.self, GLFW_KEY_UP) == GLFW_PRESS && dir != Down)
        dir = Up;
    if (glfwGetKey(window.self, GLFW_KEY_DOWN) == GLFW_PRESS && dir != Up)
        dir = Down;
    if (glfwGetKey(window.self, GLFW_KEY_LEFT) == GLFW_PRESS && dir != Right)
        dir = Left;
    if (glfwGetKey(window.self, GLFW_KEY_RIGHT) == GLFW_PRESS && dir != Left)
        dir = Right;

    if (snake.ticks == snake.speed) {
        // Move the snake's head in the direction specified by the dir variable
        switch(dir) {
            case Up:
                snake.head.y -= 2.0f;
                break;
            case Down:
                snake.head.y += 2.0f;
                break;
            case Left:
                snake.head.x -= 2.0f;
                break;
            case Right:
                snake.head.x += 2.0f;
                break;
        }

        // Move the snake's body
        for (int i = snake.size - 1; i > 0; i--) {
            snake.body[i] = snake.body[i-1];
        }

        snake.body[0] = snake.head;

        // Reset ticks
        snake.ticks = 0;
    }

    // Check if the snake eats an apple
    if (snake.head.x == apple.x && snake.head.y == apple.y) {
        // Generate a new apple
        int rx = (rand() % (10 + 1 + 8) - 8);
        int ry = (rand() % (10 + 1 + 8) - 8);
        float ax = (rx + rx % 2) - 1.0f;
        float ay = (ry + ry % 2) - 1.0f;

        apple.x = ax;
        apple.y = ay;

        snake.size++;
    }

    // Check if the snake hits its own body
    for (int i = 1; i < snake.size; i++) {
        if (snake.head.x == snake.body[i].x && snake.head.y == snake.body[i].y) {
            terminateWindow();
        }
    }
}

void renderSnake(struct Shader shader) {

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, snake.texture);

    useShader(shader);

    glBindVertexArray(snake.VAO);

    for (int i = 0; i < snake.size; i++) {
        glm_mat4_identity(camera.model); //Reset matrix
        glm_rotate(camera.model, glm_rad(90.0f), (vec3) {1.0f, 0.0f, 0.0f});
        glm_scale(camera.model, (vec3) {0.1, 0.1, 0.05}); //Construct second matrix
        glm_translate(camera.model, (vec3) {snake.body[i].x, snake.body[i].y, -21.0f});
        setShaderMat4(shader, "model", camera.model);

        glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);
    }

    _drawSnake();
}

```

The only problem is that whenever the snake collects an apple, it looks like the head of the snake or something flashes in the middle of the screen for a second then disappears. I tried tracking this bug down but I can't figure out what it's coming from. This is what it looks like:

Does anyone know what bug in my code is causing this? It's really quite annoying and any help is greatly appriciated!

# Answer
> 3 votes
When your "snake eats apple" code block is executed, you increment the snake snake size, but it doesn't look like you're initializing the location for the new snake segment. The flash looks like it's always in the center of your game area. So my intuition is that most recently added block of the snake is appearing at the origin by default, but that this error then gets corrected when the movement code executes because it moves the head & the positions "trickle down" until finally the most recent snake block gets put in the correct location.

If I'm following your code correctly, you can fix this adding an initialization step after growing the snake size:

```
snake.size++;
if(snake.size > 1)
{
   int last = snake.size - 1;
   snake.body[last] = snake.body[last-1];
}

```

---
Tags: opengl, c, snake
---


# Question
Title: Physical motions are not smooth despite a high frame rate
I've been facing this problem since a long time ago. My Unity game is getting 120 FPS, but still, physics-related movements are not as smooth as should be, and the player's movement is totally flickering.

**Information**

I'm working with Unity 2022, on an Android game. But this problem still exists in the editor and PC. All my physics-related scripts are placed in the `FixedUpdate` method, so I guess that high frame rates is not affecting them at all.

# Answer
That high FPS that you're seeing is of `Update`, not `FixedUpdate`. You're experiencing something similar to this:

The red ticks represent frames where `Update` runs, and the blue ticks represent frames where `FixedUpdate` runs. You can have a billion `Update` frames per second, but when `Update` want to access a physics object's position to render to the screen, it must still choose the latest `FixedUpdate` frame available (which is not plenty).

## Altering Rigidbodies

If you can't afford to increase `FixedUpdate`'s frequency (it is costly in terms of computational power), you can "cheat" a little bit by using **interpolation/extrapolation**. Just switch to Interpolate/Extrapolate on any `Rigidbody` that you want to appear smooth.

**Interpolation** use the `Rigidbody`'s position from the previous TWO physics frames. With two physics frames in hand, the current main frame can choose a smoothed value between that two physics frames, instead of relying entirely on a single physics frame.

**Extrapolation** essentially predicts the future. When a main frame arrives before a physics frame, the main frame can use previous physics frames as data points to "guess" where the physics object could be right now.

You can find out more about interpolation/extrapolation in-game physics with this fantastic article, or here, where I cropped the red ticks/blue ticks image.

You can also read about the difference between `Update` and `FixedUpdate`, (and even `LateUpdate`) here.

## Setting the Fixed Timestamp

Note that this method makes a huge impact on the game's performance, but will still solve this problem. To do that, Unity provides an option to alter how frequently the FixedUpdate method is being called, & that is an option named Fixed timestamp, which is available in the Project Settings window \> Time. So, in order to fix your problem, you have to set this to a lower value, such as 0.01.

> Fixed Timestamp is a framerate-independent interval that dictates when physics calculations and FixedUpdate() events are performed.

More information will be available on Unity docs. Also, I found this link helpful to know more about this topic.
> 4 votes

---
Tags: unity
---


# Question
Title: How can I use the Input System Package's Split-Screen?
I've made a simple local multiplayer game with Unity's Input System Package. Players can join the game with a keyboard or a gamepad. Currently, the game has only one static camera. And I know that there's an option in "Player Input Manager" component to enable the Split-Screen feature. But how does that work?

# Answer
> 1 votes
Actually, Input System's Split-Screen feature is so handy to use. Check the Split-Screen option. Then, some other options will be displayed in the component as below:

**Maintain Aspect Ratio**: When set to `true`, split cameras will force to have the same aspect ratio as before splitting (normal display).

**Set Fixed Number**: If enabled, the game screen will be forced to have certain parts, even if there are not that many players assigned.

**Screen Rectangle**: According to Unity Docs: The normalized screen rectangle available for allocating player split-screens into.

After configuring the "Player Input Manager" component, you have to make some changes to the player's "Player Input" component. You have to put both player & a proper camera (the current main camera should be fine) as children of a GameObject, which I name *Player Camera Group* as below:

Make sure to make it a prefab, then get back to the GameObject holding the "Player Input Manager" component, & assign the *Player Camera Group* as `Player Prefab`.

You're done. Now if you play the game, everything should be perfectly working. Also, check out this Unity Document to learn more about the "Player Input Manager" & Split-Screen features.

---
Tags: unity
---


# Question
Title: Unity build changes its resolution after going to windowed mode and then back to fullscreen
It seems to me that this behavior is incorrect (or at least illogical). Correct me if I'm wrong.

**Repro (Unity 2020.3.26f1 LTS / default project settings):**

* Run the build (in fullscreen by default):
* Go to windowed mode (Alt + Enter):
* Resize the window with the mouse so that its resolution is reduced (to 500x500 pixels):
* Go back to fullscreen mode (Alt + Enter):

**Actual results:**

* When going back to fullscreen mode resolution is being kept 500x500 pixels (the scene is rendered in 500x500 pixels, the text is blurry and the canvas is squared).
* Both `Screen.currentResolution` & `Screen.width/height` have `500x500` values.

**Expected results:**

* Fullscreen-mode should restore the game resolution back to `1920x1080` (as on the 1st screenshot before going to windowed-mode).
* Both `Screen.currentResolution` & `Screen.width/height` should have the values of `1920x1080`.

---

**The problem caused by this behavior is that the user cannot return to full-screen mode with full display resolution after switching to windowed mode and changing the window size.**

---

Component script used in this test:

```
public class ResolutionInfo : MonoBehaviour
{
    public Text text;

    private Vector2 _resolution, _currentResolution;
    private bool _fullscreen;

    void Update()
    {
        Vector2 resolution = new Vector2(Screen.width, Screen.height);
        Vector2 currentResolution = new Vector2(Screen.currentResolution.width, Screen.currentResolution.height);

        if (_resolution == resolution && _currentResolution == currentResolution && _fullscreen == Screen.fullScreen)
            return;

        _resolution = resolution;
        _currentResolution = currentResolution;
        _fullscreen = Screen.fullScreen;

        text.text =
            $"FullScreen: {Screen.fullScreen}\r\n" +
            $"Screen.currentResolution = {Screen.currentResolution}\r\n" +
            $"Screen.width/height = {Screen.width}x{Screen.height}";
    }
}

```

---

**P.S.** `Screen.resolutions` list added to the request from Arian Keshvari comment:

# Answer
> 2 votes
This is a bit late, but I ran into the same problem recently and plopped this script together after exploring the forums a bit. It should do the trick once attached to any component in your scene. Hope that helps and good luck!

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ManageFullscreenSwitch : MonoBehaviour
{
    private int _fullscreenWidth = 0;
    private int _fullscreenHeight = 0;
    private int _fullscreenAspectRatio = 0;

    private bool _fullscreen = false;

    private void Start()
    {
        _fullscreen = Screen.fullScreen;
        SetFullScreenValues();
    }
    private void Update()
    {
        if (_fullscreen != Screen.fullScreen)
        {
            if (Screen.fullScreen)
            {
                RestoreFullscreenResolution();
            }

            _fullscreen = Screen.fullScreen;
        }
    }

    private void RestoreFullscreenResolution()
    {
        Screen.SetResolution(_fullscreenWidth, _fullscreenHeight, true, _fullscreenAspectRatio);
    }

    private void SetFullScreenValues()
    {
        // Set the screen width and height
        int systemWidth = Display.main.systemWidth;
        int systemHeight = Display.main.systemHeight;

        // Get a list of all supported resolutions
        Resolution[] supportedResolutions = Screen.resolutions;

        // Find the closest supported resolution to the native resolution
        Resolution closestResolution = supportedResolutions[0];
        int smallestGapInResolution = int.MaxValue;

        foreach (Resolution resolution in supportedResolutions)
        {
            int gap = Mathf.Abs(resolution.width - systemWidth) + Mathf.Abs(resolution.height - systemHeight);

            if (gap < smallestGapInResolution)
            {
                smallestGapInResolution = gap;
                closestResolution = resolution;
            }
        }

        _fullscreenWidth = closestResolution.width;
        _fullscreenHeight = closestResolution.height;
        _fullscreenAspectRatio = _fullscreenWidth / _fullscreenHeight;
    }
}

```

---
Tags: unity, resolution, fullscreen, screen-management
---


# Question
Title: How to collide a circle against a pixel grid without getting snagged?
It's probably senseless to post my code because it simply takes a hard-stop approach when it encounters anything in the grid that is impassable (well, I've attempted to check -20/+20 deg, then -40/+40 deg, then -60/60 to see if it got around the obstacle but that didn't work) There is no salvaging my current point-sized collider code so I am here seeking code that works, sliding smoothly along edges and not getting stuck. From what I'm reading, a circle should be used for 2D (or capsule for 3D) for the character collider but I'm not sure how to implement collisions with a pixel grid (bitmap). Do I let the circle penetrate somewhat and check all collisions within the radius? How do I guide my character based on those collisions? Does anyone have any sample code for that? Thanks in advance!

# Answer
It sounds like you're describing a collide and slide algorithm (sometimes also called move & slide). I'm not presently familiar with the PhysX API, but I found this documentation from nVidia discussing it in the context of character controllers.

A (CCT) SDK is an external component built on top of the PhysX SDK, in a manner similar to PhysXExtensions.

The full documentation is extensive and too long to cover here, so I'm going to focus on their argument for using CCT at all.

The main advantage of kinematic controllers is that they do not suffer from the following issues, which are typical for dynamic controllers:

* (lack of) continuous collision detection which can lead to notorious 'tunneling effect' problems:
    + if the character goes too fast it might tunnel through a wall
    + as a consequence, the character's maximum velocity be limited (thus also limiting the game play possibilities)
    + even if it does not tunnel, the character might jitter in various cases
* No direct control: a rigid body is typically controlled with impulses or forces.
* Trouble with friction: when the character is standing on a ramp, it should not slide.
* Trouble with restitution (bouncing from fast collisions): typically, restitution should be avoided for CCTs.
* Undesired jumps: characters must often stick to the ground, no matter what the physical behavior should be - for example leaving a ramp at a high speed the physics engine often makes the character jump a bit, but that is often not the desired behavior.
* Undesired rotations: a typical character is always standing up and never rotating. However physics engines often have poor support for that sort of constraints, and a great deal of effort is often put into preventing a capsule around the character from falling (it should always stands up on its tip).

To summarize, a lot of effort can be spent on tweaking and disabling the physics engine's features simply to emulate what is otherwise a much less complex piece of custom code. It is natural to instead keep using that simple piece of custom code.
> 0 votes

# Answer
In case anyone is interested --- I'm happy with my own solution rather than implementing a full character collider (circle/capsule). I try the path forward with my single point collider. If it doesn't even make it the attempted dist\*0.2f, I ground raycast 0.3f meters left and 0.3 meters right of my character (L/R based on character's heading, or location rotation). If either of these raycasts move any distance at all, I then attempt a forward move in the same direction as the middle vector (my character). Out of the 3, whichever forward vector makes it the furthest without collision wins and that is where I move my character to. I played around with this for 15 minutes straight, purposely running into stuff and through tight spaces, up and down stairs, etc, and only got stuck 1 time.
> 0 votes

---
Tags: character-controller, physx
---


# Question
Title: Building a 3D modeling and importing workflow of a 3D indie game model
So, I am considering building an "SOP" for an indie game. The question might be simple, dumb, and wide but not deep. I am using Blender and Godot to build 3D character and environment models. These two software have their own material systems. Which one should I use to create the game model appearance?

# Answer
> 2 votes
*Part of the philosophy of Godot is to build a free software ecosystem, and yes, that includes compatibility with Blender, and also with open standards.*

---

**Making games or video**

I'll assume that you are going to use Godot, since this is for indie games.

For movies, you would not need Godot, since Blender can render video. However, I also want to mention that Godot 4 has a Movie Maker Mode, which allows you to record high quality game play footage for your game trailers without the need of screen capture, and without worry of framing problems.

---

**Godot vs Blender**

The tooling for modeling in Godot (without third party plugins) is very limited. In fact, Godot is not trying to replace Blender.

Because of that I would encourage to use Blender for modeling. And that would also be the answer for all the other things Godot does not do (without third party plugins): texture painting, sculpting, retopology…

---

Now, creating simple models in Godot can be useful. On one hand, if the model is very simple it might not be worth bothering the Blender expert with it if we can quickly do it in Godot.

On the other hand, you might find useful to prototype scenarios in Godot, then export them into GLTF (You find the option in Project -\> Tools)… Which you can then import into Blender to improve them, and then import back to Godot.

---

I would also like to encourage to take advantage of Godot to automate your process. For example, you can use a `tool` script to convert `CSG` nodes into `MeshInstances` which should give you no trouble when exporting to GTLF. Similarly, you might use `tool` scripts to do procedural generation, which you can then export to GLTF. *Yes, you could also do procedural stuff in blender.*

*By the way, Godot can unwrap and view UVs (of `ArrayMesh`)… That will likely NOT be part of the workflow. Another thing that Godot does is Create Outline Meshes (the option creates an slightly larger inverted `ArrayMesh` \- useful for an outline effect). Thus, if you ever need to unwrap UVs - in Godot - of something that is not an `ArrayMesh`, you can create their outline, and then the outline of the outline. Which will result in an `ArrayMesh` otherwise identical to the original.*

---

**Basic import workflow**

In Godot the imported model will be an scene. The approach Godot recommends is to make an scene that inherits from the imported model, and do Godot specific modification there…

However, I'll recommend composition instead. I mean: create an scene dedicated to contain the imported model (an scene containing another scene). So in this other scene you can add modifications on top of the imported model, that will not be lost if you need to re-import it.

The modification you might want to do on Godot include: adding an `AnimationTree`, setting material overrides, adding bone attachments, setting up inverse kinematics, making the root a physics body and adding physics colliders, and so on.

---

**Blender to Godot 3.x**

Godot 3.x has fairly good support for importing GLB and GTLF (which are open standards). And, of course, you can export from Blender.

So, if you can export to GLB or GLTF from Blender, and the model keeps the materials, you are going to get a good representation of the materials in Godot 3.x. *You might still have to tweak it, in particular increase roughness or lower specularity.*

However, if the materials you want to create cannot be exported to GLB or GLTF (i.e. they are a complex shader graph), then you are better off creating the materials in Godot. However, you still want to assign placeholder materials in Blender because Godot lacks the tooling to define which surfaces will have each material.

*Godot uses "import hints" which are suffixes you add in the name of the elements of the model to tell Godot how to handle them. See import hints.*

See Importing Scenes

---

**Blender to Godot 4.x**

For Godot 4 the support for GLB and GTLF has been improved. You will get a better representation of the materials. And you will have better control of how they are imported with a new UI that lets you specify how to handle different parts of the model.

You also get FBX support (which has been the de-facto standard for the industry, despite being a proprietary format) via FBX2glTF※. However, it might not be the best option because it is even more restrictive on which materials it supports. You will find that the materials are lost in FBX unless you set the shader graph in Blender in a very specific way (just a Base Color, a Principal BSDF and a Material Output). *And also it is a proprietary format.*

※: You need to download FBX2glTF separately, and configure the path in Editor Settings -\> General -\> File System -\> Import.\*

But that is not all. Godot 4 can interface with Blender※. So you can add blend files in your Godot project and have Godot communicate with Blender to get the information it needs to import them. Which also means that modifying the blend file will make Godot re-import the model without having an intermediary file.

※: You need to download Blender separately, and configure the path in Editor Settings -\> General -\> File System -\> Import.\*

*Yes, the import hints system still works in Godot 4.*

See Importing Scenes.

---

**On other tools**

My Blender skills are very limited. So I'll tell you some workarounds somebody like me can use when working alone or in a team that lacks somebody with Blender expertise. *Hopefully you find something useful here.*

First of all, if you can find another software that exports to GLTF or GLB you can import that into Godot (for example, for architecture, I have used an old version of SketchUp - for desktop - with a community plugin to export to GLTF)… But even if you can't, you might use Blender to convert the models.

And for characters… VRoid studio exports to VRM... But that is GLB file, just change the extension. So you can import that into Blender or into Godot.

Now, sadly almost every other software wants FBX. So you could tell Blender to unpack resources so it extract the textures, set the materials the way I said for FBX (just a Base Color, a Principal BSDF and a Material Output), and export it to FBX from Blender.

Now, if you upload the model from VRoid into Mixamo, then Mixamo will rig it again. Yet, the Mixamo animation library is biased to shooters with some melee, and you might need animations that are not available there… An option for the Blender impaired like me is to animate in Cascadeur. Yet, since you want the same rig for all the animations, the workflow I would use is to first take the model to AutoCore AccuRig, which will generate a rig that both Mixamo and Cascadeur can work with directly.

Finally you will want to merge FBXs files (you will have many FBX files, each with single animations either from Mixamo or Cascadeur), you can do that in Blender. And from there you can finally get the model into Godot.

It is also possible to combine the models in Godot. In which case, I will advice use a separate project to do it (and as I said at the beginning, Godot can export to GLTF, or, since it is going from Godot to Godot you can files in Godot formats from project to project). *And in Godot 4 you can even automate the process with `tool` scripts.*

*Godot 4 has some tooling to extract animations from models into animation libraries that you can apply to another model, and also some tooling for animation retargeting. I haven't figured out a good workflow with those. Yet, you might want to explore that.*

---

I've been mentioning that you can automate parts of the process in Godot using `tool` scripts. And step up from there is making plugins, you can find some third party plugins for Godot at the Godot asset library. Well, an step up from making a plugin is making an application in Godot. You will find some tools made with Godot in itch.

You might also be interested in awesome-godot.

---
Tags: textures, blender, godot, 3d-modeling, material
---


# Question
Title: How to completely disable auto refresh everywhere (in favor of manually compiling them)
Is it possible for me to create a custom script that will fully disable auto refresh everywhere within Unity *(not just on script changes; in my case, asset creation/deletion in addition to everything else)*?

Or is this particular problem a bug that should be fixed by the Unity team *(so that unchecking the **"Auto Refresh"** setting fully disables it in all locations that trigger it)*?

---

## My problem:

Unchecking the **Asset Pipeline -\> Auto Refresh** setting doesn't fully disable this `"Reload Script Assemblies"` behavoiur. *(i.e. the "stop everything and prevent you from being able to do anything, Unity is locking down to recompile things" behaviour.)*

In particular I found that even though this setting is disabled, it still happens for every **new or removed Asset** *(creating a script via **Assets -\> Right click -\> Select `Create` -\> `C# Script`**, or removing one by going to **Assets -\> Right click an asset -\> Select `Delete`**)*. I'm not a fan of this **Auto Refresh** functionality *(anywhere in Unity)*, it's very disruptive and annoying to keep running into it with very minor changes. I'm glad I am able to disable this and manually run the refresh when I'm ready for any of my script changes, but I still run into this frustrating problem.

In addition to the **Auto Refresh** setting being un-checked, I have my **General -\> Script Changes While Playing** set to `Recompile And Continue Playing`; this is fine but isn't the culprit as I'm not currently playing when this refreshing happens.

It feels like the problem is that other locations in Unity code that should be respecting the **Asset Pipeline -\> Auto Refresh** setting, but aren't setup to respect it *(either because it's a bug, or hasn't been implemented)*.

There's lots of articles about how to disable auto refresh, but I haven't found any that are specific to **new or deleted assets** (I've shared some of the links I've found below). Most sources I can find for disabling auto refresh are for updates I make to my existing scripts, for when I'm playing, or for creating a custom script to add my own logic *(not quite sure how to do this yet, still researching this path)*.

---

### A few links that are related to this issue

but aren't similar enough to help me solve this problem:

---

### My system info:

* **Unity version:** `2021.3.3f1 Personal`
* **OS:** `MacBook Pro macOS Catalina Version 10.15.7`

---

***Side Note:** I recently asked this question on the `answers.unity.com` website *(question here)*, but I found out that site is shutting down soon *(on June 23rd, 2022)*. Using Unity's forum is a mess, so I'm re-asking this here since Stack Overflow/Stack Exchange is a better Q&A community.*

# Answer
I am using Unity 2022.2 and Unity 2021.3 (LTS).

Auto refresh was off but I've seen that 2 different projects had different versions of Burst. And in both cases Burst had the "chain link" icon (installed as a dependency)

The solution in my case was: I reinstalled Burst by name (Packager Manager -\> "+" sign -\> "Add packager by name.. -\> added "com.unity.burst"). Installed version is 1.8.4. This seems to have solved it. Some settings might have been reinitialized.
> 1 votes

---
Tags: unity, c#, pipeline
---


# Question
Title: Are there limits to the number of coroutines in Unity?
While reading a thread about coroutines, I stumbled upon a random user's comment that coroutines may not fire at all:

> Just so you are aware, there is a coroutine limit and if you hit this some coroutines will not fire or fail, leading to very weird and hard to track down behaviour if you have nested coroutines like this.

I've been modelling much of my newer project around coroutines, and the prospect that they may or may not fire would be very harmful, but I cannot find any official documentation about coroutine limitations in Unity.

Other than resource allocation from the fact that you may be constructing things like `WaitUntil` almost every frame, is there any truth to that comment?

# Answer
I never heard of anything like that. The documentation on coroutines does not mention any of that either. And it also sounds like one of those "If you have to ask, you are doing things wrong" limits to me.

But to prove it, I made a little test setup.

```
using System.Collections;
using UnityEngine;

public class MassCoroutineTest : MonoBehaviour
{
    private int counter;

    void Update()
    {
        Debug.Log($"{counter} coroutines reporting in!");
        counter = 0;
        if (Input.GetKeyDown(KeyCode.Space)) {
            for (var i = 0; i < 10000; i++) {
                StartCoroutine(TestRoutine());
            }
        }
    }

    IEnumerator TestRoutine() {
        while(true) {
            counter++;
            yield return null;
        }
    }
}

```

This script generates 10,000 new coroutines whenever you press space. It counts how many of those coroutines actually got executed this frame and outputs the number. I drove this to a million coroutines without the counter ever turning out an uneven number. And then I quit because I only had 1.5 FPS anymore and it got annoyingly unresponsive.

So no, **it's a myth**. When there is indeed a hard limit on coroutines, you are not going to hit it while still having an acceptable framerate.

But I can imagine how such a myth is created. Game architectures based on lots and lots of coroutines can get really difficult to navigate and debug. You have spooky actions at a distance everywhere and you have no idea how many coroutines are active on which game object and what they are doing. So a codebase that uses a lot of coroutines often becomes really buggy and hard to troubleshoot. But it's always easier to blame the tools you are using than it is to blame yourself for not using them properly. So instead of admitting to themself that they screwed their architecture through over-reliance on coroutines and don't understand it anymore, people go around the Internet and tell everyone it has to be Unity and its coroutine management itself that is buggy.

By the way, I usually use coroutines in my code very rarely. When I want to wait until something happens, then I put the check for that condition into the `Update()` method of an appropriate component. When I want things to happen in a sequence, then I usually program a simple state machine.

---

**Update:** João Mendes in the comments wonders if there might be a limit on *nested* coroutines. Well, I tried that too by using a recursive coroutine that starts itself:

```
IEnumerator RecursiveRoutine() {
    counter++;
    yield return StartCoroutine(RecursiveRoutine());
}

```

This code actually causes a `StackOverflowException` at a depth of 272 coroutines. But that's a visible error in the console, not just a silent fail. When your game doesn't work and there are exceptions in the console caused by your own code, then that's on you, not on Unity! And it's to be expected that this error happens, because `StartCoroutine` immediately starts the execution of the coroutine method until the first `yield`.

However, when you yield for a frame before creating the coroutine, then you no longer have that problem:

```
IEnumerator RecursiveRoutine() {
    counter++;
    yield return null;
    yield return StartCoroutine(RecursiveRoutine());
}

```

it seems to run just fine. There is not even an FPS drop. Well, it *runs* fine, but interestingly the Unity editor crashes occasionally when you let this run for a while and then exit play mode. So recursively calling coroutines might not be such a good idea after all.
> 24 votes

---
Tags: unity, coroutines
---


title: Error for export at godot 4

text:
# Question
Title: Error for export at godot 4
I tried this code in GDScript, in Godot 4:

```
export (int) var width;

export (int) var height;

```

And at Metadata add width and height but these below don't show and have an error.

I don't know what the problem is.

# Answer
That syntax would work in Godot 3.x.

Let us break it down first. This is a variant variable called `width`:

```
# Godot 3.x or Godot 4.x
var width

```

We can add an optional `;` at the end. The `;` separates multiple statements on the same line. Since we are not adding more statements to the line, this is the same thing as before:

```
# Godot 3.x or Godot 4.x
var width;

```

Now, to export the variable (so it is available in the inspector), in Godot 3.x you did this:

```
# Godot 3.x
export (int) var width;

```

Here the variable is being exported as an `int`. However, the variable is still a variant. It could have values that are not `int` if you set them from code. But it will show as an `int` in the inspector.

We need to fix that. Because in Godot 4.x, you don't do that. In fact, we could have fixed that in Godot 3.x, it looked like this:

```
# Godot 3.x
export var width:int

```

Now the variable is an `int`, and we don't need to tell it to export it as an `int`, because exporting an `int` as an `int` is the default (yes, there is another option: exporting at as an Enum).

*Yes, Godot 3.x had typed variables. It is not a type hint.*

And now, this is how that looks like in Godot 4.x:

```
# Godot 4.x
@export var width:int

```

That is because `export` is no longer a keyword, but an annotation instead. Annotations are a new language feature in GDScript 2.0 (the one that comes with Godot 4.x), and they all start with `@`.
> 3 votes

---
Tags: export, godot-4
---


# Question
Title: Why do game developers not make games with cheat codes or god mode any more?
Not everyone has time to actually play through an entire game or work through it. Wouldn't video games sell more if they provide an option for the casual gamer - aka unlock everything, so someone doesn't have to work their way through it?

Nowadays, I just resort to watching gameplay walkthroughs on YouTube because it allows me to multitask and still immerse myself and see the story.

If I was given god mode, I'd probably actually buy the game.

# Answer
> 64 votes
Nowadays it's more conventional to treat these assists as accessibility settings, clearly listed in the game's menus, advertised in its promotional materials/website, and covered in accessibility reviews, rather than secret codes that need to be discovered.

That way, players who are interested in the game but don't have the time, physical, or mental capacity to play the entire game on its default settings can more easily learn if there's a way to play it that will work for them, before they buy, and without needing to get secret insider knowledge from other players.

Game studios do this not just out of the goodness of their hearts or because it's the right thing to do to make technology accessible (though those should be reasons enough). It also increases the size of the market they can sell to, because as you point out, if a player doesn't have confidence they'll be able to play and enjoy the game, they don't buy it.

Modes similar to god mode go by a variety of names including:

* no-fail mode
* story mode
* tourism mode
* assist mode

But the common element is that you either cannot die, or it's at least vastly less common for that to happen (eg. way more health/damage reduction, or super-fast regen), and the penalties for death are reduced to practically nothing.

These modes or related settings may also power up your abilities so you can more easily defeat enemies, overcome obstacles, or have less need to manage limited resources like ammo/mana/money/super meters.

Some games go even further and include some amount of auto-playing feature so you can "give your sibling the controller" digitally and watch it play past a part that's giving you trouble or that you're just not enjoying. Nintendo in particular has been exploring this, starting with the Super Guide in New Super Mario Bros Wii and continuing into, Mario Kart 8 Deluxe, etc. This has the added improvement over watching YouTube walkthroughs where at any point you can take back control to play the parts that work and are enjoyable for you.

So, the tradition of god mode and infinite ammo codes didn't completely go away, it's just changed form into one intended to be more discoverable, to serve exactly the kind of player need you've identified.

# Answer
> 21 votes
God modes were originally more of a developer mode, which would, by some slip of the tongue or through enterprising gameplay, escape to the end player. (Think of the Konami code for a famous example.) They come with ups and downs, but the tradition still somewhat exists.

The biggest drawback is with multiplayer games, particularly (but not exclusively) in cases of Player vs. Player; great investments have gone into preventing God codes / cheat-codes in these, not because they might make it more fun (or sometimes less fun) for one player but because they can ruin the experience for someone else.

That said, offline games typically have a flag which will enable a developer console, if you need one; and this, in turn, allows for spawning in ammunition, items, or NPCs, toggling invulnerability, or toggling clipping. It's usually locked behind a launch option, which is typically fairly easy to find on the web.

As an example, for Doom 2016 it is readily available with Ctrl+Alt+~, but only in single player. If you play multiplayer, the console won't work. After that, there are lists of commands you can type in to get what you want; `iddqd` being the command for god mode.

The other common option is to have a separate program running with shared memory, which can enable cheats independently from the game. This is common with games like Metro Exodus. In this instance, it's usually possible to find such a tool available on the web, but I strong advise against running anything you aren't absolutely sure of the authenticity of. Again, it serves the purpose of making the game more readily testable, and easing things for players who just don't have the time to get really good at it. However, anti-cheat programs will identify such programs very quickly when online.

The last thing to consider is the onset of the age of modding, in which many developers have gotten increasingly open to user-generated content for their games. This often includes mods which make the game significantly easier, or even game-breakers; but if there's no online competition involved, that's usually a safe assumption.

Hopefully this will make modern games a bit more navigable for you!

# Answer
> 11 votes
I would like to add a slightly different perspective to this.

When publishing games on console, all game content, modes and options have to be listed as part of the submission and are subjected to (what these days seems to be theoretical) testing by the console manufacturers prior to release.

If a developer has added some semi-hidden cheat option, the functionality that is offered still has to be tested. If a bug is found that only happens when the cheat is running, this can delay the launch of the game. Why risk delaying launch by leaving code that was really only written to aid development?

Most code is developed under environments where there are "build configurations" that allow certain routines only to be included and executed under development environments (for example writing text into a log file to help understand what might have happened when a rare bug occurs) but this code is not present in final submission builds. It makes sense to include "cheat modes" in this code for the reason stated above.

For reference, I included an "autoplay" cheat in a game I submitted to Sony which demonstrated that all the Trophies could be collected (some were pretty hard to get) thinking it would speed up submission as it would test the Trophy collection for them. They rejected the submission as the same cheat then violated one of their rules that Trophies must require effort from the player to earn. The cheat was intended to ease the submission process, but in reality it delayed it.

# Answer
> 10 votes
In the early days of game development, few knew how to make a balanced game, and of those that did, didn't always have time to meet their launch window and make it balanced; most games were in the category of Nintendo Hard (*warning: TV Tropes*). Programming was also time-consuming, so it was often easier to program a cheat code in for testing, and it didn't always get taken back out again. The same is often true for other kinds of assets as well; many times assets like sprites, animations, music, and code are left-over on the cartridge, disc, or inside the game files. These are left-over artifacts from not having enough time to do everything a developer wanted to do.

The first major blows to cheat codes were the introduction of difficulty options and improved developer tools. Developer tools allowed for faster build times, more advanced programming languages, etc. Cheat codes were less necessary, because developers could quickly change memory and code. Difficulty options basically split gamers into two groups. The hardcore gamers that thought the challenges were rewarding and there shouldn't be an easy mode, and the casual gamers that thought a game should be accessible to (almost) everyone.

If a hardcore gamer-programmer had to introduce an easy mode for marketing reasons, it was usually in a mocking manner, like Doom Guy's baby pacifier face on "I'm Too Young To Die" difficulty. Much later, more accessible games would introduce a casual player's quick mode, called "Story Mode", with limited or no combat and no challenge whatsoever. This is the mode you're likely thinking off when you talk about a game you want to just enjoy quickly. At any rate, almost any game with difficulty modes was already easy and fast enough for a casual player, so introducing cheat codes wasn't necessary. If a game had codes, they were easter eggs or cosmetic differences.

Eventually, DLC became readily available. At first, it was just cosmetics or maybe a decent starting boost to the game. After a while, games were just designed to require absurd amounts of grinding that was fixed by paying some price for a triple-experience DLC. These games were designed to frustrate players, so no cheat codes here. They then moved on from this to energy meters and progress meters that ran in realtime, which you could advance faster by purchasing in-game premium currency, known as microtransactions. They also started adding loot boxes and battle passes for extra rewards that would move you along faster, and other pay-to-win mechanics. Cheat codes are antithetical to the concept of pay-to-win.

Also, keep in mind that many modern games are also live services. That means that you can play with other players, and you'll see their cool items and abilities, and want them for yourself, so they'll offer loot boxes and battle passes and everything else to entice you to spin money so you can be powerful and/or cool like that one person you saw.

In addition, a lot of game engines had "mod" capability. Anyone with skill could make a game do pretty much whatever they wanted to. You no longer had to cheat, just install a file to customize the game the way you want to. Any game with this system was also unlikely to have any built-in cheats, since the players could already customize the game however they wanted to. It simply didn't make sense to include a cheat mode. Also, games started introducing multiple game modes, like Minecraft's Creative Mode, where a player could build without fear of dying.

Most modern games don't have cheat codes (except maybe cosmetics) because (a) they would not be used by the target audience (e.g. hardcore gamers), (b) the game already has a ton of accessibility features and difficulty levels, (c) the game is intentionally grindy to extract dollars from your wallet, or (d) the game is nearly infinitely customizable anyways, so players can completely customize their experience.

As far as your specific idea goes, there are few cheat codes in modern games out there because there isn't any incentive to have them in a game in the first place. Hardcore games are not designed for casual players. Games with run long times don't really have a way to shorten the story they want to tell without cutting out critical plot elements, though many will let you skip some or most cutscenes, but that tends to leave first-time players confused. Casual games typically already have more than enough accessibility features without needing hidden codes. Microtransaction games intentionally stretch out the game time in hope of earning more dollars.

Also, cheat codes used to be hard to find, but today, you can find virtually any cheat code in seconds on Google, so that takes a lot of the fun out of it for many people. There is a small niche market with people like me that like discovering secrets and bugs, but even I would typically rather just have a menu option than have to find the code somewhere on the Internet just to play a game.

# Answer
> 3 votes
Actually playing through the entire game is the intended experience\* (even if that wouldn't be the best experience for some players).

Developers don't cater to things outside the intended experience if they feel:

* **It would take too much development time**

Providing something like god mode should not be that difficult, but even for something like that, one would still need to test how that interacts with the various mechanics the game has and test that everything still works (if there are, say, bottomless pits, and falling into one would trigger death to cause a respawn, removing the ability to die might mean you just keep falling, so you may need to specifically handle that, or the game may trigger death for physics interactions that would otherwise cause the game to break, which developers may or may not know about).

Other functionality may require a whole lot more development time.
* **It provides too little benefit**

This benefit can be monetary, for the sake of accessibility or inclusion, or anything else.

Also note that working through the various challenges in the game may make up the majority of the typical play time. So when a game is developed and priced with that play time in mind, developers may not expect many to be willing to pay that same price for a much shorter experience that only goes through the story, which would decrease the perceived benefit of such features.
* **It is contrary to their artistic vision**

One game (series) that's infamous for being very difficult and having no difficulty setting is Dark Souls, where the intention is to "bring everyone to the same level of discussion and the same level of enjoyment" (which seems like flawed reasoning, as different players have different skill levels and physical capabilities, if nothing else, but I digress). Their artistic vision was clearly for players to have a very specific experience, and they didn't want to betray that.

* Side note: in a few games, during difficulty selection, one of the options will say something like "this is the intended experience".

---

I'm not saying I necessarily approve of these reasons, and there are plenty of games that provide plenty of possible solutions that allow you to enjoy the game in this way (as mentioned in other answers). I'm merely explaining why developers may choose to not provide any such solution.

Most developers approve of content creators playing their game for the enjoyment of others, so if this lets you sufficiently enjoy the game, I don't see a problem there. Supporting such content creators (possibly just by watching them) may also indirectly support the developers, as this increases the exposure of the creator and may influence them to keep playing that game or sequels, which can serve as marketing for the game or developer.

# Answer
> 3 votes
As the other answers have talked about, cheat codes have morphed into open ways to customize the game, make it more convenient, and adapt to wider play styles. A more few examples which are so ubiquitous we don't think of them as cheat codes anymore include...

* The ability to skip to a given level, usually one you've already played (unlocked) and sometimes those you haven't.
* Fast travel.
* Quest markers.
* Slowing, stopping, and reversing time.
* Aim assist and auto-aim.
* Being able to save anytime you want.
* 100% recycling of items and built objects.
* Directional subtitles.
* Detailed difficulty customization.
* Changing difficulty mid-game.

# Answer
> 1 votes
Plenty of games have an easy mode where tricky actions become simpler and the amount of grind needed is reduced.

Some games have PVP where a god mode would be a deal breaker.

Some games have microtransactions where a god mode would be financially harmful.

# Answer
> 1 votes
In the pre-Internet age, cheatcodes had an important **advertising function**. Back then, the main source of information for gamers on what games to buy were print magazines. One standard section of these magazines were the cheatcode sections where they listed all the cheatcodes for games released in the past couple month. Stumbling over the cheatcodes for a game in the cheat section put the game back into the mind of the reader. Which meant that being mentioned there was free advertisement!

So it was common practice back then to wait for the magazines to review your game, and then send them a letter with the cheatcodes so they could print them in the next issue.

But then around the year 2000, every gamer got Internet access. Print magazines were replaced by gaming websites. People do not read gaming websites front-to-back like they do with magazines. They only read what seems interesting to them. Putting cheatcodes onto a website doesn't help to reach an audience of people who don't already own the game. And *if* people wanted cheatcodes, they went to specialized databases like GameFAQs where they specifically looked for the titles they owned.

So it's no coincidence that the beginning of the internet age is also the age where cheatcodes started disappeared.

# Answer
> 0 votes
I would also add to this that a lack of cheats and god mode makes completing the entire game take longer, having to redo harder sections the player fails at, over and over, therefore adding to the perceived 'value' of the game.

Plus the 'damn I am good' FEELING when a player fails many times to complete a section and then FINALLY succeeds.

# Answer
> 0 votes
I know the right answer to this: this first game code appears because the developer couldnt pass the game level to check the next one... so based on this idea, games arenot that dificult anymore, so gamecodes no longer need bcz ppl can pass any game, it is just a matter of time

# Answer
> -1 votes
I believe because 20 years ago we all were noobs on playing games, and we needed cheat codes then, nowdays most of the gamers already have large experience on gaming what makes many games be easy even tough those are harder then games 20 years ago. Bassically we learn how to play and those are no longer hard for us to make cheat codes. I remember I was using an program called ArtMoney for getting ingame money \>)

---
Tags: game-design
---


# Question
Title: Recursive function for LineRenderer with reflections causes Stack Overflow Error
I'm developing a 2D top down shooter game. I'm building the grenade functionality. The idea is that while you're holding the grenade button, it remains in your hand, and then when you release the button it throws the grenade. When the grenade is in your hand, I'm using a line renderer to show the trajectory of where the grenade will be thrown and bounce off walls.

I have a recursive function that uses linecasts to detect where the grenade will bounce and reflect the line as if it was bouncing off the wall. It's working as expected but it's somehow still giving a Stack Overflow Error. If I point the LineRenderer at a wall and put a breakpoint on the first line of the recursive function ThrowLineRaycast() it's only being called twice, and `_lineRendererPoints.Count = 3`.

```
void Update() {
    if (_isHeld && _throwable.ReleaseType == "Throw") {
        DrawThrowLine();
    }
}

private void DrawThrowLine() {
    _lineRendererPoints = new() { _rigidbody.position };
    ThrowLineRaycast(_rigidbody.position, transform.up, 0, _throwDistance);
    _lineRenderer.positionCount = _lineRendererPoints.Count;
    _lineRenderer.SetPositions(_lineRendererPoints.ToArray());
}

private void ThrowLineRaycast(Vector3 startPos, Vector3 direction, float distanceTraveled, float distanceRemaining, int hitNum = 0) {
    Vector3 endPos = startPos + (direction * distanceRemaining);
    LayerMask mask = LayerMask.GetMask("Walls", "WindowsAndCover");
    RaycastHit2D[] allHits = Physics2D.LinecastAll(startPos, endPos, mask);
    if (hitNum > allHits.Length - 1) {
        _lineRendererPoints.Add(endPos);
    } else {

        RaycastHit2D hit = allHits[hitNum];
        Vector3 hitPos = hit.point;
        Vector3 newDirection = Vector3.Reflect(direction, hit.normal);
        float totalDistanceToHit = distanceTraveled + hit.distance;
        float distanceRemainingAfterHit = distanceRemaining - hit.distance;

        if (hit.transform.gameObject.layer == LayerMask.NameToLayer("Walls")) {
            _lineRendererPoints.Add(hitPos);
            ThrowLineRaycast(hitPos, newDirection, totalDistanceToHit, distanceRemainingAfterHit, 0);
        } else if (hit.transform.gameObject.layer == LayerMask.NameToLayer("WindowsAndCover")) {
            if (GetThrowHeightFromLength(distanceTraveled, distanceTraveled + distanceRemaining) < _coverHeight) {
                _lineRendererPoints.Add(hitPos);
                ThrowLineRaycast(hitPos, newDirection, totalDistanceToHit, distanceRemainingAfterHit, 0);
            } else {
                ThrowLineRaycast(startPos, direction, distanceTraveled, distanceRemaining, hitNum + 1);
            }
        }
    }
}

private float GetThrowHeightFromLength(float distanceTraveled, float throwDistance) {
    return 3f;
}

```

Note: Ignore the `WallsAndCover` and throw height part. That hasn't been fully implemented yet, but the idea is that if the grenade is in the air and has a height greater than the height of the cover (something you can shoot over) it will ignore that hit. this is why I need the `LinecastAll` and `hitNum`, but that part of the code isn't even being hit yet.

# Answer
Watched a bunch of tutorials on bouncing lasers and found one that suggested adding `Physics2D.queriesStartInColliders = false;` to the `start` function. I'm using `awake` in this case so I added it and that solved the problem. So I guess the second iteration was colliding with the same collision that the first iteration hit.

It's strange that my debugging didn't reflect that issue. If that was the case I would expect the breakpoint to be hit way more and have way more Vector3's in `_lineRendererPoints`
> 0 votes

---
Tags: unity, c#
---


title: How to make a sprite fill the image?

text:
# Question
Title: How to make a sprite fill the image?
I created a custom UI Button:

However, when I use the sprite as the image for a button it doesn't fill out the whole "Collision" area:

This is an example of how I want it to fill the "Collision" area:

Any ideas on how to achieve this?

# Answer
> 2 votes
To me it appears you are setting up your button as a 9-slice, a technique that resizes the nine areas differently to keep borders sharp or corners round. But in your case you eight out the nine areas are transparent.

Documentation: https://docs.unity3d.com/Manual/9SliceSprites.html

What you want is slicing the normal image as close as possible to the button. After that your button should fill out always the full area.

Documentation: https://docs.unity3d.com/Manual/SpriteEditor.html

Depending on how much you want to stretch your button, you might take a closer look on how to get the 9 slice correctly set up.

---
Tags: unity, sprites, unity-ui
---


# Question
Title: How to implement a function that normally returns a float, but can sometimes fail?
In Godot GDScript, I have a function that returns a `float`.

Inside the body of the function, I use the built-in method `find`, that can return `-1` if nothing is found.

In that case, I could place a condition right before the loop and return the float `-1.0` (I can't return `null` and it looks like there aren't exceptions, nor optionals, nor other common things).

```
func get_my_float(c) -> float:

    var idx = p.find(c)

    for i in range(0, idx):

        //...

    return my_float

```

But: is there any other thing I can do?

Does it make any sense to return a `Variant`, instead?

# Answer
You are correct in that you can't return `null`, which is because you have declared in your method that it returns a `float`. So, yes, removing the type declaration so it returns a variant is an option.

If you do this, remember that you should check `null`.

Be aware that operating with `null` will cause an error. But since this error happens when you try to use `null` it is away from the cause of the `null`. Which does not make for the most useful of errors.

*Also the Godot editor will show green line numbers on the lines that are type-safe, and show gray line numbers otherwise (i.e. using variant or unsafe casts), which is useful when reviewing your code.*

---

You could return `NAN` (not a number) which would allow you to keep the `float` type. With a couple caveats:

* Consider if `NAN` might be a valid result in some cases.
* Remember that you need to check for `NAN`. And nothing is equal to `NAN`, in fact one of the ways to check if a variable is `NAN` is checking if it is different to itself, or you can use the more readable `is_nan(…)` method.

Similarly to `null`, the errors that come from `NAN` happen away from the cause. However operating with `NAN` will result in more `NAN`. Which is arguably worse that using `null`. Thus, if you can help it, **please don't use `NAN`.**

---

You are also correct that Godot does not have exceptions. You might, however, use `push_error` and return. Which leads to a question: why would you use `push_error`?

If you come from language that has exception, you might be familiar with the idea that some exceptions are intended to help the developer. For example "argument out of range" exceptions. You should not catch those exceptions. Instead, you should fix the code so they don't come up in runtime. However, you still want it to show during testing and debugging. And, of course, if some of them sneak into production, you want them to show up in logs.

You get that with `push_warning` and `push_error`. They will show up in the debugger, and also in logs. *And you cannot catch them like exceptions, because they aren't exceptions.*

You might also consider using `assert` for this purpose, or you can use the `breakpoint` keyword, given that those will interrupt in the debugger.

---

Option types and similar approaches has been proposed, but - at the time of writing - have not been implemented.

You *could* have a custom return type. For example you can define a nested class (add them at the bottom of the same file) with a `float` and a `bool`.

In Godot 3.x:

```
class OptionalFloat:
    var has_value:bool
    var value:float setget set_value

    func set_value(mod_value:float) -> void:
        value = mod_value
        has_value = true

```

In Godot 4:

```
class OptionalFloat:
    var has_value:bool
    var value:float:
        set (mod_value):
            value = mod_value
            has_value = true

```

And then use it like this:

```
func get_my_float(c) -> OptionalFloat:
    var result := OptionalFloat.new()
    var idx := p.find(c)
    if idx == -1:
        return result

    for i in range(0, idx):
        # …
        result.value = something
        # …

    return result

```

*The examples above do not handle the case where you try to consume the value without checking if there is any. You can define a getter alongside the setter to do that. And perhaps use `push_error` there.*

Be aware that these optional types would also require some kind of check (similar to checking for `null` or checking for `NAN`).

OK, you *could* do that. In particular if you really want to keep the type information. However, it is not a common approach. Instead people often fallback to variant, since it can represent a `float` (or whatever type) or `null`, also has some overhead, but you have to write less.

---

So Godot does not have out parameters. In fact, you cannot choose to pass by reference. But you can pass an array!

```
func get_my_float(c, result:Array = []) -> void:
    var idx := p.find(c)

    for i in range(0, idx):
        # …
        result.append(something)
        # …

```

Notice here that `result` is optional (it has a default value).

*In Godot 4 you could use a typed array (`Array[float]`).*

That is the approach that we would use if we need the return value, and also we need to have some additional optional output. *In fact, this approach is used in parts of Godot API.*

Ah, but in this case we have left the result as `void` here. So we could use the return value instead. That is, we might return an array (which could be empty for no result):

```
func get_my_float(c) -> Array:
    var result := []
    var idx := p.find(c)
    if idx == -1:
        return result

    for i in range(0, idx):
        # …
        result.append(something)
        # …

    return result

```

Here, since we are returning, we could use packed arrays. In Godot 3 you can use a `PoolRealArray`. And in Godot 4, the equivalent of the `PoolRealArray` is either `PackedFloat64Array` or `PackedFloat32Array` (in Godot 3 which one you get depended on whether or not you had a 64 bits build or 32 bits build). *And I point out we can use them when we are returning because these are value types.*

Be aware that this does not eludes a check either, since you would have to check if the array is empty.

---

You might be putting the effort in the wrong place. If you make your function take the index in a parameter, how to handle when the value is not found becomes a problem of the layer above… There you have better context and could pick an appropriate action. So the method at hand only needs to handle the "argument out of range" situation.

---

Speaking of appropriate actions. I don't know what you are doing, because I lack said better context… But given the method name, an option that comes to mind is set a fallback default result:

```
func get_my_float(c, fallback := 0.0) -> float:
    var idx := p.find(c)
    if idx == -1:
        return fallback

    for i in range(0, idx):
        # …

    return my_float

```

*Some examples of possible default values which might make sense depending on the context: `0.0`, `1.0`, `INF`, `-INF`, `NAN`.*

Alternatively, consider if you should think of a `get_or_add_my_float` method. Or something like that.

---

Another approach you might consider is to pass continuation callbacks.

Godot 4 has the `Callable` type, inline anonymous methods ("lambda"), and you can pass methods as `Callable` directly.

In Godot 3 you can use the `FuncRef` type and the `funcref` method to create them.

---

*You know better than me what the situation is. I have given you options, you decide.*
> 5 votes

---
Tags: software-engineering, gdscript
---


# Question
Title: How to read/edit data compressed in ZXML format for modding the game Chocolatier?
I'm trying to mod the game Chocolatier from 2007. It has two .xml files, but they don't look like conventional XML when I open them in VS Code or Notepad++. Here's a sample of what they look like:

strings.xml

settings.xml

In the comments, Quentin suggests that both files' contents beginning with the characters "ZXML" could mean this data is compressed in "Cubetto 5.0 Compressed Document Format".

If that's the case, how can I decompress and read these files, or re-compress my modded files back to this format?

# Answer
Please note that I can't know for sure that the programs linked through this post are "safe" for your computer; I always play with those files within a Virtual Machine to avoid most risks.

---

Ultimately, those "xml" files are compressed with zlib. The fastest way to take the data out is to use an hexadecimal editor (I use HxD) and remove the first 12 bytes, stopping just before `78 DA`. Then, using a python script like the following:

```
import zlib

f = open('strings.xml', 'rb')
decompressed_data = zlib.decompress(f.read())
f.close()

f2 = open('out.strings.xml', 'wb')
f2.write(decompressed_data)
f2.close()

```

You'll find the XML file in `out.strings.xml`. You'll realize that it contains lots of Excel related stuff, so you could open it right away with Excel and voilà!

But that's not exactly what you're after if you want to modify the strings. To do so you'll have to work harder and install QuickBMS and run a couple of scripts, one for extracting:

```
idstring "ZXML"
get ZSIZE long
get SIZE long
savepos OFFSET
get NAME filename
clog NAME OFFSET ZSIZE SIZE

```

and one to re-compress it:

```
comtype zlib_compress
get SIZE asize
log MEMORY_FILE 0 0
putdstring "ZXML" 4 MEMORY_FILE
put 0 long MEMORY_FILE
put SIZE long MEMORY_FILE
savepos OFFSET MEMORY_FILE
append
clog MEMORY_FILE 0 SIZE SIZE
append
get ZSIZE asize MEMORY_FILE
math ZSIZE - OFFSET
goto 4 MEMORY_FILE
put ZSIZE long MEMORY_FILE
get NAME basename
string NAME + ".zxml"
get SIZE asize MEMORY_FILE
log NAME 0 SIZE MEMORY_FILE

```

I have tried the one to decompress it (it works!) but I have not been able to test the other one.

It is not a Cubetto file, it's rather a "custom" file format, likely made to 1) hide data to make tampering harder 2) make the loading of the game faster.

I'm not a pro-hacker, and as you see, I did not come up with those scripts myself. I admit that my search-fu is strong, though. Visiting the forum I've linked to will make you realize that you're not the first one in your situation. You'll also find information to figure out other file formats so you can further mod your game.

P.S. gamedev.stackexchange.com is not really the best place to ask this type of questions; it often requires back-and-forth between users, and game reverse engineering enthusiasts are pretty rare. What makes things even more complicated (at least for folks like me) is that I don't want to install shady stuff on my workstation so I have to work from within a virtual machine to use all the "hacking" tools available on the Internet, and also the access to the game files is pretty difficult, as you realized in the comments.

P.P.S. For what it's worth, I found the MacOS version through here, and the files are not compressed like for the windows version, so that could give you a hint about what you'll find in there.
> 0 votes

---
Tags: modding, serialization, xml, asset-workflow
---


# Question
Title: Buttons' hitboxes shift a bit lower when I maximize my game window
I have a simple scene in my Unity 3d project. There is a Canvas (UI Scale Mode in Canvas Scaler is set to Constant Pixel Size but the same is with Scale with screen size), Panel inside it (Stretched to fill the Canvas) and a Button on the Top-Left corner.
In Project Settings -\> Player -\> Resolution and Presentation -\> Fullscreen Mode is set to Windowed. In editor this button works fine but when I build the game and make it maximized the hitbox of the button moves a bit lower than the button (The white rectangle is the button and as the green rectangle I draw the real hitbox of the button):
I googled a lot, I tried it in different projects, I changed my UI a lot but nothing helps (only if I set Fullscreen window instead of Windowed but I don't need this).
I also found out that this happens only if I place elements near to the right side of my window, everywhere else all the buttons work fine.
I also found this thread about the similar problem to mine, but there is no solution. So how can I fix that? Thanks!

# Answer
> 0 votes
Finally, after some months I found the answer. I saw an Unity project and there was normal hitboxes of buttons and it was quite interesting. The version of the project was 2020.3.39f1 (version of mine was 2021.3.4f1). I didn't want to downgrade the version of my project so I tested version 2021.3.22f1. Everything was fine in the version. So as I understood, it was just a bug of the Unity version 2021.3.4f1.

---
Tags: unity, raycasting, user-interface
---


# Question
Title: colored triangle where the color changes over time
I am trying to draw a triangle which changes color over time. My implementation is by using uniform variable.

my fragment shader-

```
#version 330 core
out vec4 FragColor;
uniform float var;

void main()
{
    FragColor = vec4(var*0.2, var*0.333, var*0.7, 1.0f);
}

```

in render loop

```
while (!glfwWindowShouldClose(window))
{
    time = 1.0f*fabs(sin(glfwGetTime()*3.1416f));
    processInput(window);
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    shader1.use();
    shader1.setFloat("var", time);
    glBindVertexArray(vao);
    glDrawArrays(GL_TRIANGLES, 0, 3);

    glfwPollEvents();
    glfwSwapBuffers(window);
}

```

But the triangle goes blue to dark. What is missing?

# Answer
> 1 votes
your `sin()` will only fluctuate between -1 to 1, and u turn that into 0 - 1 by using the `fabs` function, which doesn't get amplified (multiplication by `1.0f`). so the line

```
time = 1.0f*fabs(sin(glfwGetTime()*3.1416f));

```

will result in a vec4 color range of `(0, 0, 0, 1)` to `(0.2, 0.333, 0.7, 1)` in a **uniform** pace for all `rgb` elements. To get better results, define 3 variables and calculate the color coefficient for each `RGB` element separately, whcih results in a **non-uniform pace** for the color change, something like this (i use pseudo-code):

```

...
time = glfwGetTime();
float r_amp = fmod(time, 0.5f);
float g_amp = fmod(time, 1.0f);
float b_amp = fmod(time, 2.0f);
...

shader1.use();
shader1.setFloat("var_r", r_amp);
shader1.setFloat("var_g", g_amp);
shader1.setFloat("var_b", b_amp);
...

```

and in your fragment shader clamp those values to a 0 to 1 range (or do that on the cpu side):

```
#version 330 core
out vec4 FragColor;
uniform float var_r;
uniform float var_g;
uniform float var_b;

void main()
{
    FragColor = vec4(var_r*2, var_g*1, var_b*0.5, 1.0f);
}

```

you can also resort to `sin()` for fluctuations as you did initially but u need to multiply `time` by a different coefficient for each `var` and then calculate the `sin()`. for now `fmod()` will be much easier to understand but later on especially in performance-critical settings, `sin()` is faster than `fmod()`

---
Tags: opengl, c++
---


# Question
Title: Converting physics example to Velocity Verlet / Leapfrog method
I'm looking at the impressive video about verlet integration. I managed to implement a sphere falling, exactly like the video up to the minute mark 2:19 in the video.

I want to use velocity verlet instead. After looking at some examples, it's not going to well. All the examples I could find have poor variable names and are not made as objective programming with a solver class.

Here is the falling ball python code.

```
import weakref
import numpy as np

dt = 1.0
frames = 10

class verlet_obj:
    instances = []
    def __init__(self, position_current):
        self.position_current = position_current
        self.position_old = position_current
        self.acceleration = np.zeros(3)
        self.velocity = np.zeros(3)

        #reference self via weakref
        self.__class__.instances.append(weakref.proxy(self))

    def updatePosition(self, dt):
        self.velocity = self.position_current - self.position_old

        self.position_old = self.position_current

        # perform velvet
        self.position_current = self.position_current + self.velocity + self.acceleration * dt * dt

        # reset acceleration
        self.acceleration = 0

    def accelerate(self, acceleration):
        self.acceleration += acceleration

class Solver:
    def __init__(self, dt):
        self.dt = dt
        self.gravity = np.array([0, -9.8, 0])

    def update(self):
        self.apply_gravity()
        self.updatePositions()

    def updatePositions(self):
        for obj in verlet_obj.instances:
            obj.updatePosition(self.dt)

    def apply_gravity(self):
        for obj in verlet_obj.instances:
            obj.accelerate(self.gravity)

# run
solver = Solver(dt)
sphere1 = verlet_obj(np.array([0,0,0]))
for frame in range(0,frames):
    solver.update()
    # print y pos
    print(sphere1.position_current[1])

```

my attempt is to follow this source:

This is my attempt:

```
import weakref
import numpy as np
from sg_blender import *
dt = 1
frames = 11

class verlet_obj:
    instances = []
    def __init__(self, position_current):
        self.position_current = position_current
        self.position_old = position_current

        self.velocity_old = np.zeros(3)
        self.velocity_intermediate = np.zeros(3)
        self.velocity_current = np.zeros(3)
        self.acceleration = np.zeros(3)

        #reference self via weakref
        self.__class__.instances.append(weakref.proxy(self))

    def updatePosition(self, dt):
        self.position_old = self.position_current
        self.position_current = self.position_current + self.velocity_old + 0.5 * self.acceleration * dt**2

    def updateVelocityIntermediate(self, dt):
        self.velocity_intermediate = self.velocity_old + 0.5 * self.acceleration * dt

    def accelerate(self, acceleration):
        self.acceleration += acceleration

    def reset_acceleration(self):
        self.acceleration = np.zeros(3)

    def new_velocity(self, dt):
        self.velocity_current = self.velocity_intermediate + 0.5 * self.acceleration * dt
        self.velocity_old = self.velocity_current

class Solver:
    def __init__(self, dt):
        self.dt = dt
        self.gravity = np.array([0, -9.8, 0])

    def update(self):
        self.new_positions() # step 2
        self.intermidate_velocity() # step 3
        self.reset_acceleration() #step 4
        self.apply_gravity() #step 4
        self.new_velocity() #step 5

    def new_positions(self):
        for obj in verlet_obj.instances:
            obj.updatePosition(self.dt)

    def reset_acceleration(self):
        for obj in verlet_obj.instances:
            obj.reset_acceleration()

    def intermidate_velocity(self):
        for obj in verlet_obj.instances:
            obj.updateVelocityIntermediate(self.dt)

    def new_velocity(self):
        for obj in verlet_obj.instances:
            obj.new_velocity(self.dt)

    def apply_gravity(self):
        for obj in verlet_obj.instances:
            obj.accelerate(self.gravity)

# run

solver = Solver(dt)
sphere1 = verlet_obj(np.array([0,0,0]))
for frame in range(0,frames):
    solver.update()
    # print y pos
    print(sphere1.position_current[1])

```

I'm not sure if I understand the concept of `dt` correctly, but after 10 iterations, I get the y position as -440. But according to falling in constant acceleration kinematic equation, this is not correct.

```
x = x_0 + v_0 * t + 1/2 * a t^2
# zero start height, zero start speed
# ==>
x = 1/2 * a t^2
x = 1/2 * - 9.8 * 10**2
  = -490

```

# Answer
> 0 votes
Solved. Maybe there are too many functions and it needs some clean up. But after testing the anaytic function of an object in free fall `x = 1/2 * a * t^2` and the result, I noticed my result changed drastically with the time-step parameter. `dt` was missing in step 2 (calculate new position).

Here is the result of `dt = 1` , free falling of 15 seconds:

and `dt = 0.1`

Code: ( yes needs some clean up )

```
import weakref
import numpy as np
import matplotlib.pyplot as plt

# dt* frames = 15 seconds
scale = 10
frames = 15*scale
dt = 1.0/scale

class verlet_obj:
    instances = []
    def __init__(self, position_current):
        self.position_current = position_current
        self.position_old = position_current

        self.velocity_old = np.zeros(3)
        self.velocity_intermediate = np.zeros(3)
        self.velocity_current = np.zeros(3)
        self.acceleration = np.zeros(3)

        self.__class__.instances.append(weakref.proxy(self))

    def updatePosition(self, dt):
        self.position_current = self.position_old + self.velocity_old * dt + 0.5 * self.acceleration * dt**2

    def updateVelocityIntermediate(self, dt):
        self.velocity_intermediate = self.velocity_old + 0.5 * self.acceleration * dt

    def accelerate(self, acceleration):
        self.acceleration += acceleration

    def reset_acceleration(self):
        self.acceleration = np.zeros(3)

    def new_velocity(self, dt):
        self.velocity_current = self.velocity_intermediate + 0.5 * self.acceleration * dt
        self.velocity_old = self.velocity_current
        self.position_old = self.position_current

class Solver:
    def __init__(self, dt):
        self.dt = dt
        self.gravity = np.array([0, -9.8, 0])

    def update(self):
        self.new_positions() # step 2
        self.intermidate_velocity() # step 3
        self.reset_acceleration() #step 4
        self.apply_gravity() #step 4
        self.new_velocity() #step 5

    def new_positions(self):
        for obj in verlet_obj.instances:
            obj.updatePosition(self.dt)

    def reset_acceleration(self):
        for obj in verlet_obj.instances:
            obj.reset_acceleration()

    def intermidate_velocity(self):
        for obj in verlet_obj.instances:
            obj.updateVelocityIntermediate(self.dt)

    def new_velocity(self):
        for obj in verlet_obj.instances:
            obj.new_velocity(self.dt)

    def apply_gravity(self):
        for obj in verlet_obj.instances:
            obj.accelerate(self.gravity)

# run code and check with analyic
solver = Solver(dt)
sphere1 = verlet_obj(np.array([0,0,0]))
y_sim = []
for frame in range(0,frames):
    solver.update()
    y_sim.append(sphere1.position_current[1])

x_sim = np.arange(0, 15, dt)
x = np.linspace(0, 15, 1000)
y = - 1/2 * 9.8 * x**2

plt.plot(x,y, label = "analytic")
plt.plot(x_sim,y_sim, label = "velocity verlet")
plt.legend()
plt.grid()

```

---
Tags: physics, python, integration
---


# Question
Title: Is writing an if statement for every element in an array the most efficient way to do so?
I have a few string arrays for which I can cycle what the current active element is (of which there can only be one at a time) using the number keys. Something like the item inventory in Half-Life. I want to arrange it so that when I have a particular element selected, and press the select key, I set my weapon state machine to the corresponding weapon. I would do that with something like this:

```
    void SelectionButton(string _selectionButton)
{
    if (_selectionButton == "a11")
    {
        _weaponStateManager.SwitchState(_weaponStateManager._weaponStateDrag);
    }
    //continue this for each element in each array
}

```

The problem is that I would need to write an if statement for each element in each array. I am concerned that maybe this is not the most efficient way to do this - maybe looping through the entire list of possible options every time I switch weapons is not the best idea? I thought to maybe use dictionaries, but I was not sure how to relay the state definition for the corresponding element in the array to the state manager.

If using a long string of if statements is the correct way to handle this, then that is OK. I am just concerned that this is inefficient.

# Answer
When you compare the same variable against multiple values, then you can do that with a `switch`/`case` statement:

```
switch (_selectionButton) {
    case "a11":
      _weaponStateManager.SwitchState(_weaponStateManager._weaponStateDrag);
      break;
    case "a12":
      _weaponStateManager.SwitchState(_weaponStateManager._weaponStateDrog);
      break;
    case "a13":
      _weaponStateManager.SwitchState(_weaponStateManager._weaponStateDrug);
      break;
}

```

Is it "efficient"? Well, does it matter? You are talking about code that reacts to a button press. That doesn't even happen every frame. Micro-optimizing code that gets executed infrequently and already has a negligible runtime is usually more effort than it is worth.

But if you really want to optimize this, then you could use a lookup table.

Identify the buttons not by a `string` but by an `int`, with those `int`s being indexes to an array of whatever type `_weaponStateDrag` is. That way you can directly fetch the correct state for the array index out of that array. Accessing an array entry by index is a very fast operation.

```
private WeaponState[] weaponStatesByButtonId; // propagate via inspector or via code in Start or Awake

void SelectionButton(int _selectionButtonId)
{
       _weaponStateManager.SwitchState(weaponStatesByButtonId[_selectionButtonId]);
}

```
> 2 votes

---
Tags: unity, state
---


title: TCP Socket communication with unity

text:
# Question
Title: TCP Socket communication with unity
I am working on communicating unity application with an PC app. Since I doesn't know how socket programming can be implemented in unity.Can anybody please help me in creating a simple small application using TCP socket with unity

# Answer
Unity has two different networking subsystems: The old but still available Legacy Networking API and the New UNET Networking API. But both are high-level APIs designed around the Unity engine and don't offer low-level TCP/IP functionality (both are based on UDP). That means you can't use them to interface with something not developed in or specifically for Unity, especially not something which expects a TCP connection.

You can also use the Unity class `UnityWebRequest` to interface with programs which use a HTTP-based communication protocol (like SOAP or REST, for example). But this class doesn't provide raw TCP sockets either.

However, nothing stops you from using the standard networking classes available in the .NET framework. Specifically the class `Socket` or the more high-level class `TcpClient` and the class `NetworkStream` are of interest here. Details about how to use the .NET socket classes aren't game-development specific, so you should ask about them on Stackoverflow. By the way: I haven't tried but I can't imagine that this works on platforms which don't have a low-level TCP API, like for example HTML5.
> 1 votes

# Answer
I’ve successfully used standard c# UDP and TCP connections in Unity. The main issue is that you’ll need to have it on a separate thread. Which Unity hates. So you need to make sure you have threadsafe data structures that are passed between the main Unity program (main thread) and the data being streamed over the socket (other thread).
> 0 votes

---
Tags: c#, unity, socket
---


# Question
Title: How do I make a ceiling limit to an asteroids-like game in Godot?
I'm making a game similar in concept (physics-wise) to "asteroids" where a spaceship moves around on a screen from left to right, shooting stuff.

The problem is I have no idea how to set a height limit for my player so it doesn't outfly the parallax background. I've tried a kinematic body 2D that moves left and right with the player so it can't outrun it but the player is pushing it upwards when I test it.

What should I do in such a scenario?

# Answer
I was an idiot 2 days ago, it was in fact simple (I am a beginner in GDscript though) I just needed to use position.y, checking if the player had hit the ceiling or the floor, sorry if I wasted anyone's time.
> 0 votes

---
Tags: physics, godot
---