# Question
Title: Blitting GStreamer's decoded buffer into a Unity render texture
I'm working on a Unity native plugin that runs a `gstreamer` pipeline in the background, decodes it using hardware decoding, then copies the texture over to a render texture to be displayed in Unity.

I have my `GStreamer` already working, I can run it from Unity and it creates a window with the camera output, all decoded on the GPU. From what I can see, `GStreamer` has a parameter in the `d3d11videosink` to "draw-on-shared-texture" of format `DXGI_FORMAT_R8G8B8A8_UNORM`. It also has an signal that gets called when `gstreamer` is about to draw, and a draw command to draw on a "shared handle".

I've only seen code out there to copy a decoded texture on the CPU and copying it back on the GPU, but never GPU =\> GPU copies. How do I go about it?

Also, I know that unity recommends doing all graphic operations in the reader thread using `GL.IssuePluginEvent`, but how am I supposed to do that when `GStreamer` doesn't let me access the texture when I want, only during the `begin_draw` callback.

I don't know much about DX11 or native unity plugin in general, and I am very lost. Any help would be appreciated.

Here's some code for my failed attempt at trying to get `GStreamer` to draw onto my `ID3D11Resource` pointer given by unity using `RenderTexture.GetNativePtr()`:

```
static GstFlowReturn begin_draw_callback(GstElement* videosink, gpointer data)
{
    GstApp* app = (GstApp*)data;
    ID3D11Resource* resPtr = app->GetResourcePtr();
    if (resPtr == nullptr) {
        return GST_FLOW_OK;
    }

    // Your custom code here
    Debug::Log("BEGIN DRAW");

    HANDLE handle;
    IDXGIResource1* pResource;
    HRESULT res1 = resPtr->QueryInterface(__uuidof(IDXGIResource1), (void**)&pResource);
    HRESULT res2 = pResource->CreateSharedHandle(
        nullptr, DXGI_SHARED_RESOURCE_READ | DXGI_SHARED_RESOURCE_WRITE, nullptr, &handle);

    std::string res1Str = HRESULTToString(res1);
    std::string res2Str = HRESULTToString(res2);
    Debug::Log(res1Str);
    Debug::Log(res2Str);

    gpointer shard_handle = (gpointer)pResource;
    guint texture_misc_flags = D3D11_RESOURCE_MISC_FLAG::D3D11_RESOURCE_MISC_SHARED;
    guint64 acquire_key = NULL;
    guint64 release_key = NULL;

    g_signal_emit_by_name(videosink, "draw", shard_handle, texture_misc_flags, acquire_key, release_key, nullptr);

    return GST_FLOW_OK;
}

```

# Answer
Your issue here is that you're trying to create a shared handle from a resource created by unity. Textures created by unity won't have the flags you're looking for.

```
// Create the shared texture
D3D11_TEXTURE2D_DESC desc = {};
desc.Width = 1920;  // Replace with your desired width
desc.Height = 1080; // Replace with your desired height
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT::DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
desc.CPUAccessFlags = 0;
desc.MiscFlags = D3D11_RESOURCE_MISC_SHARED;

hr = device->CreateTexture2D(&desc, nullptr, &(instance->tempTexture));
if (FAILED(hr)) {
    Debug::Log("Couldnt create texture");
    return false;
}

// Share the texture
IDXGIResource* pDXGITexture = nullptr;
hr = (instance->tempTexture)->QueryInterface(__uuidof(IDXGIResource), (void**)&pDXGITexture);
if (FAILED(hr)) {
    Debug::Log("Couldnt DXGI res");
    return false;
}

HANDLE sharedHandle = nullptr;
hr = pDXGITexture->GetSharedHandle(&sharedHandle);
if (FAILED(hr)) {
    Debug::Log("Couldnt create shared handle");
    pDXGITexture->Release();
    return false;
}

```

Consider creating a texture yourself inside your plugin, and using making it a Unity texture by using the `ID3D11Texture2D*` inside Texture2D.CreateExternalTexture().

Your GStreamer callback shouldn't look more complicated than this:

```
static GstFlowReturn begin_draw_callback(GstElement* videosink, gpointer data)
{

    GstApp* app = (GstApp*)data;
    HANDLE tempSharedHandle = app->GetTempSharedPtr();

    if (tempSharedHandle == nullptr) {
        //Debug::Log("Invalid shared handle?");
        return GST_FLOW_OK;
    }

    gpointer shard_handle = (gpointer)tempSharedHandle;
    guint texture_misc_flags = D3D11_RESOURCE_MISC_FLAG::D3D11_RESOURCE_MISC_SHARED;
    guint64 acquire_key = NULL;
    guint64 release_key = NULL;

    g_signal_emit_by_name(videosink, "draw", shard_handle, texture_misc_flags, acquire_key, release_key, nullptr);

    return GST_FLOW_OK;
}

```

If you want example of how to write clean Unity plugins that interacts with the graphic devices, consider looking at KlakSpout which achieve roughly the same, but with a different video framework.
> 1 votes

---
Tags: unity, c++, directx11, plugin
---


# Question
Title: LeanTween | Rect Transform Moving To Incorrect Position
I am using LeanTween to animate my menu selector.

This is how is looked prior to animating it with LeanTween:

And when I animate it with Leantween, for some reason it is positioned much further away:

Logic:

First I am starting the tween, and I am passing the RectTransform next to each skill when the player pressed up or down.

```
public void AnimateSubMenuSelector()
    {
        var xPos = MyRectTransform.localPosition.x;
        LeanTween.moveX(MyRectTransform, xPos - 25f, .5f).setLoopPingPong();
    }

public override void SetAssignedRectTransform(RectTransform rectTransform)
    {
        AssignedPosition = rectTransform.position;

    }

```

Then I update the Selector's position every frame with its current x position and it's assigned y position.

```
public override void UpdatePosition()
    {

MyRectTransform.position = new Vector2 (MyRectTransform.position.x, AssignedPosition.y) ;
    }

```

It animates correctly, and it moves to the correct y position of the hovered skill, but I don't understand why it's x position is moved so far to the left.

Is anyone that is familiar with LeanTween able to assist me? Thanks so much for taking the time!

# Answer
This is probably late but I had this issue, and the problem was that I was using the Gameobject variable and not the RectTransform variable as the first argument.

So instead of doing this

```
LeanTween.moveX(gameObject, xPos, .5f);

```

You use the RectTransform component instead like so;

```
LeanTween.moveX(gameObject.GetComponent<RectTransform>(), xPos, .5f);

```

I hope it helps someone.
> 0 votes

---
Tags: unity, tweening
---


title: Pygame polygon click detection

text:
# Question
Title: Pygame polygon click detection
Here is my problem: I am creating a game and I have a board made out of polygons (hexagons). I want to be able to click on the different tiles but I can't find a simple method. I understood how to detect a click on basic surfaces such as rectangle or pictures, but not with more complex shapes like hexagons. Is it possible to do so?

I first searched for a Pygame function close to this but I didn't find any. Then I searched for the sprites, and I think it is possible, but very long. And the last way I found was to simply detect the color. However I don't want to change the color of the tiles.

How can I detect a click on a polygon? (Hexagons specifically)

# Answer
I am currently using PyGame to build a small RPG game project, and I can personally attest that there is no built-in way to do this, at least nothing that I could find in the documentation or forums. Which is obviously very annoying and took me a long time to figure out.

The way I solved it was by:

**1.** Having a game loop that detects all hardware inputs from the mouse or keyboard:

```
for event in pygame.event.get():

```

**2.** Checking if a particular event is a mouse click event:

```
if event.type == pygame.MOUSEBUTTONUP:

```

**3.** Getting the position on screen where the mouse clicked:

```
pygame.mouse.get_pos()

```

**4.** Checking if anything with a special "clickable" attribute is on the screen at that position, and doing appropriate actions. For example, if I wanted to check for a particular object to see if the cursor was over that object at the moment of the click, I would do:

```
if clickableObject.collidepoint(mousePosition):

```

Hopefully this helps!

---

Edit: I reread your question and am now realizing you wanted to know specifically about *polygon* detection, rather than general shape detection. Apologies if I was not answering your specific question. You may want to use something like Box2D for anything more complicated than a rectangular collision area, but most polygons should just be a matter of doing some more math.
> 0 votes

# Answer
I just ran into this issue when creating a board using triangles, I simply wanted to highlight whichever triangle the mouse was hovering over. As such I figured out:

When drawing the polygons you can simultaneously use the `collidepoint()` function to get a bool from the mouse position.

e.g.

```
if pg.draw.polygon(screen, white, polygon, 1).collidepoint(pg.mouse.get_pos()):
    pg.draw.polygon(screen, white, polygon, 0)

```
> 1 votes

# Answer
First, I want to thank you for your answer. I tried a method using the first 3 steps you gave, it worked (approximately) but it was not so optimized. I couldn't figur how to create a clickableObject using polygons. Then I discovered the masks, and using a mask on a polygon picture worked with the .collidepoint(pos). I hope it will work for my 70 polygons on the screen, but it worked just fine for one...

In my case I was using hexagons and I admit it is a very regular shape, I just find it strange that we could not use the "normal method".

Thanks again, and I hope I will one day play your RPG Pygame game.

~Definity
> 0 votes

# Answer
You can use pygame and PIL. I have this code:

```
import pygame, PIL.Image
pygame.init()

info = pygame.display.Info()
root = pygame.Surface((info.current_w, info.current_h))

def isPolygonInCords(pos: list, cordsOfPolygon):
    global info, root
    pygame.draw.polygon(root, (255, 255, 0), cordsOfPolygon)
    a = pygame.image.tostring(root, 'RGB')

    b = PIL.Image.fromBytes('RGB', (info.current_w, info.current_h), a)

    try:
        return b.getpixel(pos) == (255, 255, 0)

    except:
        return None

```
> 0 votes

---
Tags: pygame, polygoncollider2d
---


# Question
Title: In my Roblox Tycoon game, my button is not working
I am a rookie at Lua and Roblox Studio in general. I am attempting an easy and reasonably simple tutorial on how to make a pretty good looking tycoon game. In my "Core" script, I am attempting to make it so when you press a button, a dropper appears, or whatever the StringValue has assigned it to (it is inside the button model). Here is the core script:

```
local tycoon = script.Parent.Parent

local mainItems = tycoon:FindFirstChild("MainItems")
local values = tycoon:FindFirstChild("Values")

local buttons = tycoon:FindFirstChild("Buttons")
local purchasedItems = tycoon:FindFirstChild("PurchasedItems")

local objects = {}

mainItems.OwnerDoor.Door.Touched:Connect(function(hit)
    if values.OwnerValue.Value == nil then
        local player = game.Players:GetPlayerFromCharacter(hit.Parent)
        if player then
            if player:FindFirstChild("HasTycoon").Value == false then
                values.OwnerValue.Value = player
                mainItems.OwnerDoor.Title.SurfaceGui.TextLabel.Text = tostring(values.OwnerValue.Value).."'s Tycoon"
            end
        end
    end
end)

if buttons then
    for i, v in pairs(buttons:GetChildren()) do
        spawn(function()
            if v:FindFirstChild("Button") then

                local newObject = purchasedItems:FindFirstChild(v.Object.Value)
                if newObject ~= nil then
                    objects[newObject.Name] = newObject:Clone()
                    newObject:Destroy()
                else
                    v:Destroy()
                end

                if v:FindFirstChild("Dependency") then
                    v.Button.Transparency = 1
                    v.Button.CanCollide = false
                    v.Button.BillboardGui.Enabled = false
                    coroutine.resume(coroutine.create(function()
                        if purchasedItems:WaitForChild(v.Dependency.Value) then
                            v.Button.Transparency = 0
                            v.Button.CanCollide = true
                            v.Button.BillboardGui.Enabled = true
                        end
                    end))
                end

                v.Button.Touched:Connect(function(hit)
                    local player = game.Players:GetPlayerFromCharacter(hit.Parent)
                    if player then
                        if values.OwnerValue.Value == player then
                            if v.Button.CanCollide == true then
                                if player:FindFirstChild("leaderstats").Cash.Value >= v.Price.Value then
                                    player.leaderstats.Cash.Value -= v.Price.Value
                                    objects[v.Object.Value].Parent = purchasedItems
                                    v:Destroy()
                                end
                            end
                        end
                    end
                end)
            end
        end)
    end
end

```

It is a pretty long script, but my error occurs on line 42. In my output, the error reads:

```
Infinite yield possible on 'Workspace.Tycoons.Tycoon.PurchasedItems:WaitForChild("Dropper")'.

```

# Answer
Let's look at line 42:

```
if purchasedItems:WaitForChild(v.Dependency.Value) then

```

And next let's look at the documentation for Instance:WaitForChild():

> This function does not yield if a child with the given name exists when the call is made.
>
> `Instance:FindFirstChild()` is a more efficient alternative to `WaitForChild()` for objects that are assumed to exist.
>
> If a call to this method exceeds 5 seconds without returning, and no `timeOut` parameter has been specified, a warning will be printed to the output that the thread may yield indefinitely. This warning takes the following form where X is the parent's name and Y is the child's name:
>
> `Infinite yield possible on 'X:WaitForChild("Y")'`

In other words, `Infinite yield possible` is warning you that when the code executed, the desired parameter didn't exist for more than 5 seconds. Often means you asked the code to find something that wasn't there.

In your case specifically, the parameter `v.Dependency.Value` resolved to `"Dropper"`, but it was unable to get the Dropper object/model before it timed out.

In the comments, you said that your Explorer matched the one in the tutorial. That's good & probably covers the next part, but I'm going to mention this again anyway:

The first thing I would check it to make sure there's not some syntax error. Programming can be painfully literal doing what the code says rather than what was meant and a simple typo can lead to inscrutable errors. Double check the spelling and capitalization in your code, folder names and model names against the tutorial. Make sure that the folders are located in the appropriate locations. It may help to back track to this earlier tutorial video where the Dropper model is made.

That said, I did a quick skim of the YouTube comments noticed someone asked the author about the same error you had:

> is it normal to get a infinite yield in dropper1?
>
> > Yes, that's because we are using WaitForChild("")

So you could have done everything exactly right (with respect to the tutorial) and still be having this problem. If that's the case, you consider some alternatives as described in this Stack Overflow answer. Here's a summary:

You could give the code a longer period before it times out by adding a second argument:

```
local timeout = 10 -- seconds
if purchasedItems:WaitForChild(v.Dependency.Value, timeout) then
    v.Button.Transparency = 0
    v.Button.CanCollide = true
    v.Button.BillboardGui.Enabled = true
else
    warn("Could not find v.Dependency.Value")
end

```

You could also try changing from `WaitForChild()` to `FindFirstChild()`. The later won't generate `Infinite yield possible` errors, but it will give `Attempt to index nil` if it can't locate the target, so it might simply be trading one problem for another. And the tutorial author already uses `FindFirstChild()` in other parts of the code & is aware that `WaitForChild()` can result in `Infinite yield possible` errors. So I would assume that if swapping from `WaitForChild()` to `FindFirstChild()` was a fix, they would have mentioned that in the comments &/or updated the tutorial. I'm mentioning it as an option for the sake of completeness since it was discussed in the post I linked above.
> 2 votes

---
Tags: scripting, lua, roblox
---


# Question
Title: Is vertex coordinate limited to -1 to +1f range
I thought that everything outside of `[-1.0f, +1.0f]` should not be renderable in Open GL. However, this code renders just fine with Silk.NET. I draw 3 axes and one of them is longer than the others.

```
private static readonly float[] AxisPoints =
{
  // X
  -2.0f, 0.0f, 0.0f,
  2.0f, 0.0f, 0.0f,

  // Y
  0.0f, -1.0f, 0.0f,
  0.0f, 1.0f, 0.0f,

  // Z
  0.0f, 0.0f, -1.0f,
  0.0f, 0.0f, 1.0f
};

private static readonly uint[] Indices =
{
  0, 1,
  2, 3,
  4, 5
};

var numberOfLines = AxisPoints.Length / 3 / 2;

gl.VertexAttributePointer(0, numberOfLines, VertexAttribPointerType.Float, 3, 0);
gl.DrawElements(GLEnum.Lines, Indices.Length, DrawElementsType.UnsignedInt, 0);

```

**Fragment shader**

```
#version 330 core
out vec4 FragColor;

void main()
{
    FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);
}

```

**Vertex shader**

```
#version 330 core
layout (location = 0) in vec3 Position;

uniform mat4 Model;
uniform mat4 View;
uniform mat4 Projection;

void main()
{
    gl_Position = Projection * View * Model * vec4(Position, 1.0);
}

```

**Question**

What is the minimum and maximum value that I can specify for a vertex?

# Answer
> I thought that everything outside of \[-1.0f, +1.0f\] should not be renderable in Open GL.

The `[-1.0f, +1.0f]` range is what you have to arrive at as **the output** of your vertex shader. Because anything outside of that range is outside of the player's screen rectangle. But during any of the steps that come before that, OpenGL lets you use the whole range of single-precision floating point values.

How your intermediate coordinates scale in relation to the screen coordinates is managed by the matrices. For example, if you have two 3d models, one using coordinates in the `[-1.0f, +1.0f]` range and the other in the `[-1000.0f, +1000.0f]` range, then you can use different model matrices with different scaling factors for them. That way you can make them have the same dimensions in world space. Which range is "normal" size? That's for you to decide. Because your projection matrix is then used to control the overall scaling factor between world space and screen space. So 100 world-space units can be huge or tiny, depending on what you want them to be in your game.

See also How to transform 2D world to screen coordinates OpenGL on Stackoverflow.
> 3 votes

---
Tags: opengl, coordinates
---


title: Adding text label to sprite

text:
# Question
Title: Adding text label to sprite
I'm completely new to Unity. I'm trying to create something similar to Scrabble.

I've simply got a tile as a sprite (red arrow).Firstly, I don't understand it being so small.. I'm trying to give the tile a label, "A", say. So, in my text input I have entered the "A". What am I missing?

If that would work, I could go into dynamically programming a bag of tiles.

# Answer
> 0 votes
This small step by step guid will give you at the end a small scrabble like hand with random letters and values. It is meant to be used with a canvas. The screenshots are containing the how it will look at the end of the guide, don't worry if there is sometimes a bit more listed.

First we need to define a Tile. Usually a scrabble tile can be broken down into three parts: background, letter and points.

1. First we add a canvas to our game scene.
2. Create an empty GameObject in the canvas. Unlike a normal GameObject, it should have the Rect Transform. Name it Basic Tile.
3. Under the this new Basic Tile, create another three GameObject, one for each background, letter and points. The order is important, later ones are drawn over earlier ones, if we have first a letter and than the background, it will hide the letter.
4. Select the Background Gameobject and assign an Image Component (Component -\> UI -\> Image). Give it your scrabble background tile. Set the transform to 0, 0, 0. As for width and height, you need to do some math. (Since this is most likely one of your first games, use the resolution of your target device to make it look nice. Canvas uses pixels, if your phone has for example 2280x1080 and you want to display a 6x6 board with maybe a hand below, your tiles can be around 100x100 to make it not too crowded.)
5. Select the letter GameObject, attach the TextMeshPro - Text component. Give it the same height/ width as your background, set the text to autosize and under text options to center and middle. This will place our letter always in the middle. Give it a good contrast color.  The first time you add a TextMeshPro component, you should get a popup asking for permission to import the relevent files.
6. Repeat step 5 for the points but make the size smaller. Once you are happy with the size of the letter, select the anchor present and move it to the top right corner with both pivot and anchor (shift + alt click)
7. We are creating a basic tile setting script.

```
public class TileScript: MonoBehaviour {

    public TextMeshProUGUI textLetter;
    public TextMeshProUGUI textPoints;

    public void InitTile(string letter, string points) {
        textLetter.text = letter;
        textPoints.text = points;
    }
}

```
8. Add this script to the Basic Tile GameObject, assign over the editor the two TextField by dragging the whole GameObject onto them. Once all is assigned, make a prefab out of everything.
9. As a bonus here is a small generation script. It will need some adjusting for real tile values. Create a new GameObject HandTiles under the canvas, give it a GridLayoutGroup and a width of how ever many tiles you want to display in your hand. Add some small spacing and attach the following script.

```
public class TileBag: MonoBehaviour {

    public GameObject basicTile;
    public GameObject handTileHolder;

    private void Start() {
        for (int i = 0; i <= 5; i++) {
            GameObject tempTile = Instantiate(basicTile, handTileHolder.transform);
            var letter = (char) Random.Range('A', 'Z');
            tempTile.GetComponent<TileScript>().InitTile(letter.ToString(), Random.Range(1, 8).ToString());
        }
    }
}

```

That's it. In your game you want the TileBag script somewhere in your game logic, tempTile should go to some variable which tiles are already generated. You should not read out the value from the tiles themself, your logic code should keep track which tile is placed where later on the board.

# Answer
> 0 votes
As the comments say, maybe your text object is too small relative to its parent. Maybe is the font size of your Text Mesh pro component, or the scale of the object (I can't say why it is scaled down). You can try to change the anchor presets on the Rect transform component of your text object, using `alt` \+ `shift`, and select the 'expand' option:

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


# Question
Title: Gradient from white to transparent instead shows as white to black
I need how to make a gradient that smoothly transitions from white to transparent for a 2D sprite via a URP shader graph.

It seems like I’m already set up and everything should work, but for some reason the sprite turns from light to black, and not transparent. Why might this happen?

# Answer
I realized that I did graph incorrectly. I recorded a tutorial for YouTube on how to make a transparent gradient for Unity. Here is the link:

https://www.youtube.com/watch?v=qKp1sWAEMUg&t=604s
> 0 votes

---
Tags: unity, unity-shader-graph
---


title: Modelling assets from within game

text:
# Question
Title: Modelling assets from within game
I'm helping to build a game using the Unreal engine. My friends are working on other parts of the game such as UI, AI, npcs, camera and movement interpolation, etc.

**My job** is to work out **the building system for the game**. I want to be clear that this game will be a **sandbox game** like Garry's Mod or Minecraft, but that is **overshadowed by its role as a 3D modelling software** that is meant to replace the combined forces of Civillo, Civil 3D & Revit. I want the **building system** to be extremely **advanced, but** also extremely **intuitive**, because the player doesn't pan or rotate around objects, rather they move around and look at them. The building system will be based off control lines, and the schematics that can be swept across those control lines can be customized within the game. I also want the world file to save as a dwg file + a player data file. ***What do I need to know to allow players to edit assets from within a game in the unreal engine?***

**I don't want** them to **upload assets** that are otherwise modeled in blender **or use any API's which depend on existing 3D modelling software** because that would rather defeat the point.

# Answer
> What do I need to know to allow players to edit assets from within a game in the unreal engine?

There is a whole lot you would need to learn for a feature like that.

1. How to use the Unreal Engine in general, because that's a foundation for each of the following steps.
2. How to build UIs, because you are probably going to need some tool palette.
3. How to create and change a procedural mesh at runtime.
4. How to detect mouse interactions in the game's viewport and associate them with a specific vertex, edge or surface of the procedural mesh the player is pointing at.
5. How to create a shader that highlights individual vertices, edges or surfaces of a 3d mesh, because you probably need some way to visualize what the player has selected.
6. How to change textures at runtime, because you are probably going to need a way to paint textures.
7. How to save mesh data and textures to a file. Either by implementing a standardized 3d model format of your choice or by inventing one of your own.
8. How to load mesh data and textures from those files.

This is really just scratching the surface, though. The tools you want to "replace the combined forces of" are sophisticated pieces of software that had probably a whole lot of professionals working on them for years. Replicating their whole feature-sets is probably not something you can do on your own over the course of a couple weekends.
> 1 votes

---
Tags: 3d-meshes, unreal, asset-creation
---


# Question
Title: I can't access 'My Assets' in the Project Manager Unity
I was following a tutorial on how to make a 2D Multiplayer Card Game in Unity where they were using the Mirror Networking tool.

I downloaded it from the Assets store, put in my username and password, then it opened the package manager in my Unity editor where I was prompted to sign in again. So I did that in my browser, then it said it was going to redirect me to the Unity Hub. When it redirected me there, nothing happened.

I just want to be able to access the 'My Assets' area - how do I do this?

# Answer
Update: I checked back in like 1 hour, now the "My Assets" page doesn't need my sign in? IDK why but I'm glad.
> 0 votes

---
Tags: unity, assets
---


# Question
Title: How do I come up with the stats of a weapon?
I am working on a game, where mosquito is one of the enemies. I'm trying to evaluate the stats of the Electric Racket (used to kill mosquito in real life)?

How can I come up with the stats for such a weapon?

# Answer
My approach to game design is to keep things as simple as possible, and then add complexity when it helps me to solve a specific design problem.

You didn't tell us much about your game. Only that it contains mosquitoes, an electric racket and that the goal of the player is to kill the mosquitoes using the electric racket. But you didn't tell us anything about how the player accomplishes that. Is it a game of strategy or skill? Real-time or turn-based? I'll have to make a ton of assumptions in order to answer your question, and most of them are probably wrong.

But in most genres, the most simple solution would be as follows. When the player hits a mosquito with the racket, the mosquito dies. There are no hit points or damage formulas, just a binary dead/alive state. There are also no restrictions on how often the player can use the racket. Each click/tab in the correct location kills the mosquitoes. **At this point of the game's development there is no need for stats**.

Depending on your desired game design goals, that might or might not be sufficient. Perhaps you are fine with that gameplay loop. Or perhaps you aren't. Perhaps you don't want the mosquitoes to always die, but rather that they have a chance to survive. Or perhaps they only get injured and need multiple hits. Perhaps you want to limit the speed with which the player can swing their racket.

Perhaps you want to add more weapons with different attributes: Affected area, attack frequency, deadliness. You probably either want those weapons to be balanced against each other, so the player can pick one based on personal preference. Or you want some progression system where the player advances from less to more effective weapons. In either case, you need some way to make weapons better or worse in certain aspects. **This is the point where stats come into play**.

* If you want weapons to affect different areas, then the shape and size of their hurtbox becomes a stat.
* If you want weapons to deal more or less damage, their damage value becomes a stat.
* If you want weapons to have a lower or higher attack frequency, then their cooldown delay becomes a stat.

A good way to design the values for stats like that is to keep them relative to the stat of the most basic weapon. If you want the electric racket to be the "default weapon", then you would use its stats as a baseline and make the stats of all other weapons lower or higher depending on how they should perform relative to the electric racket. How much lower or higher? Finding that out is the fun part! Because the best way to figure it out is by repeatedly playing your game and adjusting the values until you figured out ideal values.
> 3 votes

---
Tags: game-design
---


# Question
Title: Direct3D 11: Changing fullscreen resolution does not work
In my application I can switch back and forth between windowed and fullscreen mode using IDXGISwapChain::SetFullscreenState. When the WM\_SIZE is handled, IDXGISwapChain::ResizeBuffers is called in response. This works fine and when entering fullscreen mode DXGI chooses the desktop resolution.

The problem comes when I'm trying to change resolution while remaining in fullscreen. I try to change resolution by using IDXGISwapChain::ResizeTarget. The mode description I'm trying to switch to is aquired by using IDXGIOutput::GetDisplayModeList, so it should be valid. When doing the resize I get the usual blinking that happens when I enter fullscreen, but nothing has changed; the resolution is still the same and there's no WM\_SIZE message being generated like in Choosing the DXGI Output and Size.

DXGI best practices also contains alot of information but it didn't help me.

I am using the DXGI\_SWAP\_CHAIN\_FLAG\_ALLOW\_MODE\_SWITCH flag when creating the swap chain and I have also tried using IDXGIFactory::MakeWindowAssociation with the DXGI\_MWA\_NO\_WINDOW\_CHANGES and DXGI\_MWA\_NO\_ALT\_ENTER flags to no avail.

If I hardcode the swap chain to be created in fullscreen mode using a low resolution I can see the mouse cursor being jagged and larger, and this visual difference is not present when changing resolution.

Am I possibly getting the concepts wrong here? Am I supposed to get a WM\_SIZE message after calling ResizeTarget? How are the display mode and back buffer related? I know that when the front buffer size is changed the back buffer should be resized to match in order to do flips instead of blits according to the links, which is why it's recommended to do the resize when the application gets the WM\_SIZE message.

In a few of the similar questions I've found there are discussions about it maybe being a bug, but they all just died out with no final answer.

**EDIT:** I just tried to manually call OnResize (my method actually calling ResizeBuffers and so forth) after I attempt to change resolution and the following warning shows up in the debugger (not visible before):

> DXGI WARNING: IDXGISwapChain::Present: Fullscreen presentation inefficiencies incurred due to application not using IDXGISwapChain::ResizeBuffers appropriately, specifying a DXGI\_MODE\_DESC not available in IDXGIOutput::GetDisplayModeList, or not using DXGI\_SWAP\_CHAIN\_FLAG\_ALLOW\_MODE\_SWITCH.DXGI\_SWAP\_CHAIN\_DESC::BufferDesc = { 800, 600, { 60, 1 }, R8G8B8A8\_UNORM\_SRGB, 0, 0 }; DXGI\_SWAP\_CHAIN\_DESC::SampleDesc = { 1, 0 }; DXGI\_SWAP\_CHAIN\_DESC::Flags = 0; \[ MISCELLANEOUS WARNING #98: \]

The new resolution (800x600) seems to be set, but note that the Flags member is 0. Shouldn't it be 0x2? Could that be the reason the resolution doesn't have any effect? The flag is set in the swap chain description right before the swap chain is created so I don't understand how it's changed to 0.

**EDIT 2:** In a tiny remark at the bottom of the DXGI\_SWAP\_CHAIN\_FLAG documentation it says that ResizeBuffers can reset or change the flags. I took a look at my code and there it was: flag was set to zero (reading my book I must have accepted it as reusing the old flag or something). I changed it to allow mode switch and voilá, resolution changed and I got my WM\_SIZE. I did however get a couple of warnings about presentation inefficiencies but that was expected, and I have plans on how to fix those.

# Answer
If anyone else stumbles across this problem:

For me, the underlying problem was that the swap chain flag was reset even though I explicitly set the DXGI\_SWAP\_CHAIN\_FLAG\_ALLOW\_MODE\_SWITCH when creating the swap chain. It turns out that IDXGISwapChain::ResizeBuffers is able to reset or change the swap chain flags. I used a value of zero (probably thinking that it would not alter anything) which disabled mode change. Changing it to allow mode switches resulted in IDXGISwapChain::ResizeTarget properly switching display mode and generating a WM\_SIZE message.

> Am I possibly getting the concepts wrong here? Am I supposed to get a WM\_SIZE message after calling ResizeTarget?

Yes, ResizeTarget does generate a WM\_SIZE message (even if you're remaining in fullscreen).

(If you have any problem regarding DXGI you really should follow the links of the original post; they're stuffed with good information)
> 3 votes

# Answer
I am not sure why. But one more thing I've noticed is that if you want to switch to a fixed resolution after switching to full screen mode, you must first create the swapchain with **width** and **height** set to the desktop resolution **OR** create the swapchain with any width and height and then before calling `SetFullScreenState`, call `ResizeTarget` with the width and height set to the **default desktop resolution** (mostly for laptops, it's 1920x1080).

Now you can call `ResizeTarget` at any other point during your program to switch it to another resolution. I am not sure why it's like this, but it's something I observed and the only way I could perform this operation without starting out with a fullscreen swapchain.

If you start the swapchain with some other resolution, and when u set a particular resolution later on, it doesn't choose that resolution and chooses something else, or worse, just shows a blank screen.
> 0 votes

---
Tags: directx, resolution
---


# Question
Title: Object::cast_to in godot still casts even when the cast is invalid
I have a class for a projectile defined like this:

```
namespace godot
{

class Projectile : public RigidBody2D
{
    // Godot structure
private:
    GDCLASS(Projectile, RigidBody2D);

public:
    virtual void _physics_process(double delta) override;

    Projectile();
    ~Projectile();

};
}

```

Then I have a class for anything that can be shot:

```
class ShootableObject : public RigidBody2D
{
    // Godot structure
private:
    GDCLASS(ShootableObject, RigidBody2D);

public:
    virtual bool receiveDamage(double damage);

    ShootableObject();
    ~ShootableObject();

};

```

This is how I register them with the engine:

```
#include "Projectile.h"
#include "ShootableObject.h"

void initialize_example_module(godot::ModuleInitializationLevel p_level)
{
    if (p_level != godot::MODULE_INITIALIZATION_LEVEL_SCENE)
    {
        return;
    }
    godot::ClassDB::register_class<godot::Projectile>();
    godot::ClassDB::register_class<godot::ShootableObject>();
}

```

Then for collisions, I do this in the projectile class:

```
void Projectile::_physics_process(double delta)
{
  TypedArray<Node2D> colliders = get_colliding_bodies();
  bool hit = false;
  for (int i=0; i<colliders.size(); ++i)
  {
    Object* o = colliders[i];

    if (PhysicsBody2D* body = Object::cast_to<PhysicsBody2D>(o))
    {
      if (ShootableObject* shootable = Object::cast_to<ShootableObject>(body))
      {
        if(shootable->is_inside_tree())
          shootable->receiveDamage(props.damage);
      }
      hit = true;
    }
  }

  if (hit)
  {
    queue_free();
  }
}

```

The problem is, the `cast_to` always returns a pointer, even if two projectiles hit each other. That subsequently causes crash when trying to call `receiveDamage` on something that is not `ShootableObject`.

I can avoid the issue by doing this, but that's just plain stupid:

```
        if (body->get_class() != "ShootableObject")
        {
          return;
        }

```

Why is this happening? I tried to enable RTTI in my build in case there was a problem with that (shouldn't be) and that did not help. Is there something wrong with those class definitions?

# Answer
> 0 votes
This was a bug that was still occurring in Godot 4.0 (I tested it a few months ago) and is no longer occurring in Godot 4.1.

---
Tags: c++, godot
---


# Question
Title: How do I use these Unity math functions in Godot C#?
Here's a list of math functions I'm having trouble finding a direct function match for in Godot C#:

```
math.rcp() //get reciprocal of a float
//Then there's swizzle operations like:
float4 point;
float4 newpoint = point.yzwx;

```

There's also all sorts of other vector operations I can't find the equivalent for like:

```
float3 point;
math.abs(point);
math.exp(point);

```

Also I need certain special vector types like:

```
uint3 point //Is like an unsigned int vec3

```

Also in this code that I'm converting it adds a float to a float3 and I'm not even sure what the semantics are for that.

```
float3 add
add * 0.6f + 0.5f;

```

This is the code I'm trying to convert https://github.com/aras-p/UnityGaussianSplatting/blob/main/package/Runtime/GaussianUtils.cs I've been able to reproduce all of the functions with constructors and changing rcp to 1.0f/x, but I don't know what the memory allocations will do to the performance. These are my questions, thanks.

# Answer
The code in the question comes from Unity.Mathematics.

This is a relatively independent package that does not depend much on other parts of Unity. So we can simply refer to the source code to make a version for godot c#.

Source code of Unity.Mathematics

> math.rcp(); math.abs(point); math.exp(point);

They are all in math.cs.

> float4 point;

It's in float4.gen.cs.

> float4 newpoint = point.yzwx;

They created different versions of swizzles using code generation, e.g.

```
/// <summary>Swizzles the vector.</summary>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public float4 yzwx
{
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    get { return new float4(y, z, w, x); }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    set { y = value.x; z = value.y; w = value.z; x = value.w; }
}

```

> add * 0.6f + 0.5f;

They use operator overloading to implement various operations between float4 and float, e.g.

```
/// <summary>Returns the result of a componentwise addition operation on a float value and a float4 vector.</summary>
/// <param name="lhs">Left hand side float to use to compute componentwise addition.</param>
/// <param name="rhs">Right hand side float4 to use to compute componentwise addition.</param>
/// <returns>float4 result of the componentwise addition.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float4 operator + (float lhs, float4 rhs) { return new float4 (lhs + rhs.x, lhs + rhs.y, lhs + rhs.z, lhs + rhs.w); }

```

Anyway, translating Unity code to Godot C# is not a simple API switch. Depending on the situation, you can implement a method yourself or create a replacement for a package yourself. It's a lot easier when you have a ready-made package as a reference.

P.S. LICENSE of Unity package source code
> 2 votes

# Answer
> math.rcp() //get reciprocal of a float

As far as I know godot has no ready-made `rpc` method. All mathematical methods of godot are placed in globalscope. You can check if a method is implemented.

> Vector4 newpoint = point.yzwx;

Pretty sure this swizzle syntax doesn't come from godot or unity or c#. It comes from a shading language.

> math.abs(point);

`abs` is implemented as a member function of vector, see class\_vector2:

```
var absPoint = point.Abs();

```

> math.exp(point);

Exp(float) returns e raised to the specified power. It does not accept a vector parameter. This is also implemented in globalscope.

> uint3 point //Is like an unsigned int vec3

See c\_sharp\_variant. Here are Vector2I, Vector3I and Vector4I.

> add * 0.6f + 0.5f;

Pretty sure this code comes from a shading language too. The OpenGL Shading Language specification says:

> One operand is a scalar, and the other is a vector or matrix. In this case, the scalar operation is applied independently to each component of the vector or matrix, resulting in the same size vector or matrix.

Where Godot is lacking convenience methods, you can build your own. For instance, a quick search brings up the Unity docs for `rcp` which says that when `n` is a vector the result is a componentwise reciprocal. The reciprocal of `n` is `1.0/n`. Applying that to a `Vector2` would give you something like:

```
public static Vector2 rcp(Vector2 v)
{
   return new Vector3(1.0/v.x, 1.0/v.y);
}

```
> 2 votes

---
Tags: unity, mathematics, vector, godot, linear-algebra
---


# Question
Title: How to use key bindings in Godot from C++ extension code?
I have created a simple C++ "game" in godot. Lacking any good documentation, I based my work off examples on the internet, and for input I have this:

```
    const Input* i = Input::get_singleton();

    double delta_v = 0;
    if (i->is_action_pressed("ui_up"))
        delta_v += acceleration * delta;
    if (i->is_action_pressed("ui_down"))
        delta_v -= acceleration * delta;
    if (i->is_action_pressed("ui_left"))
        angular_velocity -= angular_acceleration * delta;
    if (i->is_action_pressed("ui_right"))
        angular_velocity += angular_acceleration * delta;

```

Based on that, I wanted to add a new action triggered by space. So I tried this:

```
    const Input* i = Input::get_singleton();
    if (i->is_action_pressed("game_shoot"))
    {

    }

```

I then added this action in the project key mapping:

But I am getting an error:

```
The InputMap action "game_shoot" doesn't exist.

```

Curiously, it works from a script like this:

```
func _input(event):
    if event.is_action_pressed("game_shoot"):
        print("game_shoot occurred!")

```

# Answer
> 1 votes
I finally figured this out. There is a method on the `InputMap` singleton. You probably should call this only once.

```
    InputMap* map = InputMap::get_singleton();
    map->load_from_project_settings();

```

---
Tags: c++, godot
---


# Question
Title: Weapon flips upside down when aiming to the left
When the player turns to the left, the texture of the weapon turns upside down. How can I solve this?

**Shooting Script**

```
public class Weapon : MonoBehaviour
{
    [SerializeField] private float _offset;
    [SerializeField] private GameObject _prefabBullet;
    [SerializeField] private Transform _shootPoint;
    [SerializeField] private PlayerMove _playerMove;

    public void Shoot()
    {
        Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        float rotateZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0f, 0f, rotateZ);
        Instantiate(_prefabBullet, _shootPoint.position, _shootPoint.rotation);
    }
}

```

**Movement script (only method here)**

```
private void Flip()
{
    // Switch the way the player is labelled as facing.
    m_FacingRight = !m_FacingRight;

    // Multiply the player's x local scale by -1.
    Vector3 theScale = transform.localScale;
    theScale.x *= -1;
    transform.localScale = theScale;
    //transform.Rotate (0f, 180f, 0f);
}

```

# Answer
> 0 votes
You may want to try doing the calculation in the parent's coordinate space instead, so it correctly flips when the parent does.

```
public void Shoot()
{
    // Get offset from gun to target, expressed in parent coordinate space.
    Vector3 worldTarget = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Vector3 localTarget = transform.parent.InverseTransformPoint(worldTarget);
    Vector3 localDifference = localTarget - transform.localPosition;

    // Take the perpendicular to this vector.
    Vector3 perp = new Vector3(localDifference.x, -localDifference.y, 0);

    // Aim the sprite so its up vector points at that perpendicular
    // (so its right vector points toward the target).
    transform.localRotation = Quaternion.LookRotation(Vector3.forward, perp);

    // Spawn bullet.
    Instantiate(_prefabBullet, _shootPoint.position, _shootPoint.rotation);
}

```

I've also shown a trick to avoid doing the trigonometry manually. If the gun's "right" vector is meant to aim in the direction `localDifference`, then its "up" vector will point toward the perpendicular direction `perp`. We can construct a quaternion that points the up vector that way while keeping the forward vector pointing into the screen (so the sprite faces the camera), and assign that to the `localRotation` property without having to do any angle math or radian/degree conversions ourselves.

---
Tags: unity, c#, 2d, rotation, sprites
---


# Question
Title: How do I create a localtoworldmatrix and worldtolocalmatrix in Godot?
From what I can tell Godot uses Projection for 4x4 matrixes, but I see no way to generate a localtoworldmatrix from a given transform in Godot, how do I do this?

# Answer
> 4 votes
In Godot a `Transform3D` has no concept of local or world. They are transformations between spaces, and what those spaces are depend on how you use them.

For a concept of local or world space, we would have a `Node3D`. They expose two `Transform3D`:

* `Transform`: converts from local space to parent space (i.e. local space of the parent `Node3D`).
* `GlobalTransform`: converts from local space to world space.

Thus, if you want to convert a `Vector3` from local space of a `Node3D` to global space (world coordinates), you can multiply like this: `node.GlobalTransform * vector`.

For the opposite operation (global space to local space) you can get the inverse of the transform: `node.GlobalTransform.AffineInverse() * vector`.

However, we rarely do it like that, because `Node3D` has short hands for those operations: `to_global` and `to_local`.

So, if you have a `Camera3D` and you want to convert a `Vector3` from its local space to world space, you do this: `cam.to_global(vector)`.

---
Tags: unity, matrix, transformation, godot, projection-matrix
---


# Question
Title: How do I add a function to the sequence of functions which runs pre camera culling in Godot?
In unity you can do:

```
Camera.onPreCull += OnPreCullCamera;
void OnPreCullCamera(Camera3D cam){
//...
}

```

But in Godot I don't know what the equivalent is. How do you add a function to the sequence which takes place before culling the camera. Thanks.

# Answer
> 2 votes
I don't think there is an equivalent, nor understand why you need it (I would expect that you can work in `_Process`). The closest I can think of is the `frame_pre_draw` signal of `RenderingServer`.

**Addendum**: You can get the `Viewport` inside of which a `Node` is with `GetViewport()` and get the `Camera3D` of said `Viewport` like this `GetViewport().GetCamera3D()`.

---
Tags: unity, camera, godot, culling, camera3d
---


title: Sprite Animation in Pygame Zero

text:
# Question
Title: Sprite Animation in Pygame Zero
How do I use a sprite sheet in pygame zero? The height of the images are 32, width is 25

# Answer
> 1 votes
As you've probably discovered, Pygame Zero doesn't have direct support for spritesheets. If you want to programmatically extract the desired sprites from the sheet at run time you'll need to use python code to do that. There's spritesheet code on the Pygame wiki.

Alternatively, you can use some other app to extract the sprites to individuals files for Pygame Zero to use. A web search for "spritesheet extractor" brings up a number of online options. You could also use most any image editing capable software (Photoshop, Gimp, Krite, Paint.net, etc) to manually extract the desired sprites.

---
Tags: animation, python, pygame, spritesheet
---


title: Protect authentication token in memory

text:
# Question
Title: Protect authentication token in memory
## Scenario

The game has leaderboards for the score at the end of a level.

Assume strong self-signed SSL encryption is used when communicating between the game client and server, and a secure handshake is established for giving the game client user the authentication token for future requests. The authentication token is used so that a handshake does not have to be established upon every single request.

## Question

How do you prevent the user from extracting the authentication token from memory and fabricating a fake score request to the game server?

I am assuming that if they know how to extract the token from memory then they would know how to decompile the game client; allowing them to figure out how to send requests and understand obfuscation measures.

# Answer
You cannot. Any attempt to do this will fail against a sufficiently determined adversary.

Worse, they don't even *need* to sniff the authentication token out of memory. They can simply hack the code in the game client that computes a score and make it produce any value they like, then allow the client's normal handshaking and reporting mechanisms deliver this tampered payload to your server, authentically signed and everything.

You can't stop this by challenging the client to compute a checksum of its own code or similar to check if it's been modified: the attacker can simply hack the code that performs the checksum so that it does it against an unmodified copy of the executable instead of itself. Or they can inject the false score value *into* the right spot in memory using another process.

“The client is in the hands of the enemy” — any capability you code into the client, you have gifted to every sufficiently motivated hacker or cheater who wants to exploit your game. The best you can do is keep updating frequently, hoping the time it takes hackers to exploit the new version frustrates them more than the repeated need to download and install updates (and possible bugs that come with them) frustrates your legitimate players.

The only way to protect the legitimacy of reported scores is server-side validation, where as the game is in progress the client reports data about the play, and the server uses those play traces to either compute the score itself, or validate that the reported score is consistent with the data. Even this is still vulnerable to a hacked client coaxed into reporting super-humanly optimal — but still *possible* — play. To frustrate that, see "how to prevent automation-type cheating"
> 2 votes

# Answer
If the code runs on a user-controlled device, a sufficiently clever and determined user will eventually be able to emulate and/or impersonate your application in every regard.

Regarding your comment here:

> This really only leaves one option if you want to maintain minimal server costs, which is to make it as annoying/frustrating as possible for dedicated hackers to hopefully minimize it.

Unfortunately no matter what you do, it's really not that hard for people who know what they're doing to compromise your client.

Ultimately, if you're doing the check client-side, *somewhere* in your code will be a conditional that says `if(passes validation) {do legitimate thing} else {do other thing}`.

All they need to do is find that branch instruction and toggle (reverse) it.

(Or if you're offloading server-side, there will be a "package results for submission" method that can be patched so it builds a false payload before getting it signed).

Neither of those really require much knowledge of the codebase, nor source code/debug symbols...

It's possible with a debugger and some patience alone, but now there are tools to run multiple instances (virtually) and fuzz branches/memory values to get a desired outcome.

This is basically what all the DRM in AAA games is trying to guard against (and why it always fails... They're not trying for long-term security, they consider delaying hackers by 60 days to be a big win).

It's also why all the competitive online games always do all the processing that can impact scoring server-side... It's the only trusted environment.
> 1 votes

---
Tags: client-server, authentication
---


# Question
Title: How can I help my unpaid 2D and 3D artists improve their portfolio?
I'm part of a 20 people team working on a game for free but we've got intentions of starting a company soon.

At the moment, not even the prototype is finished, but we've got 6 artists, half 2D and half 3D producing assets for us, what's happening is that the artists give feedback that it's hard to stick around since they're not paid (fair) and they can't really use the stuff they produce for their portfolio.

* The 2D artists seem to be bothered by the fact that sketch work isn't good enough for their portfolio, and most concept art they're doing isn't fully explored because as soon as the directors are happy with it they're asked to move to another piece.
* The 3D artists seem to be bothered by the fact that their 3d models can't be published on any store or market, as it would potentially harm the game in the long run.

Not having a lot of experience with artists, how can we go about and help them in this regard?

# Answer
Given that artists need time to improve the quality of their assets. And given that they cannot publish assets related to game, then they need time to work on assets that are not for the game. Which suggests that to actively help them improve their portfolio you could:

* Give them random prompts on what to work on, so they are not linked to the game.
* Set apart some limited time from the project for this.

For the prompts you could pick nouns at random. Or if you want to get them involved, you could have them submit possible prompts, and at the start of the allotted time pick prompts at random.

Whatever they do, let them add to their portfolios on their own discretion. Be aware that this might also result in new ideas, either for your game or other projects. Yet, in the spirit of helping them improve their portfolio, resist taking any of the resulting assets for the game (instead you can task them to use them as reference for something for the game, but it would be a different asset).
> -5 votes

# Answer
You got to find a way to pay your artists.

Currently they don't really get anything out of the work on your project. Even if your project *would* demand artwork on a level of polishing that's good enough to use as a portfolio piece, the 2d artists could just create those on their own without being connected to your project. Even if your project *would* allow 3d artists to sell their work on asset stores and keep the money, they could probably make more money if they created assets that are in demand for a general audience rather than creating the assets your project needs.

So there is really no good, objective reason why an artist would stay connected to your project at all.

So how could you pay them?

If you don't have any funds yet, then you can only pay them with the promise of funds in the future. For example:

* By making a contract that you owe them $x per hour/artwork, but to be paid at a later date when funds are available.
* By giving them equity in the soon-to-be founded company in exchange for their work.

Both of these arrangements are still a gamble for the artists, because there is a high chance that they won't ever get paid for their work. You might never be able to secure a source of funding that covers your outstanding artist fees. The company might be bankrupt before it made a dime. You might succumb to evil and run away with all the money you promised to pay to the artists. Not to mention that artists require food and housing, so future promises might be useless when it comes to covering their immediate financial needs. So if I would be one of your artists, I would ditch you as soon as I get an opportunity from someone who is able to pay me ***now*** instead of "maybe some time in the future". But at least it's better than nothing.
> 24 votes

# Answer
I'll skip the mandatory part talking about payment. I get it. I've worked on a game for free for years because it's a passion. I assume the same is true for these people as well, to an extent, but they want to have something to show for it, right?

With that said, there's three steps in my recommended approach here.

1. Convince the directors to ease off of the concept artists. It sounds like the workflow instituted by the directors is not standard to the concept art industry, and fixing the first issue is simple enough. Just let the 2D artists explore their concepts in a way that's suitable for their portfolio. This will (maybe) reduce their output and maybe upset the directors, but it's better than losing the artists entirely. Plus, the explored concepts might be better than the directors even expected.
2. Meet with the whole team and write up a basic agreement for how pay *will* be distributed once you have a company and have released the game. This is to cover the blue sky, flowers and butterflies ideal scenario. This should include minimum payment values for each contributor, like a usual agreement of this sort would. It's never fun to be 'that guy', but it would be important in this step to emphasize the highly likely possibility of the game never seeing the light of day or only ever making a couple bucks. It's very unlikely for any game made in this sort of environment (or almost any environment, really) to become a 'hit', if it is ever finished in the first place. This is important because it leads into Step 3.
3. Now, down to the stuff you probably don't want to hear, but will solve your problem. In that agreement you just made, *establish a deadline.* It could be two years, or maybe even five years. The terms are simple: when the deadline expires, if the game is not released or not profitable enough to pay your artists, they're free to publish their assets to stores or marketplaces to cover their losses.

Hopefully it should be relatively easy to see how these three actions allow your artists to have some guaranteed amount of value gained by working on your project despite the lack of payment.
> 17 votes

# Answer
It sounds like your root problem is wanting to keep your team members on board.

As with all volunteer-based projects, it's important to be mindful of the fact that *volunteers come and go*. This is something that should be expected and planned around. It can be affected to some degree, but at the end of the day, volunteers are going to drop out whenever the push from external factors (e.g. other projects in their lives) exceed the pull from their interest in the project.

The goal therefore isn't necessarily to make the work better for your artists' portfolios, but rather to make the project more appealing to them. Play into their passion for the project. They will still leave eventually, but a hobby project will still around longer if it's *fun* than if it's *work*.

Making the project more appealing to your volunteers could be done in many ways:

* Make the project less work-like by allowing artists to *focus on the aspects they have passion for*, instead of deciding their tasks for them. The artists are there because they want to, and if they are forced to do tasks they don't enjoy, - or end tasks before they reach the enjoyable parts - then they have little incentive to stick around.
* Encourage your volunteers to explore their skillset. The tasks a project needs to progress often center around the same things - e.g. drawing in the same style, or modelling the same type of characters - and quickly become chores. If you can encourage *varied tasks*, either by changing the direction of the game or by giving your volunteers time, space and encouragement to play around, it will take far longer for your volunteers to grow tired of them.
* Build a following, for example by developing in the open, having a noteworthy product and playing into social media. This can give volunteers motivation to continue working on the project, and can also provide a reasonable source of new volunteers when existing ones inevitably drop out.
* As mentioned in other comments, *pay your artists*. Convert the project from a volunteer-based project to an employee-based project, and it'll no longer be competing with other free-time activities. Employees still come and go, but at a far slower rate than volunteers.

Regardless of how you approach it however, it is important to be mindful of the fact that people leaving is a fact of life for passion projects.
> 4 votes

---
Tags: 2d, 3d, teamwork, portfolio
---


title: Audio won't pause in coroutine

text:
# Question
Title: Audio won't pause in coroutine
I am making a system where I have one long audio clip made up of voice lines which I want to be able to play one after the other with a variable pause in between.

I press the space key to start the clip, and I want it to pause after a set time and then I will press the enter key to start the next line(s).

I am able to get the audio to pause inside `Update()` with `AudioSource.Pause();` but for some reason it will not work inside the coroutine I have set to pause it after a number of seconds.

Since I do not want to have to time the pauses myself, how can I achieve this? The debug messages inside the `SoundWaiter()` function are all printing, but the audio is not being paused.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SoundTracker : MonoBehaviour
{
    public AudioSource soundFX;
    public bool pausing = false;
    public int count = 0;

    // Start is called before the first frame update
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Return))
        {
            pausing = !pausing;
        }

        if(pausing)
        {
            // This works, but I don't want to have to time the pauses myself
            //soundFX.Pause();
        }

        if (!pausing)
        {
            soundFX.UnPause();
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (count == 0)
            {
                soundFX.Play();
                StartCoroutine(SoundWaiter(10));
            }
            //if (count == 1)
            //{
                //soundFX.UnPause();
                //StartCoroutine(SoundWaiter(5));
            //}
            //if (count == 2)
            //{
                //soundFX.UnPause();
                //StartCoroutine(SoundWaiter(12));
            //}
            //count = count + 1;
        }
    }
    IEnumerator SoundWaiter(float duration)
    {
        Debug.Log("In waiter...");
        yield return new WaitForSeconds(duration);
        Debug.Log("Pausing audio...");
        soundFX.Pause();
        Debug.Log("Paused audio.");
    }
}
```

# Answer
> 3 votes
Okay, I figured out the issue. It is pausing the audio, but since I left `soundFX.UnPause();` inside the `if (!pausing)` block inside `Update()`, right after it pauses it will be unpaused by `Update()`.

---
Tags: unity, c#, audio, coroutines
---


# Question
Title: Ensure a path always exists between moving objects
I am working on a small non-discrete game where monster are coming towards player in random direction, sort of the very simple asteroid shooter game.

Monster behaviour is as follows:

* they spawn out of screen
* have a final direction
* have a final velocity
* moves in a continuous (non-discrete) way
* they do not stop for any reason nor do they collide together

> Note that all of these points can definitely be changed if if might help tackle the issue.

It kind of works, but I sometimes face a situation where player is doomed: monsters are popping in such a way that it is impossible for player to find a way out.

I would like to get rid of this frustration by, upon generating a new monster, ensuring there will always be a way out for the player. Point is that it does not, to me, looks like an simple static pathfinding-like problem, since:

* I just have to make sure a solution exist (maybe easier than finding one ?)
* Objects are moving
* Objects and player can collide

> Note: I am not looking for any type of cooked solution, just some references to existing algorithms, implementations,... to look into by myself.

I understand this fairly looks like collision prediction, but what I am looking for is a solution in which a path exists without such collision, which might be a slightly different problem, at least new developers in the domain such as myself...

> ***edit:*** Generating monsters in a random-like direction seems OK to me, as long as it does not feel like the pattern is "static" and they all can be avoided by following always that same pattern.

# Answer
> Note: I am not looking for any type of cooked solution, just some references to existing algorithms, implementations,... to look into by myself.

A noteworthy algorithm here is Velocity\_obstacle.

Its evolved version algorithm `RVO(Reciprocal Velocity Obstacles)` and `ORCA(Optimal Reciprocal Collision Avoidance)` are standard solutions for dynamic group obstacle avoidance. In this particular case, only the player can move freely, so the simple original version will suffice.

When spawning a new monster:

1. For each all `Monster(B)`, Get a VO area about `Player(A)`. Combine all VO areas to get the velocity value space that the player can survive.
2. Randomly select a point in the value space as a prediction of the player's velocity. If the value space is empty, the player has no chance to survive at this time. This is due to improper operation of the player rather than the sudden appearance of monsters.
3. Randomly choose a position for the new monster.
4. For `Player(B)`, Get a VO area about `NewMonster(A)`. If the value space does is empty, return to step 3, else randomly select a point in the value space as the new monster's velocity. If you want to increase the pressure, choose a point closer to the VO area.
5. Expand the player's radius when calculating to increase error tolerance.
> 1 votes

---
Tags: collision-avoidance, collision-prediction
---


# Question
Title: Why does find_child not work during _ready, but looping over child nodes finds the child?
I have been trying to split a game object in half, starting with splitting the collision shape in half. I create two new clones of the split object, then give them a property to be assigned to the collision polygon. In the editor, the setup looks like this:

The health\_xxx are sprites to be changed based on how damaged it is. In code, I do this:

```
      // two paths created from the original shape
      std::array<PackedVector2Array*, 2> paths {&path1, &path2};

      for (const auto* path : paths)
      {
        ShootableObject* myCopy = (ShootableObject*)duplicate(DUPLICATE_SIGNALS & DUPLICATE_SCRIPTS);
        // this is the path to be assigned when the object is ready
        myCopy->collisionOverride = *path;
        get_parent()->add_child(myCopy);
      }

```

In `_ready`, I tried to do `find_child` and `Object::cast_to`, but that doesn't work. The following code works and demonstrates my problem:

```
  if (collisionOverride.size() > 0)
  {
    CollisionPolygon2D* collision = Object::cast_to<CollisionPolygon2D>(find_child("collision"));
    if (collision)
    {
      // never happens
      collision->set_polygon(collisionOverride);
    }
    else
    {
      UtilityFunctions::print("Cannot override collision, node not found! Trying alternative method");
      for (int i = 0; i < get_child_count(); ++i)
      {
        Node* child = get_child(i);
        if (child->get_name() != StringName("collision"))
        {
          continue;
        }
        if (collision = Object::cast_to<CollisionPolygon2D>(child))
        {
          // this works
          collision->set_polygon(collisionOverride);
          UtilityFunctions::print("Success.");
          break;
        }
      }
    }
  }

```

The output I get:

```
Cannot override collision, node not found! Trying alternative method
Success.

```

I just don't understand why do I have to reimplement `find_child` in this case. Even stranger is the fact that for nodes that exist from the start, this is not a problem.

I am using Godot 4.2.

# Answer
> 3 votes
find\_child docs say:

> Node find\_child ( String pattern, bool recursive=true, bool owned=true ) const
>
> ...
>
> If owned is true, this method only finds nodes who have an assigned owner. This is especially important for scenes instantiated through a script, because those scenes don't have an owner.

Creating clones sounds like spawning the nodes via script, so they don't have owners.

In your hierarchy, you don't need recursive either. When you don't need recursive, it's good to disable it because find\_child searches depth first.

So as Mangata said, use `find_child("collision", false, false)`.

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


# Question
Title: How to generate resource clusters on a 2d map like Factorio?
I am trying to add some ores on my map using Perlin noise. The problem is sometimes Perlin noise does not produce enough values above the threshold, causing the amount of one ore is much lesser than the others.

In Factorio they somehow managed to keep the amounts of each ore are within a certain range during map generation. How can I achieve a similar behavior?

Edit:

Right now I am using scale, octaves, persistence, lacunarity, offset and threshold to generate a Perlin noise map, then just checking if the value at a coordinate is within the range of the threshold, if yes, then mark the pixel at that position with a specific color.

Currently the results look like this:

The first problem is sometimes, for example, blue regions are super rare, like there are only 2 or 3 over the whole map. Another problem is there could be many unwanted little scatters around the map and I am unable to control them. How can I fix them?

PS: One type in a cell, binary presence and fixed quantity.

# Answer
> 3 votes
Here's one way to use noise to generate a one type in a cell, binary presence resource map.

The first step is to generate site locations for the resources. There's a variety of ways to do this. The specific methodology is a balance between what type of distribution you want, how performant the code needs to be and how much complexity you want to deal with. Point generation details are beyond the scope of what I'm going to cover in detail here. I often favor a Poisson disc distribution, but for the purposes of illustration, I'm using a filtered uniform random distribution - basically it's rand & I randomized a few times until I got something that wasn't too clumpy. If you want to know more about point generation, I suggest researching some of our other posts on the topic followed by posting your own questions if needed.

A key point to mention - this step is pivotal in getting the desired amount of resources. I'm going to demonstrate using the colors red, blue and yellow to indicate different resources and decided red is about 50% less common than yellow or blue.

After generating the site locations, the next step is to generate a Voronoi diagram. Here's an illustration showing the sites, and color coded regions of the Voronoi:

The next step is to build an intermediate layer that maps out the influence of each site. To do that, we select some radius \\$r\\$ and for each site, generate an area of influence with values of \\$1 - \frac{d}{r}\\$ where \\$d\\$ is the distance for the site. Visually, the influence map looks like this:

The next step is to generate the noise layer. As with point generation, I'm not going to go into a lot of details. But based on your comments concerning small single pixel areas of resource, I suggest using a rather smooth looking noise & keep in mind that it may take some trial and error to hone in on what you're looking for. Here's an image of the noise I used:

Both layers should have values from 0 to 1; if not, normalize your data. Then we combine the layers using the color burn operation:

* invert the noise layer
* divide by the influence layer
* invert the result

Mathematically, the value for each \\$x,y\\$ coordinate location is: $$1-\frac{1-n\_{x,y}}{i\_{x,y}}$$

Graphically we get this:

Again, the result should have values from 0 **to** 1. Applying a threshold function will convert the result to have values of 0 **or** 1. Mathematically, examine each coordinate location and if it's below the cutoff assign it a value 0; otherwise assign it a value of 1. This is another place where you can potentially tune the quantity of resources; the following animation shows how the resource area change as I adjust the threshold:

A more complex model might dynamically adjust the threshold to each resource type in order to more or less of a resource as needed. For simplicity, I applied the same threshold to all the resources. Here's the final result as a color coded map:

There's rarely a one size fits all solution to procedural generation. You will likely need to experiment to get results that work well for your specific game. For instance, if smoothing out your noise doesn't reduce the unwanted little scatters, you will need to add a post processing step to remove them. However, using the approach here, any small scatters should be near a much large concentration of the same resource, so you might find that it works for you as a feature. For instance if I use this noise:

I get this instead:

# Answer
> 2 votes
If you want "One type in a cell, binary presence and fixed quantity", then using a noise pattern is probably not the right tool for the job.

A far more straight-forward method would be to do this for every resource node you want to have in a cell:

1. Pick a random spot within the cell
2. Evaluate if the spot is suitable for placing this resource there, and if not, reroll until it is (up to a reasonable maximum amount of retries, so you don't end up in an infinite loop in cases where there aren't *any* suitable spots in the cell)
3. Place a resource region with the desired quantity there.

---
Tags: procedural-generation
---


# Question
Title: Can I delete UnitySetup .exe files from AppData Temp folder?
Can I safely delete the following Unity-related files in order to clear up space?

* %APPDATA%\Local\Temp\unityhub......\UnitySetup64-2022.3.7f1.exe
* %APPDATA%\Local\Temp\unityhub.......\UnitySetup64-2021.3.23f1.exe

# Answer
Anything in the temp folder should always be treated with the understanding that it may disappear at any given time. This means you should not store critical information that your program depends on in that directory.

In addition, this is the installer for the corresponding Unity version which is needed for just the installation. UnityHub can redownload them if you need to install a specific version again.

(Just because no critical needed information should be stored in temp, some programs still do so. But in this case, you are safe to delete those files)
> 2 votes

---
Tags: unity, windows, filesystem
---


# Question
Title: How to make a CharacterBody2D slide out of StaticBody2D instead of teleporting?
I am trying to replicate Mario Maker's On/Off switches in Godot 4.1.

In my current version, if the player got stuck inside the block after it was toggled on, the player just teleports out it. I know this is expected, but I wanted a smoother transition.

After looking it up, I found a video replicating the same feature in Godot, but the player, when stuck inside the block, slid out it, much more smoothly (see 0:33 in the video).

How can I replicate this smoother overlap resolution?

# Answer
> 2 votes
The key is to use `add_collision_exception_with` to prevent the physics system from resolving the collision. Then you're free to implement whatever movement you want!

I assume your block is a StaticBody2D. I would add an Area2D that matches the size of the StaticBody2D so you can detect objects overlapping the block. When you enable the switch to turn on collision:

1. `Area2D.get_overlapping_bodies` to find what's overlapping and store them.
2. For each of them, `add_collision_exception_with` to prevent collision response so they won't collide with the static body.
3. Push them smoothly out of the collision (extrapolate a point that's outside and lerp them there over time or move them away at a fixed speed).
4. When the Area2D gets `body_exited`, `remove_collision_exception_with` that body to collide with the block again.
5. When all bodies have been forced out, turn `monitoring` off on the Area2D since you no longer need to respond to bodies.
6. If the switch is hit again, turn `monitoring` back on the Area2D and repeat the process.

That might look like this (untested):

```
var push_speed := 3.0

var _pending_bodies

func _ready():
    $Area.body_exited.connect(_on_body_exited)

func enable_collision():
    _pending_bodies = $Area.get_overlapping_bodies()
    $StaticBody.disabled = false

    var needs_to_push := _pending_bodies.size() > 0
    $Area.monitoring = needs_to_push
    if needs_to_push:
        set_physics_process(true)
        for body in _pending_bodies:
            $StaticBody.add_collision_exception_with(body)

func disable_collision():
    $Area.monitoring = true
    $StaticBody.disabled = true

func _on_body_exited(body):
    _pending_bodies.erase(body)
    $StaticBody.remove_collision_exception_with(body)
    if _pending_bodies.size() == 0:
        set_physics_process(false)
        $Area.monitoring = false

func _physics_process(dt):
    for body in _pending_bodies:
        # May need to raycast to find an empty space to push them to. Or try a
        # few different ways to push them away.
        var away = (body.global_position - $StaticBody.global_position).normalized()
        body.move_and_collide(away * push_speed * dt)

```

---
Tags: collision-resolution, character, gdscript, godot-4
---


title: Unity VR Max File Size

text:
# Question
Title: Unity VR Max File Size
I have recently run into errors when building my Unity VR app for the Meta Quest 2 - and I wanted to check my understanding of something - from everything I've found it sounds like there is a max file size for an apk build of 2gb, and maybe the max theoretical is 4gb - but I am wondering if that is true?

Mainly because it seems mad to me! My Quest 2 GPU/CPU is perfectly capable of rendering and playing my 1.5gb scene in isolation, but when I add the menu and other scenes it becomes too big - so the answer would seem to be to scale back on the size of the level, texture optimisations,etc - but it seems crazy to me that that is enforcing a limit beyond the hardware? Ie - the GPU/CPU is capable of playing much more complex scenes that are going to look smaller and more rubbish because of an arbitrary max file size to a single file apk. It seems like limiting the hardware for no reason.

In addition - I am working for the Quest 2 - and have been reading articles on how the Quest 3 means apps are going to be bigger and it has all this fancy new hardware - but are they not going to be limited by the same 2 or 4gb limit?

I feel like I am missing something here - either that games can be bigger and there is a workaround I haven't found? Or maybe there is a hardware reason for this limit that I don't understand?

I feel like it would blow my mind if every app on the Quest store is less than 2gb?

Any help at understanding it or possible solutions would be much appreciated!

# Answer
The answer is in the VRC.Quest.Packaging.5 docs

> **Criteria**
>
> APK files must be less than 1 GB in size, but can be accompanied by multiple expansion files up to 4 GB each.

So yes, technically all of the apps are limited to 1 GB (and therefore less than the 2 GB limit you asked about). But it's possible to technically exceed that restriction by using expansion files.

The docs include links to Unity asset files to manage download size (OBB expansion files & required asset files).
> 2 votes

---
Tags: unity, virtual-reality, oculus, quests
---


# Question
Title: How does unity refer a to a normal when there are so many?
When an object collides with another object, does unity calculate the normal, or return it from the list of normals?

# Answer
> 1 votes
How Unity calculates the collision normals depends on the types of colliders involved.

It's worth noting that unity will offload all of this to a physics engine (primarily nVidia PhysX), so in a lot of cases it's not *actually* Unity doing the calculations.

That said, at a high level, there are 2 classes of collider/geometry...

#### Primitives

These are simple shapes (spheres, planes, capsules, boxes, etc)

Each combination of colliders will require a slightly different solution.

Eg If it's calculating the collision of 2 spheres, it's pretty trivial... PhysX knows the radius and center of each sphere. If the magnitude of the vector between them is equal to the sum of their radii, they're touching), and the normal of the collision can be calculated by looking at the sphere's velocities and doing a dot product.

A sphere and a plane involves calculating the distance from the center of the sphere to the nearest point on the plane and comparing to the sphere's radius, with the normal being perpendicular to the surface.

Each unique combination has a different mathematical solution.

As a rule, primitive-primitive collisions are relatively cheap (computationally).

(That's one reason Unity uses a capsule collider by default for the player controller).

#### Meshes + Height fields

For meshes, there are sub-categories...

##### Convex hulls

These are shapes with no overhangs/dips/hollows. You can draw a line between every pair of points on their surface and it will never leave the shape.

These are more complex to handle than primitives as it needs to compare collisions for many (but not all) faces.

(Obviously a mesh-mesh collision is worse than a mesh-primitive collision as there's multiple faces on each mesh to cross-compare)

Even so, there are optimisations to reduce the number of faces that need to be compared (beyond my ability to describe).

##### Concave meshes

Meshes with overhangs, holes, etc...

These are a real problem.

Unity *used* to handle dynamic concave collision meshes but dropped support when PhysX stopped supporting them (The recommendation is to use a number of convex hulls to build up a concave overall shape).

I *believe* that for concave hulls, all faces need to be checked every time, as there are no good universal optimisations that handle all the geometry edge-cases.

#### Further Reading

This page gives far more detail about how PhysX defines different types of colliders, and this page explains how collisions are handled

This one explains the Rigid Body object hierarchy.

# Answer
> 0 votes
I'm not a Unity dev, but let's work it out. Unity has some excellent documentation. More often than not, the things that you might need to follow up on are linked from the places you've first found them. So you don't need to repeatedly use their search bar , Google follow stuff, etc - once you're on the trail, it's usually just a matter of clicking through to the next thing.

A quick search for "Unity collision" (I actually had a typo & looked for "nity" instead of "Unity") brings up the Unity docs Collision & we'll start with Introduction to collision:

> ... On the first physics update where the collision is detected, the `OnCollisionEnter` function is called.

So now let's take a look at the docs for `OnCollisionEnter`. The description tells us its parameters are "The Collision data associated with this collision event." And further down, there's a couple of code samples including the following:

```
void OnCollisionEnter(Collision collision)
{
    foreach (ContactPoint contact in collision.contacts)
    {
        Debug.DrawRay(contact.point, contact.normal, Color.white);
    }
    if (collision.relativeVelocity.magnitude > 2)
        audioSource.Play();
}

```

Notice that the `foreach` loop is iterating over the contents of `collision.contacts`; And as it does so, the code is drawing some white rays that start at the point of contact and extending along the normal of the contact. So this is technically enough to infer an answer to your question, but as long as we're looking stuff up in the documentation, we can go a couple steps further to get a definitive answer.

We can go to the documentation for Collision and from there look up the documentation for its contacts property which states:

> Every contact contains a contact point, normal and the two colliders that collided (see `ContactPoint`). From inside `OnCollisionStay` or `OnCollisionEnter` you can always be sure that contacts has at least one element.

We've learned that a `Collision` contains a collection of `Contacts`, that each `Contact` has normal and that within the `OnCollisionStay` or `OnCollisionEnter` methods, you are guaranteed at least one contacts (and therefore at least one normal), but there may be more.

So you're not exactly getting a collection of normals directly, you're getting a collision, which has a collection of contacts and the contacts have normals for their respective points of impact.

---
Tags: collision-detection, normals, computational-geometry
---


# Question
Title: How to make the player feel like giving up?
I am planning a game that has a level that is a confusing and illogical maze, and I want to make the player feel like giving up, but not so intense that they want to quit the game. Also, I'm probably going to have some way to restart the level if they get too lost. Do you have any ideas of subtle level design that could discourage the player from continuing?

# Answer
> 30 votes
**Minor spoilers follow for Journey and Nier Automata.**

Both of these games include scenes where the player is meant to feel extremely discouraged. The way they both sell this in the game mechanics is by taking abilities away from the player and making it harder and harder to progress. The important trick they use is they don't apply this adversity all at once: they do it a little at a time, gradually, over the course of a whole level/zone.

In Journey, as you climb farther up the frozen mountain...

* your "voice" range shrinks, first a little, then a lot
* your character hunches down and moves slower through the heavy snow
* the music gets tense
* you have to get closer to your partner to recharge each other
* there are fewer recharge stations, so you can barely jump/fly
* frost starts to cover you, only thawing if you're touching your partner
* strong winds push you back
* the music gets foreboding
* your flight charge begins to deplete all on its own, even when you're not using it
* enemies tear your scarf (charge meter), decreasing your maximum charge
* your scarf starts to erode and wither all on its own
* the colour drains from the scene until it's nearly monochrome, in a depressing blue-grey palette
* your movement speed slows down even more
* the music gets shrill
* blowing snow makes it harder to see where you're going
* even touching your partner doesn't thaw you anymore
* you face an empty expanse with no landmarks, so you can't even tell if you're making progress and there's no respite in sight
* the music drops away entirely, sound is muffled
* your camera wobbles and your character falters, you can no longer steer them well
* your movement speed slows down so much that you're barely moving at all

The point is that these penalties don't arrive all at once, a cue players might take as "oh, this is the hard mode area, I just have to work within these constraints". Instead, every time the player begins to acclimate to their diminished abilities or harsher challenges, things get a little bit worse, and you never feel you've gotten a handle on it.

This exploits a bias in our subjective experience of reward/punishment:

(Diagram by Laurenrosenberger via Wikipedia, CC-BY-SA-4.0)

Larger rewards/punishments feel more impactful, but with diminishing returns: a penalty twice as large doesn't feel twice as bad. Most of the perceived pain/adversity comes from "I lost something *at all*", and the magnitude of that loss is secondary.

So, splitting a large penalty into a number of smaller setbacks spaced out in time lets the player feel each one individually. By repeatedly hitting the player with small losses, we keep them in the steep portion of the graph where they feel the adversity most intensely, even while the total size of all punishments added together is not that big (so the game doesn't become unplayable).

To use this in your game: look for things you can do that feel bad, then do the tiniest amount of them that's perceptible. Then keep doing it, over and over, with enough time in between for the next setback to be perceived as its own separate loss.

Be careful of overshooting here. As you can see in the graph, the "loss" side is a lot steeper than the "gain" side, a bias called "loss aversion" - we tend to feel the psychological pain of a loss or setback more keenly than the pleasure of a similarly-sized reward. So you probably don't have to punish as much as you think to create the desired feeling.

The player's time is often a good target: you'll notice a lot of the Journey examples reduce movement speed or range, or limiting access to faster modes the player had gotten accustomed to. Giving the character an occasional stumble, or trap they have to take a moment to pull themselves out of, all increase the sense of friction in doing anything, without killing off the player character and making them restart.

Even cosmetic changes, like altering the colour grading or vignette, or changing the character's animation to look uncomfortable or pained, can generate a powerful feeling from the player in sympathy. Nier Automata makes great use of purely visual changes to the user interface as the virus infects your character, and the display gets increasingly glitchy and information widgets become unreliable/unavailable. Sound and music changes can also powerfully sell a discouraging mood.

Something else these cosmetic effects do is help convey that there's an *intention* behind the player's mounting feeling of hopelessness here: it's not just that the game is buggy/unfair, it's trying to tell you a story about hardship. That clue hints to players that they should tough it out to see where the story goes, rather than just quit because the game got too hard. The mounting signs of adversity fill in for the sense of progress the player is being denied in the level design, telling them they're still getting *somewhere*, even if it's not closer to their goal.

Without knowing much about your game, I can't say much about what specific changes would be appropriate. But in terms of level design, some options are:

* more dead ends (you can script a level where the way forward is always the last corridor they try, no matter which order they try them in)
* loops, so the player feels they're going in circles (Labyrinth Zone in the original Sonic the Hedgehog has a nasty version of this)
* lack of landmarks, sowing doubts about whether they're making progress
* lack of guidance, so the player's less sure which way to go or whether they're getting closer or farther away

(You can make both these last two more noticeable by being generous with landmarking and signifiers of goal / proximity in earlier levels, so players get accustomed to it and miss it when it's gone)
* unreliable clues (say the player has a Geiger counter whose frequency of chirping indicates when they're getting closer - start randomizing it, so the player finds they can't rely on it anymore)
* terrain that's slow to cross, like waist-deep muck, or big stone blocks that need to be pushed out of the way - this is a good place to gradually crank up the slowness factor the deeper they get

Avoiding overshooting with this, where the player gets so frustrated they just quit, will be an exercise in playtesting.

# Answer
> 6 votes
I'd like to add Celeste to this as an example.

Some of the levels there can be brutal, but there is little to no death penalty and you're back where you were a moment ago. This way, you'll have to progress trough trial and error, and learning the mechanics on the way. In the extra levels, you may have to repeat a section so many times that it almost becomes a muscle memory. It can be hard, and in some times also frustrating, but it makes the satisfaction of reaching even just a little further already worth the climb.

The story also adds up to this, where it is about overcoming fears and obstacles.

The givaway here is that it is about dying often, but compensated with a quick respawn in each room.
On the other side: dying less often, but losing more progress is also frustrating, but I think that leads quicker to quitting the game.

# Answer
> 2 votes
This is a common feature of boss levels, but doesn’t necessarily have to be exclusive to them. Make the level ridiculously impossible with quick death for the player all but assured, with the ability for the player to try again over and over again to the point the player starts to think “this can’t be right; I have to be missing something”. And then they notice the key to overcoming the level (or at least surviving) that had been present through environmental cues but that they’d missed because the cues were subtle. Pleased at how smart they are and feeling accomplished the player continues the level. The level could still be difficult, even very difficult, but at least now the player knows it’s possible.

---
Tags: 2d, game-design, level-design, psychology
---