# Question
Title: What is the point of a "rebirth" mechanic in a game?
There are many (mini)games which revolve around the player collecting points to buy upgrades (think Cookie Clicker, ROBLOX simulator games, etc.). Most of these games have a mechanic called "rebirth", where the player can trade all of their points and items for bonuses and/or "rebirth" points. In some games, the player will have exclusive items or areas accessible to them when they get enough rebirths. What exactly does this mechanic contribute to a game, and is it necessary in order to make this type of game good?

# Answer
> 23 votes
Like any other scoring mechanic, there's an element of social prestige. It takes some amount of skill to reach the end of the game, and doing it multiple times shows that you have a lot of skill. See also the prestige mechanic in Call of Duty.

Rebirth mechanics also help with replayability - eventually you run out of ways to optimize your production, but that means you can't scratch the "make numbers go up faster" itch anymore. Players could start a new game themselves, but losing that progress goes counter to the primary reward mechanism of the genre.

Mechanics like this won't necessarily make your game good or bad. That's going to come down to whether rebirth serves the purpose of your game or not. If your target audience is fans of incremental games, they may expect that you include such a mechanic, or they may think that it's over-used; that's a market research question.

# Answer
> 15 votes
Expanding on crass\_sandwich's point about 'numbers go up', specifically for idle / clicker / merge games, prestige mechanics allow the game creator to provide an extra 'layer of power', above what's already in the game: by making certain boosts/abilities contingent on prestige (or even `n` number of prestiges, for yet another 'layer'), you can give the player *exponentially* more power without requiring infeasible amounts of grind.

Additionally, there's pleasure *for the player* in revisiting already-experienced content but with vastly-increased abilities - the player may recall "last time I reached Underboss IV, it took me hours, but now I can one-shot it! RAWR!!"

# Answer
> 9 votes
One aspect that I think makes "rebirth" useful, which I think is missed, is in a game with branching quests, skill trees, etc.

Your players could just start a new game, sure - but sending them back to the beginning, nominally with the same character, gives them the chance to go down a different route.

It makes the game longer, makes sure more of the game content gets experienced, and doesn't have the same emotional weight as "start completely from scratch". This is great if you're a game designer - players get more unique playtime out of the same amount of content.

# Answer
> 4 votes
Rebirthing/prestige, often called a "soft reset", is a game mechanism that works like most other genres' unlockable content. However, unlike most other genres, the soft reset is usually built in as part of the game loop. Other genres tend to have common game mechanics for players that meet certain conditions in the game, such as clearing a level, winning a specific fight, or reaching the game's end credits. The content afterwards is a reward for those who want more content after the main adventure is done.

Clicker and idle games use the soft reset as a way to allow the player to explore more content the more they engage with the soft reset mechanism. In a sense, you might say that the soft reset is actually telling a story of some sort. Soft reset milestones are like "levels" in an adventure game; they allow the players to reach initially unobtainable content by allowing them to reset, but with better multipliers, new skills or features, and so on.

Not every game needs this, nor does every player want this. Sometimes, I enjoy a short idle game, like Space Plan. It's short, tells an amusing story, and I think was worth the time I invested in it. On the other hand, I have save files for Clicker Heroes, Idling To Rule The Gods, NGU Idle, Idle Slayer, and more, that go back many years and have been played for hundreds to thousands of hours. They're something fun to go back to, because it seems they're always adding new content.

Games without a soft reset tend to feel shorter and typically have less content. Space Plan, for example, has a runtime of 6-9 hours. It's a nice way to waste a weekend. Games with well-designed soft reset systems might last for hundreds or even thousands of hours. The soft reset should be designed to unlock new multipliers, skills, and other content the longer the player plays. This keeps the content fresh and engaging.

# Answer
> 4 votes
## Sometimes, it helps to adjust a polynomial or exponential cost increase

One of the clicker games I played in the past used what was probably initially a fairly reasonable curve of costs, but after playing for a few months, it wasn't difficult to wind up with a cost per action somewhere in the quintillions, and the curves for increase in clicking power didn't scale with the increase in costs, so it wound up in a situation where I could basically click once a day. The person developing the game introduced a reset mechanic where resetting gave you some additional multipliers at the start of the game, which meant that about a day or so of clicking after the reboot got you back to where you were before, but the multiplier, applied to the respective curves, gave you another few months before the curves went out of whack again.

Arguably, they could simply adjust the curves in general, but doing it in the restart mechanic changes the experience less for people starting from the start.

# Answer
> 3 votes
You've gotten some answers already, but I wanted to point out something extra: prestige is a trope of the incremental genre. In the majority of these games its how new features are unlocked, and I would argue its a pretty core mechanic that makes the genre work. Watching numbers go up is fine, but resetting back to the beginning and watching everything go up again but way faster makes for a very satisfying continuation. It makes the player more aware of how much they progressed in the first place. To my mind, its not the same as replayability at all - because the game should be different after prestiging. You should be reaching much higher numbers, and new content, much faster.

For actionable advice, I'd say that your game does not have to include this mechanic, but if you can incorporate it into your game loop elegantly (see Trimps, Antimatter Dimensions, Magic Research, Kittens Game, etc) then it works brilliantly. In my opinion, the mechanic does not work that well in Cookie Clicker for instance because there are times the game slows to the point you want to prestige, but the amount of currency you gain is not enough to unlock any new changes to the game for the next run. This should be avoided (in my opinion).

# Answer
> 2 votes
**A "Rebirth" mechanic allows the games to avoid a "Killscreen"**

The other answers are relevant from a player's perspective, and a game designer's perspective, but there's another reason for designers to encourage players to go through a "Rebirth" mechanic.

Most games can manage to find ways around this by having an alternate way of ending the game, but some Clicker genre games could still run into the issue of hitting an integer overflow (Or an long integer overflow).

Even with the largest number storage types, it's possible that a machine trying to store additional numbers to eventually run into a "Killscreen" where they run out of memory, or space to run the code, or they trip a glitch trying to display a number. That type of scenario does happen in some older games, especially where there is no "Rebirth/Reset/New Game +" mechanic implemented.

This allows us to have games where that still scratch the "Numbers go up" itch well beyond what would have been naturally viable for their game's setup.

# Answer
> 1 votes
In a rogue-lite type game it allows the developer to force a new player into a narrow upgrade path for their first few runs through the game. This makes the learning curve at the start manageable.

But every time they die they can purchase new upgrades using "meta currency" that increases strategic options for the next set of runs. And if the rate of earning that currency is decently balanced then a player going through the unlock cycle will only get one or two playstyle-changing upgrades at a time.

All this combines into letting the developer keep the "main" game short and simple and make a "failed" run still mean something in terms of forward progress. For example Vampire Survivors has 30 minutes per run through with a dozen stages and 50-odd characters, even playing each character on each stage to completion once will take hundreds of games.

# Answer
> 1 votes
In Cookie Clicker specifically, the developer Orteil has stated there will only be 20 buildings (Version history for 2.052), so the only thing left is to buy more buildings and upgrades, which is relatively slow to make progress even with combos.

What's much more important is the Heavenly Upgrades system, which lets players customize their playstyle much more than the original Grandmapocalypse mechanic, and introduces more decision making on when to ascend versus when to continue building up CpS. The Angel and Demon upgrades are designed for maintaining CpS while the game is closed, the Golden Cookie upgrades are designed for a combo-oriented playstyle, and the Golden Switch and Shimmering Veil upgrades are designed for idling with the game open. In addition, there are cosmetics like Label Printer and Dairy Selection as optional rewards.

---
Tags: game-design, game-mechanics, progression
---


# Question
Title: Want get rotation based on the details of four corners of a square
I got four corner points of the object which are topLeft, topRight, BottomRight, BottomLeft and are as clockwise. I want a rotation values in X, Y and Z for unity object to rotate based on the rotation of these four points. Actually, these points are coming from python and I want to represent rotation of it on unity object which has Rotation x,y and z

# Answer
> 0 votes
If the object is a square, you can do this:

```
// Find perpendicular vectors running sideways...
Vector3 right = TopRight + BottomRight - TopLeft - BottomLeft;

//...and vertically along the object's edges.
Vector3 up = TopLeft + TopRight - BottomLeft - BottomRight;

// Use a little vector math to get the remaining
// perpendicular axis, forming a basis.
Vector3 forward = Vector3.Cross(right, up);

// Extract the orientation of that coordinate basis.
Quaternion rotation = Quaternion.LookRotation(forward, up);

```

Then you can use the quaternion directly (good if you need to interpolate/blend the rotation) or extract `rotation.eulerAngles` if you need the output as angles (just note these are not as nicely behaved and can have unintuitive and large value discontinuities for small orientation differences, even though they still express the same orientation as the source quaternion)

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


# Question
Title: Position object in top left of Rect Transform 2D
I have a GameObject with a Rect Transform (I assume I should be using one) and I am trying to essentially spawn squares in a grid formation. However it starts from the middle and I want it to start from the top left.

I have tried adjusting the pivot but it seems to have no affect so I am pretty stuck.

Here is an image of what I have and the Rect Transform

Here is a snippet of my code for performing the Instantiation

```
rectTransform = GetComponent<RectTransform>();
Vector3 position = new Vector3(x * 1, y * -1, 0);
GameObject newPiece = Instantiate(PiecePrefabs[(int)type], position, Quaternion.identity);
newPiece.transform.SetParent(rectTransform);

```

I want this to start at the top left of the rect transform. (Assuming I should be using one).

# Answer
You can get the absolute position of the corner by

```
firstPosition = new Vector3(
    rectTransform.position - rectTransform.width / 2f,
    rectTransform.position + rectTransform.height / 2f,
    0f);
Instantiate(prefab, firstPosition, Quaternion.identity, rectTransform);

for (columns) {
    for (rows) {
        var position = new Vector3(
            firstPosition.x + columns * prefabWidth,
            firstPosition.y - rows * prefabHeight,
            0f);
        Instantiate(prefab, position, Quaternion.identity, rectTransform);
    }
}

```
> 0 votes

# Answer
While you can position it at the corner, personally I think its much easier to just add an offset, you can modify it in the inspector easily and change it through code whenever you like. It only takes a couple lines to do.

First create an offset variable that you can modify in the inspector:

```
public Vector2 spawnOffset = new(-50, 50);

```

Then add it to your spawn position:

```
rectTransform = GetComponent<RectTransform>();
Vector3 position = new Vector3(x * 1, y * -1, 0);
position += spawnOffset;
GameObject newPiece = Instantiate(PiecePrefabs[(int)type], position, Quaternion.identity);
newPiece.transform.SetParent(rectTransform);

```

Of course, you can get the position of the top corner, but in my personal opinion, this is way easier and more customizable.
> 0 votes

---
Tags: unity, 2d
---


title: GLSL ported shader not working in HLSL

text:
# Question
Title: GLSL ported shader not working in HLSL
I have been working on an Infinity Grid shader for my engine.

It was already implemented to **Vulkan’s GLSL**, so it worked great with **OpenGL’s (4.6) GLSL**.

Here's a reference.

This basic shader with simple XY plane that projected in the world and apply **fragment/pixel** shader calculation to look as a grid. So what could have gone wrong? With **OpenGL** it works good as expected, but with **DirectX 11** it doesn't.

That's how the grid looks in OpenGL.

But in DirectX 11, that grid starts to glitch or even disappear. It is only visible while I'm actively resizing the window.

I'm sure the problem is not at DirectX 11 Pipeline (**Blend, Depth-Stencil, Rasterizer states**) because I already 100 times disabled, re-enabled it and changed its descriptions (`D3D11_BLEND_DESC, D3D11_DEPTH_STENCIL_DESC`). I tried different combinations but the result is still the same. So I assume that the problem is actually in the **pixel/fragment** shader, I think with some math functions or even with alpha.

**GLSL** Vertex Shader:

```
#version 450 core

// Input VAO data.
layout (location = 0) in vec3 attrib_Position;
layout (location = 1) in vec4 attrib_Color;
layout (location = 2) in vec2 attrib_TextureCoord;
layout (location = 3) in vec3 attrib_Normal;
layout (location = 4) in vec3 attrib_Tangent;
layout (location = 5) in vec3 attrib_Bitangent;

layout(std140, binding = 0) uniform UB_GridVS_MVP {
    mat4 viewMatrix;
    mat4 projectionMatrix;
    mat4 invViewMatrix;
    mat4 invProjectionMatrix;
} view;

// Out to Framgment Shader.
layout(location = 1) out vec3 nearPoint;
layout(location = 2) out vec3 farPoint;
layout(location = 3) out mat4 fragView;
layout(location = 7) out mat4 fragProj;

vec3 UnprojectPoint(float x, float y, float z) {
    vec4 unprojectedPoint =  view.invViewMatrix * view.invProjectionMatrix * vec4(x, y, z, 1.0);
    return unprojectedPoint.xyz / unprojectedPoint.w;
}

void main(void) {

    // Unprojecting the near/far plane.
    vec3 p = attrib_Position;

    fragView    = view.viewMatrix;
    fragProj    = view.projectionMatrix;
    nearPoint   = UnprojectPoint(p.x, p.y, 0.0);
    farPoint    = UnprojectPoint(p.x, p.y, 1.0);
    gl_Position = vec4(p, 1.0);
}

```

**GLSL** Fragment Shader:

```
#version 450 core

layout(location = 1) in vec3 nearPoint; // nearPoint calculated in vertex shader
layout(location = 2) in vec3 farPoint;  // farPoint calculated in vertex shader
layout(location = 3) in mat4 fragView;
layout(location = 7) in mat4 fragProj;

layout(std140, binding = 1) uniform UB_GridFS {
    vec4  gridColor1;
    vec4  gridColor2;
    vec4  cameraPos;
    vec4  cameraForward;
    float near;
    float far;
    float maxDistance;
    float offset;
} gridUBO;

layout (location = 0) out vec4 pixelBuffer;

const float subdivisions = 10.0f;

vec4 Grid(vec3 fragPos3D, float scale, bool drawAxis, vec3 gridColor) {
    vec2 coord = fragPos3D.xz * scale; // use the scale variable to set the distance between the lines
    vec2 derivative = fwidth(coord);
    vec2 grid = abs(fract(coord - 0.5) - 0.5) / derivative;
    float line = min(grid.x, grid.y);
    float minimumz = min(derivative.y, 1);
    float minimumx = min(derivative.x, 1);
    vec4 color = vec4(gridColor, 1.0 - min(line, 1.0));
    // z axis
    if(fragPos3D.x > -0.1 * minimumx && fragPos3D.x < 0.1 * minimumx)
        color = vec4(0.0, 0.0, 1.0, color.w);//1.0;
    // x axis
    if(fragPos3D.z > -0.1 * minimumz && fragPos3D.z < 0.1 * minimumz)
        color = vec4(1.0, 0.0, 0.0, color.w);//1.0;
    return color;
}

float ComputeDepth(vec3 pos) {
    vec4 clip_space_pos = fragProj * fragView * vec4(pos.xyz, 1.0);
    return (clip_space_pos.z / clip_space_pos.w);
}

float ComputeLinearDepth(vec3 pos, float near, float far) {
    vec4 clip_space_pos = fragProj * fragView * vec4(pos.xyz, 1.0);
    float clip_space_depth = (clip_space_pos.z / clip_space_pos.w) * 2.0 - 1.0; // put back between -1 and 1
    float linearDepth = (2.0 * near * far) / (far + near - clip_space_depth * (far - near)); // get linear value between 0.01 and 100
    return linearDepth / far; // normalize
}

int RoundToPowerOfTen(float n) {
    return int(pow(10.0, floor( (1 / log(10)) * log(n))));
}

void main(void) {

    float t = -nearPoint.y / (farPoint.y - nearPoint.y);
    if (t < 0.)
        discard;

    // Temp
    float _far = 200.0f;

    vec3 fragPos3D = nearPoint + t * (farPoint - nearPoint);
    gl_FragDepth = ComputeDepth(fragPos3D);

    float linearDepth = ComputeLinearDepth(fragPos3D, gridUBO.near, _far);
    float fading = max(0, (0.5 - linearDepth));
    float decreaseDistance = _far * 1.5;
    vec3 pseudoViewPos = vec3(gridUBO.cameraPos.x, fragPos3D.y, gridUBO.cameraPos.z);

    float dist, angleFade;
    if (fragProj[3][3] == 0.0) {

        // Perspective
        vec3 viewvec = gridUBO.cameraPos.xyz - fragPos3D;
        dist = length(viewvec);
        viewvec /= dist;

        float angle;
        angle = viewvec.y;
        angle = 1.0 - abs(angle);
        angle *= angle;
        angleFade = 1.0 - angle * angle;
        angleFade *= 1.0 - smoothstep(0.0, gridUBO.maxDistance, dist - gridUBO.maxDistance);

    } else {

        // Orthographic
        dist = gl_FragCoord.z * 2.0 - 1.0;

        // Avoid fading in +Z direction in camera view.
        dist = clamp(dist, 0.0, 1.0);// abs(dist);
        angleFade = 1.0 - smoothstep(0.0, 0.5, dist - 0.5);
        dist = 1.0; /* avoid branch after */
    }

    float distanceToCamera = abs(gridUBO.cameraPos.y - fragPos3D.y);
    int powerOfTen = RoundToPowerOfTen(distanceToCamera);
    powerOfTen = max(1, powerOfTen);
    float divs = 1.0 / float(powerOfTen);
    float secondFade = smoothstep(subdivisions / divs, 1 / divs, distanceToCamera);

    vec4 grid1 = Grid(fragPos3D, divs / subdivisions, true, gridUBO.gridColor1.xyz);
    vec4 grid2 = Grid(fragPos3D, divs, true, gridUBO.gridColor2.xyz);

    grid2.a *= secondFade;
    grid1.a *= (1 - secondFade);

    // Adding multiple resolution for the grid.
    pixelBuffer   = grid1 + grid2;
    pixelBuffer.a = max(grid1.a, grid2.a);

    pixelBuffer *= float(t > 0);
    pixelBuffer.a *= fading;
    pixelBuffer.a *= angleFade;
}

```

**HLSL** Vertex Shader:

```
// Input VBO data.
struct VsInput {
    float3 position     : attrib_Position;
    float4 color        : attrib_Color;
    float2 textureCoord : attrib_TextureCoord;
    float3 normal       : attrib_Normal;
    float3 tangent      : attrib_Tangent;
    float3 bitangent    : attrib_Bitangent;
};

// Output VBO data to Pixel Shader.
struct VsOut {
    float3   nearPoint : v_NearPoint;
    float3   farPoint  : v_FarPoint;
    float4x4 fragView  : v_FragView;
    float4x4 fragProj  : v_FragProj;
    float4   position  : SV_Position;
};

// View Projection + MVP buffer.
cbuffer UB_GridVS_MVP : register(b0) {
    float4x4 viewMatrix;
    float4x4 projectionMatrix;
    float4x4 invViewMatrix;
    float4x4 invProjectionMatrix;
};

// Grid position are in xy clipped space
// Grid mesh loaded by Force on CPU as attrib_Position.

float3 UnprojectPoint(float x, float y, float z) {
    float4 unprojectedPoint = mul(mul(invViewMatrix, invProjectionMatrix), float4(x, y, z, 1.0f));
    return unprojectedPoint.xyz / unprojectedPoint.w;
}

VsOut main(VsInput input) {

    // Unprojecting the near/far plane.
    float3 p = input.position;

    VsOut vsOut;
    vsOut.fragView  = viewMatrix;
    vsOut.fragProj  = projectionMatrix;
    vsOut.nearPoint = UnprojectPoint(p.x, p.y, 0.0);
    vsOut.farPoint  = UnprojectPoint(p.x, p.y, 1.0);
    vsOut.position  = float4(p, 1.0);
    return vsOut;
}

```

**HLSL** Pixel Shader:

```
// Input VAO data from Vertex Shader.
struct FsInput {
    float3   nearPoint : v_NearPoint;
    float3   farPoint  : v_FarPoint;
    float4x4 fragView  : v_FragView;
    float4x4 fragProj  : v_FragProj;
    float4   position  : SV_Position;
};

cbuffer UB_GridFS : register(b1) {
    float4 gridColor1;
    float4 gridColor2;
    float4 cameraPos;
    float4 cameraForward;
    float  near;
    float  far;
    float  maxDistance;
    float  offset;
};

struct OMOut {
    float4  pixelBuffer : SV_Target0;
    float   depthBuffer : SV_Depth;
};

// Constants.
const static float step = 100.0f;
const static float subdivisions = 10.0f;

float4 Grid(float3 fragPos3D, float scale, float3 gridColor) { // No cause glitching OK
    float2 coord = float2(fragPos3D.x * scale, fragPos3D.z * scale);
    float2 derivative = fwidth(coord);
    float2 grid = abs(frac(coord - 0.5) - 0.5) / derivative;
    float _line = min(grid.x, grid.y);
    float minimumz = min(derivative.y, 1);
    float minimumx = min(derivative.x, 1);
    float4 color = float4(gridColor, 1.0 - min(_line, 1.0));
    // z axis
    if(fragPos3D.x > -0.1 * minimumx && fragPos3D.x < 0.1 * minimumx)
        color = float4(0.0, 0.0, 1.0, color.w);
    // x axis
    if(fragPos3D.z > -0.1 * minimumz && fragPos3D.z < 0.1 * minimumz)
        color = float4(1.0, 0.0, 0.0, color.w);
    return color;
}

float ComputeDepth(float3 pos, float4x4 fragProj, float4x4 fragView) {
    float4 clip_space_pos = mul(mul(fragProj, fragView), float4(pos, 1.0));
    return (clip_space_pos.z / clip_space_pos.w);
}

float ComputeLinearDepth(float3 pos, float4x4 fragProj, float4x4 fragView, float near, float far) {
    float4 clip_space_pos = mul(mul(fragProj, fragView), float4(pos, 1.0));
    float clip_space_depth = (clip_space_pos.z / clip_space_pos.w) * 2.0 - 1.0; // put back between -1 and 1
    float linearDepth = (2.0 * near * far) / (far + near - clip_space_depth * (far - near)); // get linear value between 0.01 and 100
    return linearDepth / far; // normalize
}

int RoundToPowerOfTen(float n) { // Cause litte glitch
    return int(pow(10.0, floor( (1.0f / log(10.0)) * log(n))));
}

OMOut main(FsInput input) {

    OMOut omOut;

    // Temp
    float _far = 100.0f;

    float t = -input.nearPoint.y / (input.farPoint.y - input.nearPoint.y);
    //if (t < 0.)
    //  discard;

    float3 fragPos3D = input.nearPoint + t * (input.farPoint - input.nearPoint);
    omOut.depthBuffer = ComputeDepth(fragPos3D, input.fragProj, input.fragView);

    float linearDepth = ComputeLinearDepth(fragPos3D, input.fragProj, input.fragView, near, _far);
    float fading = max(0, (0.5 - linearDepth));
    float decreaseDistance = _far * 1.5;
    float3 pseudoViewPos = float3(cameraPos.x, fragPos3D.y, cameraPos.z);

    float dist, angleFade;
    if (input.fragProj[3][3] == 0.0) {

        // Perspective
        float3 viewvec = cameraPos.xyz - fragPos3D;
        dist = length(viewvec);
        viewvec /= dist;

        float angle;
        angle = viewvec.y;
        angle = 1.0 - abs(angle);
        angle = mul(angle, angle);
        angleFade = 1.0 - angle * angle;
        angleFade = mul(angleFade, 1.0 - smoothstep(0.0, maxDistance, dist - maxDistance));
    } else {

        // Orthographic
        dist = input.position.z * 2.0 - 1.0; // fragCoord.z is unprojectedPoint position or direct position?

        // Avoid fading in +Z direction in camera view.
        dist = saturate(dist);// abs(dist);
        angleFade = 1.0 - smoothstep(0.0, 0.5, dist - 0.5);
        dist = 1.0; /* avoid branch after */
    }

    float distanceToCamera = abs(cameraPos.y - fragPos3D.y);
    int powerOfTen = RoundToPowerOfTen(distanceToCamera);
    powerOfTen = max(1, powerOfTen);
    float divs = 1.0 / float(powerOfTen);
    float secondFade = smoothstep(subdivisions / divs, 1 / divs, distanceToCamera);

    float4 grid1 = Grid(fragPos3D, divs / subdivisions, gridColor1.xyz);
    float4 grid2 = Grid(fragPos3D, divs, gridColor2.xyz);

    grid2.a = mul(grid2.a, secondFade);
    grid1.a = mul(grid1.a, (1 - secondFade));

    // Adding multiple resolution for the grid.
    omOut.pixelBuffer   = grid1 + grid2;
    omOut.pixelBuffer.a = max(grid1.a, grid2.a);

    omOut.pixelBuffer = mul(omOut.pixelBuffer, float(t > 0));
    omOut.pixelBuffer.a = mul(omOut.pixelBuffer.a, fading);
    omOut.pixelBuffer.a = mul(omOut.pixelBuffer.a, angleFade);
    return omOut;
}

```

All **Uniform/Constant** buffers data were uploaded correctly. What is causing the glitch?

Here video showing whats happens.

**EDIT1**: I have been notices that when i remove this lines from HLSL Pixel Shader

```
    //omOut.pixelBuffer.a = max(grid1.a, grid2.a);
    //
    //omOut.pixelBuffer = mul(omOut.pixelBuffer, float(t > 0));
    //omOut.pixelBuffer.a = mul(omOut.pixelBuffer.a, fading);
    //omOut.pixelBuffer.a = mul(omOut.pixelBuffer.a, angleFade);

```

I can see normal white grid almost without glitches (e.g it became less).

And if i output red color to pixelBuffer

```
omOut.pixelBuffer   = float4(1, 0, 0, 1);

```

All glitches are gone.

So i can guess that maybe something wrong with one of math function or all of them. Maybe some of it internally behaves little different that GLSL does.

Here all math functions that use HLSL Pixel Shader.

* fwidth
* abs
* frac
* min
* max
* pow
* log
* floor
* length
* smoothstep
* saturate

# Answer
Given that it works when resizing the window, I wonder if there's some kind of issue outside of the shader code.

Resizing the window will probably be re-creating some render targets, so maybe you need to clear some or more of them every frame?

Also given that there's a non-opaque alpha output from the shader, you should double check all of the blending render state setup. You could also try outputting opaque pixels from the shader.

Having said that, those are just educated guesses. I'd recommend using a GPU debugger like https://renderdoc.org/ to analyse what's going on.

EDIT: I'd also recommend using D3D11\_CREATE\_DEVICE\_DEBUG as that can catch some types of error.
> 2 votes

---
Tags: opengl, glsl, directx11, hlsl, fragment-shader
---


# Question
Title: Animation for some reason doesn't trigger after death
So I am trying to trigger this explosion animation after this enemy dies, but for some reason the animation doesn't trigger. I've made sure that the explosion animation is linked to "Any State", and that the transition from any state to the explosion animation has the trigger "Death". Here is my script (only the important parts):

```
using UnityEngine;
using System.Collections;

public class Enemy : MonoBehaviour
{

    [System.Serializable]
    public class EnemyStats
    {
        public int maxHealth = 100;

        private int _curHealth;
        public int curHealth
        {
            get { return _curHealth; }
            set { _curHealth = Mathf.Clamp(value, 0, maxHealth); }
        }

        public void Init()
        {
            curHealth = maxHealth;
        }
        public int damage = 40;
    }

    public EnemyStats stats = new EnemyStats();

    private Animator anim;

    [Header("Optional: ")]
    [SerializeField]
    private StatusIndicator statusIndicator;

    void Awake()
    {
        anim = transform.GetComponent<Animator>();
    }

    public void DamageEnemy(int damage)
    {
        stats.curHealth -= damage;
        if (stats.curHealth <= 0)
        {
            GameMaster.KillEnemy(this);
            anim.SetTrigger("Death");
        }

        if (statusIndicator != null)
        {
            statusIndicator.SetHealth(stats.curHealth, stats.maxHealth);
        }
    }

    public void OnCollisionEnter2D(Collision2D _colInfo)
    {
        Player _player = _colInfo.collider.GetComponent<Player>();
        if (_player != null)
        {
            _player.DamagePlayer(stats.damage);
            DamageEnemy(999999999);
        }
    }
}

```

# Answer
> 0 votes
Here is a quick set up guide on 2D animations, perhaps you can run through these and see if you've missed any.

---

**Step 1**

Add an animator component to your `gameobject` you want to animate.

`Right Click` in the project window and create a new `Animator Controller`

**Step 2**

`Click` on the object your animating, and open the `Animation` window. (Window/Animation/Animation).

Click new clip in the animation window, and give it a name + somewhere to save to.

**Step 3**

Animate it, you can do whatever you like for this step, add particles, disable/enable stuff. It's up to you.

**Step 4**

Open the `Animator` window (Window/Animation/Animator). You should see your animation as a node in the animator, if you don't, find the Animation Clip you saved, and drag it into the Animator window. If you don't see the animator in the animator window, make sure you have your object selected.

**Step 5**

Go to the 'parameters' section in the Animator window, create a new 'trigger' parameter, you can call it whatever you like. By default you will have 3 nodes, an Entry node, an Exit node, and an Any State node. The entry node is similar to the `Start()` function in scripting. It allows you to set an 'idle' animation that will play on start. The exit node and any state node aren't really important for this example although if you're using death you may want to connect any state -\> death node instead of idle -\> death. That way you can die whenever.

**Step 6**

Go back to your object and head back to the animation window.

In the dropdown, click new. (I'm using a random animator from my game so I have more)

Name the animation idle or something similar, and then create your idle animation. It doesn't even have to be animated it could just have 1 keyframe with your idle stuff in it. Now go back to the animator and select the idle node you just made, `Right Click` it and select 'set as layer default state'.

**Step 7**

Now `Right Click` on the idle animation and `Click` 'make transition' this will make an arrow, selected your death animation or whatever you made earlier.

Click the arrow, there are a few options, first disable exit time, because we want the death animation to happen instantly without waiting for the previous animation to finish.

You can set a transition duration if you want the animations to smoothly transition from one another but you can mess around until it suits you. I have it off in this one.

Make sure you have a condition too and select your trigger as the condition.

Now in code you can get the animator like this:

```
animator = GetComponent<Animator>();

```

note there is no need for this `transform.GetComponent<>()`

Set the trigger like this:

```
animator.SetTrigger("triggername");

```

---
Tags: c#, 2d, animation, animator
---


# Question
Title: How do I get a client side health bar to update? Netcode for gameobjects
I am working on a multiplayer prototype and am trying to get health bars working. It's working on server side and health is working and subtracting from client side with a network variable, however I cannot get the slider to update properly.

```
   private void OnTriggerEnter(Collider other)
{
    if (IsServer)
    {
            if (other.GetComponent<PlayerNetworkHealth>() != null)
                other.GetComponent<PlayerNetworkHealth>().DepleteHealthClientRpc(damage);
    }
}

  [ClientRpc]
public void DepleteHealthClientRpc(int value)
{
    if (!IsServer) return;

    health.Value -= value;

    healthBar.value = health.Value;

    if (health.Value <= 0)
        Debug.Log("Dead");

}

```

Any info would be appreciated. Im at a loss.

# Answer
> 0 votes
In Mirror (and thus in Unity Networking) you can annotate simple types with SyncVar and let the library handle the syncing. In addition you can define a hook that should be executed, when the value changes. Mirror Unity (The documentation is better in Mirror for this)

```
[SyncVar(hook = nameof(SetHealth))]
int playerHealth = 100;

void SetHealth(int oldValue, int newValue) {
   healthBar.value = newValue;
   if (newValue <= 0)
       Debug.Log("Dead");
}

```

However if you are sure that the value is getting updated correctly on the client,

```
  if (!IsServer) return;

```

does not make much sense clientside. It will simply exit your setter and can't update your slider that way.

When you are new to networking, make sure that the test device is never in host (or server) mode when you want to test client code. Since host mode is both client and server in one, it can (and will) hide a lot of mistakes you can make like not actually syncing variables. But because you are both, you can always see the correct server value.

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


# Question
Title: How do materials and shaders work in graphics programming?
I stumbled upon a few videos about shaders and materials from The Cherno and my understanding is that materials are this sort of input that a shader takes to calculate an output instead of hard coding values into the shader so basically shaders become more flexible since you can control what their output is with a material.

I'm not sure if this is 100% accurate, but it makes sense so if this is true would you have multiple types of materials for different shaders? For example, shadows I believe require at least a shadow and depth shader so would I have a shadow material? Same for skinning/skeleton animations or are materials only for controlling how an object reacts to light?

# Answer
> 4 votes
A **shader** is simply a program that runs on the GPU. Shaders are most often used to determine how a mesh is rendered, but can be used for many other things as well.

### Rendering meshes

The most common use case for shaders is to describe how the surface of a mesh is rendered. In this case, the shader will usually be paired with a **material**, which is a collection of settings for that shader that are not hard-coded into the shader. The settings may include what textures are displayed on the surface, how glossy or metallic the surface is, or anything else required by the shader. One game will often have many different materials that use the same shader. For example, two humans might use the same set of shaders for rendering their clothing and skin, but have different materials with different textures.

At runtime, the shader will receive scene information (such as the position and rotation of the mesh in 3D space, and the data for any lights that are in range of the mesh) as well as the settings from the material.

Typically, the shader will determine the color of each pixel on screen where the mesh is visible. The color is often determined by the texture(s) assigned to the material, and how light should interact with the surface at that pixel's point in 3D space. However, shaders can also incorporate special effects that are independent of scene lighting - for example, highlighting an object by flashing it red.

However, besides determining the color of each pixel, shaders can also do advanced things like manipulating the vertices of the mesh. For example, vegetation (such as trees or bushes) might use a shader that causes some of the vertices to sway back and forth, giving the illusion that the vegetation is swaying in the wind. In this case, the material would probably have settings specifying things like how often and how far the vertices sway.

### Full-screen effects

Another common use for shaders is for applying post-processing effects over the entire screen. These are often called **screen-space shaders**. Rather than operating on a mesh, a screen-space shader takes a rendered frame as input (sometimes also using the depth buffer as a second input) and outputs a new version of the frame. Common screen-space effects include bloom, ambient occlusion, reflections, and depth-of-field.

While a screen-space shader still uses settings, I don't think the term 'material' is commonly used for screen-space shaders.

### Compute shaders

While shaders started out as a way to render complex graphics, the specialized hardware of a GPU can be used for other types of computation as well. Modern GPUs often support **compute shaders**. This is a category of general-purpose GPU programs which operate on a set of input and produce an output that is (usually) not a rendered image.

Compute shaders may be used for any kind of data processing that benefits from the highly parallelized computational architecture of a GPU. One of the most famous recent uses for compute shaders is in "mining" digital currency such as Bitcoin. Compute shaders can be used in video games for animation, physics, AI, audio processing, and more, though the developer must take care that the compute shader doesn't use enough GPU time to interfere with rendering.

# Answer
> 0 votes
Sort of. The way I would generally explain it is as follows:

> "Shader Program"
>
> The representation of the actual code written in a shader language; HSLS or GLSL. In the case of DirectX this is a structure in C++ that encapsulates the byte code of the HLSL shader and any of the applicable shader stages (VS, PS, HS, DS, GS, CS).

> "Shader"
>
> A collection of Shader Programs and what raster, blend, depth, and stencil operations to apply to them.

> "Material"
>
> Encapsulates what Shader to use and what textures to use as input into a Shader Program.

My own engine only allows a one-to-one relationship between Shaders and Materials. That is, Materials can only reference one Shader. But, a Shader can reference multiple Shader Programs. You can write one Vertex Shader Program and reference it between several different Shader objects.

Example Shader (custom xml):

```
<shader name="asteroid">
    <shaderprogram src="Data/ShaderPrograms/entity_VS.cso"/>
    <shaderprogram src="Data/ShaderPrograms/entity_PS.cso"/>
    <raster>
        <fill>solid</fill>
        <cull>none</cull>
        <antialiasing>false</antialiasing>
    </raster>
    <blends>
        <blend enable = "true">
            <color src = "src_alpha" dest = "inv_src_alpha" op = "add" />
        </blend>
    </blends>
    <depth enable = "false" writable = "false" />
    <stencil enable = "false" readable = "false" writable = "false" />
</shader>

```

Seen here, the Shader references two shader programs, a compiled Vertex shader and a compiled Pixel shader.

Example Material (custom xml):

```
<material name="asteroid">
    <shader src="Data/Shaders/asteroid.shader" />
    <textures>
        <diffuse src="Data/Images/asteroid.png" />
    </textures>
</material>

```

The associated Material takes the previously mentioned Shader with a given texture as input.

During Runtime, this data is used to create a Material object that knows what shader stages and textures to apply during draw calls.

---
Tags: c++, shaders, graphics-programming, materials
---


title: Does Steam have an API for sales data?

text:
# Question
Title: Does Steam have an API for sales data?
I go to the Steamworks website to see data about my game, change its page, see sales numbers, etc. Is there a way I can download this data into my own visualization setup so it is easier for me to view up to data information. I am mostly interested in getting page view, sales, and wishlist data so I can overlay that with marketing events, sales, etc in my own software.

# Answer
> 3 votes
At this spot in the Steamworks Quick Tips - UTM Analytics on Steam video you can see an option in the lower right corner for downloading UTM data as a CSV:

Documentation for UTM is available here.

The Sales & Activations Reports portal docs and the Wishlist Reporting docs also mention CSV options.

If you can't find what you're after digging through the CSVs, searching the docs and browsing their \[developer videos\](Official Group for Steamworks Development Support), you'll probably need to ask in the Steamworks Development Support Group or contact a Valve developer support specialist.

---
Tags: steam, steamworks, api
---


# Question
Title: How to stop acceleration on AddRelativeForce Unity 3D?
I'm a very new game developer, and I was making a simple first-person script using AddRelativeForce. However, when I go forward(or any direction), I slowly accelerate instead of going at a constant speed. Does anyone know how to fix this?

# Answer
Ok, I found something that works. I basically kept my entire old script, but in every frame I set the velocity to 0 and then added the relative velocity. This caused `AddRelativeVelocity` to essentially be the same thing as `SetVelocity`, but instead it set the relative force. While this worked in my situation, it might not work in others. Thank you to all of the helpful people who answered my question, though!
> 1 votes

# Answer
If you want to move your character using the AddRelativeForce-Method you need to keep track of the current velocity to prevent applying a force when the limit is reached. Something like this could be a solution:

```
public float yourMaximumMovementSpeed = 10f;

// we use velocity.magnitude to get the length of the vector
if (rigidbody.velocity.magnitude < yourMaximumMovementSpeed)
{
    rigidybody.AddRelativeForce(yourDirection * yourForce);
}

```

Instead of adding force you also could just set the velocity directly:

```
rigidbody.velocity = yourMovementVector * yourMovementSpeed;

```
> 0 votes

---
Tags: unity
---


# Question
Title: How to get value of transitionDuration in C# for Unity UI Toolkit
My existing code for this task is:

```
private VisualElement _creditSection;

    private void Start()
    {
        var rootElement = uiDocument.rootVisualElement;

        _creditSection = rootElement.Q("CreditSection");

        Debug.Log(_creditSection.style.transitionDuration.value);
    }

```

However, I am receiving null for this in console. I understand it's because the value is of object type, but I don't know how to get the value of the transition duration.

# Answer
> 1 votes
By chance, I discovered that I am able to get the value of `transitionDuration` using this code:

```
print(_creditSection.resolvedStyle.transitionDuration.First().value);

```

It seems that `_creditSection.style` is used for setting values, whereas `resolvedStyle` is used for getting values. Utilizing LINQ, we can extract the first value of transitionDuration.

---
Tags: unity, c#, unity-ui, ui-toolkit
---


# Question
Title: How to drag and drop complex objects (with multilayered textures and text) in Godot?
Newbie to Godot here. My idea is to create a deck building game, inspired by Slay The Spire or Across the Obelisk. I have come to a problem that I can not seem to find the answer.

So, the card object is complex: it consists of multiple things (textures for card frame and card front images, texts for card name and card category). Something like MtG type of a card. The issue is that the cards should also be draggable.

I found tutorials and examples online how to implement drag and drop in Godot, but they always show how to move a simple object like a sprite with one texture or a colored rect. No idea how to move an object that has a lot of children inside. My attempts to drag containers or controls were not successful.

Is there a way how to do it? Or is it better to preload all the textures and texts for the card and 'combine' them in one texture to drag? If so, how to do it correctly?

# Answer
> 0 votes
You could make the card be a separate scene with a node2D as root. I don't know how you want to implement dragging and dropping but here is how I would try to do it:

(this is all in the card scene)

Add a Area2D node and a collisionshape2D as a child of the area. (don't forget to also set the shape you want!)

Add your sprites/textures (I just used multiple copies of the godot logo as an example)

Add a script to the root node in the scene.

This is my script:

```
extends Node2D

var mouse_overlap = false
var dragging = false

func _process(delta):
    if mouse_overlap and Input.is_action_just_pressed("LMB"):
        dragging = true

    if dragging and Input.is_action_just_released('LMB'):
        dragging = false

    if dragging:
        global_position = get_global_mouse_position()

func _on_area_2d_mouse_entered():
    mouse_overlap = true

func _on_area_2d_mouse_exited():
    mouse_overlap = false

```

The `func _on_area_2d_mouse_entered():` and `func _on_area_2d_mouse_exited():` are signals from the Area2D connected to the script. You can add signals clicking on the Area2D and going to the node tab (over in the top right) and double clicking the signals `func _on_area_2d_mouse_entered():` and `func _on_area_2d_mouse_exited():`.

node tree in the card scene:

Finally, add the card scene to your main scene.

Final result: (you can't see the mouse because It's a screenshot)

---
Tags: godot, card-game, godot-4
---


# Question
Title: What does Unity do with a Prefab's Start function when it is assigned to something in the editor?
Unity C#. This is a hard question to phrase, an example explains it the best:

## Setup

1. Create a GameObject called Thing.
2. Create a script ThingScript and attach it to Thing.

```
public class ThingScript : MonoBehaviour
{
    bool initialized = false;

    void Start()
    {
        Debug.Log("Thing Started");
        initialized = true;
    }

    public void Run()
    {
        Debug.Log("Before Start: initialized= " + initialized);
        if (!initialized) Start();
        Debug.Log("After Start: initialized= " + initialized);
    }
}

```
3. Create a Prefab of Thing and delete the instance from your scene.
4. Create another GameObject called Holder.
5. Create a script HolderScript and place it on Holder.

```
public class HolderScript : MonoBehaviour
{
    public GameObject thingPrefab;

    void Start()
    {
        thingPrefab.GetComponent<ThingScript>().Run();
    }
}

```
5. In the Unity editor, drag your Prefab of Thing into the slot of Holder-HolderScript-thingPrefab
6. Run the game.

## Expected Result

Game prints come out as:

> Before Start: initialized=False

> Thing Started

> After Start: initialized=True

My assumption here being that thingPrefab was never initialized right, so the Start never ran. So we basically run it manually and therefore the result should be like above.

## Actual Result

Game prints come out as:

> Before Start: initialized=True

> After Start: initialized=True

---

An interesting note about this problem:

* When you close and open your Unity project again, the first run will print the Expected Result
* But if you stop your run, and hit play again, then it will switch to the Actual Result. And any runs after that will be the same.

So for some reason, restarting the editor is changing this result. Unity is somehow caching something.

What is going on here? I feel like I am going crazy.

# Answer
> 2 votes
First to answer the question, why it is behaving like this.

Because if you just assign a GameObject in the Editor, it does not exist yet. If you compare it with other languages, you are basically calling functions of a null object and you get undefined behaviour. MonoBehaviours can't be called with new, always use `Instantiate`.

Now for some examples on the differences.

```
public class Weapon: MonoBehaviour {

    public GameObject bulletPrefab;

    void Shoot() {
        Instantiate(bulletPrefab);
    }
}

```

The bullet does not need to be in your scene at the game start, you would create one each time you are shooting. You do not call functions on bulletPrefab, it is the original. In the example you don't have any reference left to the bullet you shot.

```
void Shoot() {
    GameObject bullet = Instantiate(bulletPrefab);
}

```

Now we have a reference to our created bullet. This would be the same as if you dragged your prefab in the editor in the scene and afterwards assigned it to the variable. The big difference is, since it is used as a template, any changes are reflecting in the copy at the time when you make it. If you drag an enemy in the scene, hurt it and use that as a source for later, the copies are as well hurt (or have the other state changes to it).

> Is it bad practice to then move these "reference objects" like to 9999,9999,9999?

No and yes. You can create reference objects and move them out of the players view. But not that far, this can cause problems on its own. If you want to read more about that, check out object pooling. Short version, Instantiate is performance intensive, if you need to create a lot of the same object fast, it is better to create them beforehand, deactivate them and use them when you actually need them. Examples would be bullet hell games.

You assigning a gameobject to a variable directly that exists in the editor already for fixed references. Take a spawn point. You would design it in the game at a location, your spawn manager would use this as a reference to know where to spawn something. (The spawnpoint could be more complex than just a Vector as the location).

As a last mentioning special mentioning, you can have Singletons. They usually do not have any visual component (normally a collection of just scripts) and thus are not visuable to the player. 0/0/0 makes not much a difference compared to 999999999. They are normally static and you can access them directly without having a reference to them or looking them up.

Now you can probably answer your statement

> Some people say using Find is bad, but now assigning to an editor is also bad.

If it livs in the scene and you need to know where, assigning in the editor is good. Find is expensive. The difference to your posted code is with that statement you compare apples to pears. Just assigning the prefab to a variable doesnt make it magically appear, `Find` won't even work for those (it will for all created instances of them).

Do not call Start yourself, this is bad practice, there should never a need to do this. If you want to have code that handles some init of your gameobject, have a seperate init function. Call this in `Start`. Call this init again if you need to reset the gameobject (often done in object pools). But don't call `Start`.

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


title: Open-source character creation engine

text:
# Question
Title: Open-source character creation engine
I'm working on a project which aims to create a 3D character/avatar, given a set of facial parameters (e.g. offset of the eyes, hairstyle or gender of the avatar) (something like Blade & Soul character creation). Currently, I'm looking for an API of an open-source game engine that allow generating a 3D avatar from the input set of facial parameters, then return the front view image of that avatar.

However, as I'm completely ignorant about the game-design community, I couldn't either find any appropriate tools that suit my purpose.

Are there any open-source API (maybe from a game) for 3D character creation, then return the front (or any) view of that avatar, with the input being a set of facial parameters?

Edit: The facial parameters I'm referring to are the parameters responsible for the appearance of the avatar. It can be either continuous (a floating number, e.g. offset of the eyes) or discrete (hairstyle or gender).

# Answer
> 0 votes
The method I would recommend would be to create models for each thing you want, for example one body, two eyes, different hairstyles, etc.

Then you can use the parameters to do different things. Like you said eye offset. You can just move each eye model a certain amount. Or for hairstyles, you can set the hairstyle you've chosen active, and deactivate all others.

Hopefully this answers your question. :)

# Answer
> 0 votes
I recommend you look at VROID Studio. It is a free program that let's you generate anime style avatars for VR Chat that can be imported into unity. The exported models have blendshapes and bones already rigged, so it should be easy to make sliders for them in Unity. You own the models you generate with VROID but you may not use them for the purpose of creating your own standalone avatar generator program (direct competition with the source program). I am not a lawyer, but using it in the context of a game should be OK.

Link to VROID: https://vroid.com/en/studio

---
Tags: asset-creation, avatar
---


# Question
Title: How do I go about creating an interesting progression for metal refinement for my automation RPG?
So, I'm having trouble devising a progression system for metal refinement in my game concept. I've tried doing research for it, but while I am trying to be realism focused (at least for automation, the rest is fair game), there's just too many options and most of them are far too complex to consider for a game that's supposed to be accessible. So, what are my options for a varied progression system of metal refinement processes? A foreword: the game's technological progression goes from early industrial revolution to near futurism, and the setting is as an sapient android assigned to colonize a frontier planet, if that info is needed.

**Important:** I have a distinct feeling this question may be unsuitable for this stack exchange, but it's the best fit I could find. If anyone has any suggestions for an alternate stack exchange or a different source of info entirely, please share and I will remove this question effective immediately in favor of this theoretical option.

# Answer
Looking at other games, there are a few factors that can be played with.

**-speed**
The speed at which a refiner can process inputs and produce and output. For most players, I think this is the core value expected to improve with higher tech refiners. Example: ARK has a refining forge and an industrial refining forge. The only difference is that the industrial forge smelts far faster at the cost of more advanced fuel and more space.

**-yield**
The input to output ratio is another important value. If you input X ore and get Y ingots, then higher tech refiners will typically get a value for Y that is closer to X than a lower tech refiner. The yield should never be more than 1 unless magic is involved (mass out can't be more than mass in). Example: ARK mortar and pestle vs chemistry bench. The chemistry bench has a higher starting recipe cost, but produces more items per use than the equivalent items would in a mortar and pestle.

**-Refinable Materials**
The types of materials that can be refined can be another good option for differentiating. I would recommend that you not go overboard with limiting refiners to a small subset. In general, as the tech level goes higher, the refiner should handle all previous inputs plus a few new ones. Example: Space Engineers survival kit vs basic refiner vs refiner. The survival kit can only process stone, but lets you get the materials you need to get a basic refiner, which can refine most ores. Those ores let you craft a full refiner, which can refine all materials in the game.

**-number of inputs**
If you want to get more complicated with alloys and exotics, more advanced refiners can have more input slots available. Putting different combinations of inputs results in different outputs. More input slots, more combinations, more advanced.
> 2 votes

# Answer
> there's just too many options

You don't need to add every single refinement to the game. Adds only refinement that is actually used to craft item in your game, and if you can, choose refinement that cover as much item as possible to reduce the amount of refinement.

> and most of them are far too complex to consider for a game that's supposed to be accessible.

You can try not adding the "far too complex" refinement to the game and instead sell the refined item from merchant. You allows player to sell raw material for money, and then player use the money to buy the refined item. If you insist for the refined item to be unlocked before player can have access to it, you can try making the merchant ask for additional material (probably one of the base material to create the refined item) alongside money, and lock that additional material behind progression, so that player don't have access to the refined material before they unlock the additional material.
> 2 votes

---
Tags: game-design, progression
---


# Question
Title: What is the process to transform physics positions in pixel art (ex. Rain World)?
In this video (GDC 2016), Rain World developers explain a lot of the procedural animation process in the game.

However, it is not clear to me how you go from physical locations and bones to the smooth pixel art rendering as shown in the video at 8:18 and 23:51. Is that the engine doing the rendering then a pixelation shader is applied on top of it or is it some kind of custom renderer that takes the bones' positions and "manually" draws the pixels?

**Edit**
Add picture. Question is about the method used, as (I try to clarify) in the drawing:

1. build spline from bones then pixelate via shader or pixel perfect camera.
2. build the tentacle from multiple sprites then (optionally?) pixelate.
3. other techniques?

*Please note I am totally new to game dev so assume close to 0 knowledge on these topics. I just find the graphics on this game particularly amazing and am curious as the main dev is an artist before being a coder.*

# Answer
> 1 votes
Looking around modding resources and communities...

The creatures are made of multiple sprites, each one picked depending on orientation, plus some simple polygon shapes (mainly for the tails). The animation seems to be mainly cutout animation, plus stretching and some masking (a silhouette through which we see a section of the actual texture that is "facing the camera").

The tentacles would be made of a large number of segments, which allow them to appear curve.

---

This is a quote form the devlog:

> This is what the animation system of rain world essentially is - it's actually not as procedural as you might think, because it's not just a magic formula that makes everything look cool. Instead it's heaps and heaps of special cases, hand crafted "animations" that are made more or less frame by frame, but not by drawing sprite sheets but by deciding what force should affect what body part at what time. The cool thing about it certainly isn't that it saves a lot of time, but that combinations of animations and smooth transitions between them can exist. If one body part is for example animated to do something, those motions might be defined in relation to the overall alignment of the body, which will make it look a little bit different each time depending on what else is going on.

---

This, combined with the explanation on the linked video, implies that creatures have two skeletons. One for simulation, and one for animation, which can be more complex. The simulation would be concerned with making sure a motion is possible, while the "cosmetic layer" would try to approximate the simulated motion while making it look organic.

---

I believe the game uses a lot of inverse kinematics and physic based follow through secondary animation.

It is unclear to me, but they might be using a "pixel perfect camera" (render to a low resolution texture and display it) which is common in pixel art games made in Unity, which is the engine of the game. However, the assets seem to be designed for the resolution at which they are displayed.

*And, of course, the result is stretched to fit the screen.*

I also want to note that game enviroment 3D effect is done via a large number of 2D layers and paralax. *Just in case that is what is making you think it is some pixelation shader.*

# Answer
> 0 votes
The game is rendered at a low resolution and then upscaled to fit the monitor size I think.

---
Tags: rendering, procedural-generation, pixel-art
---


# Question
Title: Is it wrong to leave references objects in the game world like 99999 units away
It's hard for me to explain my question with an example. But essentially, I have a game with many craftable items. Each item is a prefab. Each item has many unique scripts and functions on it.

Sometimes these items interact with each other (an Axe cuts Tree spawns Wood). So in either of their scripts, you need to reference the other ones.

What I did first was create one of each object in the hierarchy and move them 999999 units away. So basically I have a 100 items living very far away from the player. And so I would always use `Find("Wood")` to get a reference to the Wood to spawn some when the Tree is hit with the Axe (just an example).

Then I was told using Find is bad and you should rather use assignments in the unity editor (serialized fields). So I removed all my `Find()`s and replaced then with editor references to the prefabs (I drag the prefab into the field).

But now my problem is that editor-assigned game objects aren't always that great. These objects don't run through their `Awake()` and `Start()` setups. They also aren't "alive" yet. So you run into many issues trying to query stuff from an object that doesn't exist yet. A lot of references to stuff that is in the `Start()` is not being run so a lot of the item's code crashes without these references. So you have to write this "if not instantiated: `Instantiate()`" type of logic. All in all, this is honestly becoming a bigger mess than "Find" was.

**Is it wrong to just have a 100 spawned items living super far from the player?** Is this a common game design idea or how exactly are these "keeping references of things" solved? Because I don't feel the Unity editor assignment is exactly the solution.

---

I realized a better example might be required, so here is one. Each item has its own script. Each script has a `TryCraft()` function. This function checks if the player has the correct amount of resources or rules (like standing near a Builders Bench) to craft this item. If the player does not, we throw a popup explaining what is missing.

Notice we need 2 references here, a reference to the player's current inventory and a reference to the popup component. Both of these references are set up in my `Start()`.

So now, if I assign this Axe prefab to the UI craft button (through a serialized field) and the player tries to run `TryCraft()` on the Axe. Now the Axe complains because it doesn't know what `playerInventory` or `popupComponent` is. Because it never ran its own `Start()`. You see my point, I don't need a instance of the Axe just yet, I just need to run `TryCraft()` and that will create the instance if the player has the right amount of items. And I can't really move this logic somewhere else because some items are simple (you just need 2 x Grass) but other items are a lot more complex (you need to have 1 x Iron and be standing next to a Builders Bench to create a Bucket).

# Answer
> 2 votes
> Is it wrong to leave references objects in the game world like 99999 units away

Nope, it is not wrong, many games actually hide references object in unreachable place. Let me give you examples on recent games.

Lethal company hide the reference to char model in unreachable place of the map, which was found only by using modded version of the game.

Genshin impact hide their texture palette below the ocean, which is reachable only by using glitches. The texture palette size increases when new region is added to the game.

Location of the texture palette in the game

# Answer
> 0 votes
The main question is one of efficiency. Any object created will consume memory and CPU resources.

For 100 simple objects in a small game, this waste may not matter.

---

If your overall design requires all objects to already exist, there is a flaw in the design.

---

The best solution is to not use the objects themselves to convey information, but shadow the information in a **single** place like the player object: (could be stored elsewhere)

`Find("Wood")` becomes a lookup to an array stored on the player object indicating the count of the objects of that type collected.

Since the array always exists and has a default value for each item, null references and look-ups are not a problem.

---

Objects should be visual representations of collectable items and not the storage mechanisms themselves.

---

Chop down a tree, create via instantiation collectable "Wood" object(s). When the player collides with the "Wood" object the object is destroyed, and 1 is added to the player's resource array in the "Wood" slot.

Note that each slot "type" should be defined by an `Enum` value: `"Wood" = 0, "Iron" = 1, ...= 99` for the 100 types possible.

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


# Question
Title: How to change layer depth according to player location?
I would like to change the layer depth of objects, so that the player can go behind them. Right now it looks like this when the player is behind the object:

The problem is that the layer depth doesn't take into account the players location in relation to the object, so it doesn't look correct when the player is in front of the object:

What would be a good way to accomplish this? Could it be done just by comparing the locations of collision boxes (green boxes in the image) when they overlap? Or should I calculate and change the depth for all objects currently on-screen? How could I do that?

Thanks.

**\[UPDATE\]**

Here is the draw call from the base class for game objects:

```
public virtual void Draw(SpriteBatch spriteBatch) {

        if (texture != null && Active == true) {
            spriteBatch.Draw(texture, position, null, Color, 0f, Vector2.Zero, Scale, SpriteEffects.None, LayerDepth);
        }

        DrawCollision(spriteBatch); // DEBUG

}

```

It's an overload of the built-in MonoGame `SpriteBatch.Draw()` function. The thing that determines the draw order is `LayerDepth`. LayerDepth is a property inside each object. Currently it is just set to a fixed value.

# Answer
> How do I change layer depth according to player location? ... How could I do that?

Sort the `Draw()` calls by "location".

You have given two 2D images and no code. Without code, it is not possible to be more specific.
> 0 votes

---
Tags: c#, monogame, depth-buffer, draw-order
---


# Question
Title: How do I go about Mesh Simplifcation in generating multiple LODs?
I have been recently looking for any information on creating multiple LODs (level of detail) for an inputted mesh. However, there does not appear a lot of articles or pseudo code on how to go about how to produce multiple levels.

Any guidance would be very helpful, thank you.

The only information I could find is a Stanford slides but did not go in depth enough

They never show the evaluation.https://graphics.stanford.edu/courses/cs468-10-fall/LectureSlides/08\_Simplification.pdf and I found a paper I been trying, but lots of constants seem to be left out of definition, ex. d http://www.cs.cmu.edu/~garland/Papers/quadric2.pdf

# Answer
Quality LOD meshes are created during the creation process: "Start small and build upon..."

There is no general automatic solution for the reverse process.

Use the full mesh in all LOD levels.

---

Yes, there are vertex reduction algorithms, see point-cloud triangulation, but they require human correction to look natural.
> 0 votes

---
Tags: optimization, 3d-meshes, mesh, lua, level-of-detail
---


# Question
Title: Techniques for VR controller input smoothing
I work on a zero gravity space VR game where player can hold to an object and rotate around it using their hand. Imagine spacewalk on ISS, grabbing a handle with your extended hand and trying to move yourself around, including rotation.

When player grabs the object and moves hand/rotates wrist, I calculate where their body should move and apply transformations.

My issue is with jerkiness of controller input. It's just not smooth and doesn't feel very nice. Raw controller input has no lag, but high frequency and low amplitude jitter.

So far I tried slerp and 1Euro filter, but in both cases if jitter was reduced, I couldn't manage to reduce lag to an acceptable level.

What adds to complexity is that I need to smooth out both position and rotation and if any of them lags more than the other, movement is off.

I wonder if there are any other solutions I could look into?

I'm using Godot 4

# Answer
> 0 votes
Lag and smoothness are competing goals in the real-time 3D input context.

You must choose one over the other.

Either it is at the VR location, or it getting there over time.

---

> When player grabs the object and moves hand/rotates wrist, I calculate where their body should move and apply transformations. My issue is with jerkiness of controller input. It's just not smooth and doesn't feel very nice. Raw controller input has no lag, but high frequency and low amplitude jitter.

Any signal filtering will add input delay.

The answer is to limit/restrict the "hand/rotates wrist" input to reasonably small adjustment values within the given game constraints.

---

---
Tags: godot, virtual-reality
---


# Question
Title: Max velocity for smooth deceleration to destination
I am able to update velocity of my agent every 0.5 seconds. My agents max speed is 5f/s and max acceleration/deceleration is 2f/s.

I know how far away I am from the destination. How to determine current max velocity that my agent can go at the moment, to be able to decelerate to the destination (ending at velocity 0)? Since I am able to change velocity only twice per second and my max deceleration is 2f/s, I would image my agent arriving to the destination at max 2f/s velocity and then changing it to 0.

# Answer
Just work backwards to set up a "glide path" are the closest points/maximum speeds you can get without overshooting:

If you arrive to the destination at max 2f/s velocity and then change it to 0,

0.5 seconds earlier you are 1 ft away changing from 4f/s to 2f/s,

1 second earlier you are 3 ft away changing from 5f/s (the max) to 4f/s,

More than 3 ft away you are at 5f/s.

So the glide path is:

| Distance | Max speed arrival | Max speed departure |
| --- | --- | --- |
| 3 | 5 | 4 |
| 1 | 4 | 2 |
| 0 | 2 | 0 |

The idea is that when you get to a particular distance on a tick, you are are travelling at no more than the arrival speed, and at that distance you switch to the departure speed.

Taking your 5.4f example, if you were to travel at maximum speed if 5 f/second then you will be 5.4-2.5=2.9f away moving at 5, which is no good (faster and closer than specified by the glide path), so instead immediately reduce the speed to 4.8f/s, then after one tick you are 3f away and can reduce to 4f/s and stay on the glide path, so:

| time | distance | speed |
| --- | --- | --- |
| 0.0 | 5.4 | 4.8 |
| 0.5 | 3.0 | 4.0 |
| 1.0 | 1.0 | 2.0 |
| 1.5 | 0.0 | 0.0 |

So it takes 3x0.5=1.5s to get to the stopping point (your solution in comments takes 2s by travelling slower).
> 1 votes

# Answer
Dubre Den,

The max and assumed current speed(5) requires \<3.0 max deceleration steps(-2 speed) to reach 0.

Since the update rate is twice per second, the exact solution should be apparent without calculus.
> 0 votes

---
Tags: 2d, physics, mathematics, movement
---


# Question
Title: What design pattern should I use for adding functionality
I am making a tile based roguelike game with different objects in the world, like Doors, Security Cameras, Storage Shelves. With that, there are objects that have an inventory, can detect the player, or need interaction to operate.

How can I add such functionalities to a base class without inheritance? Because there will be objects with a combination of these functionalities.

I'm considering the decorator pattern, where the base class has all the methods defined (in the most bare form) and the concrete decorators have the implementation of the functionality. Is that really the way to go, or is there another option?

# Answer
> 2 votes
**Composition over inheritance.**

The basic idea that instead of having one specific class for each kind of entity in your game that is part of a long inheritance chain with "Entity" as the abstract base class, the class "Entity" doesn't do much more than handle a list of abstract components. Those components hold the data the entity needs to interact with different mechanics in your game.

So every entity in the game is of class Entity, but differs from other entities by its specific combination of components.

This allows you to mix and match components to create new entities. For example:

* Want a shelf to appear in the game? Create an entity with the "renderer" component that says what 3d model to use.
* You don't want the player to walk right through it? Add a "collider" component that says that this shelf is a solid box with a certain width, height and depth.
* Want it to also act as a container? Add the "container" component with a list of contents and a maximum capacity.
* Want the shelf to also be a secret door that can open and close? Add the "door" component to it that remembers whether the door is currently open or closed.
* Want the player to alternatively be able to smash it? Add the "destructible" component with an amount of hit points.

OK, so much for the data, but what about the code, you ask? Where does that go?

Well, there are two competing design philosophies here:

1. Entity - Behavior. The components themselves implement the mechanics by implementing virtual methods like Initialize, Update, HandleEvent etc.. This is a bit closer to the object-oriented philosophies that any object should be a "smart" piece of data that governs its own behavior.
2. Entity - Component - System. The components are just "dumb" data-holders that contain no or only minimal program logic. The actual code is in Systems. The systems each iterate over all entities that have certain combinations of components and implement the mechanics that use and manipulate that data. This approach seems a step back from the object-oriented design that was popular in the past two decades back to how games were designed in the age of C. But it recently became very popular again, because it makes it a lot easier to optimize for CPU cache usage and organize your logic in a way that makes it easy to parallelize on multiple CPU cores.

---
Tags: software-engineering, design-patterns, polymorphism
---


# Question
Title: How would I make my water shader ripple?
I can easily make a basic water shader, and create a script that detects when something touches the water, but does anyone know how I would actually trigger a ripple in shader graph? I'm not asking for full in-depth guide, I just need a basic idea. I have struggled to find videos that actually talk about collision based ripples. Also my game is 2.5d so you can see both the top and side of the water-I don't know if a normal map would work with that.

When I say 2.5d, its basically just 2D but using a perspective camera, so the water would look something like this just with a shader and different colors:

As you can see its like a cube but its more 2D than 3D, you only ever see the top and side.

Here is an idea of what I want:

It's basically 2D but you can see it's got some depth and it's quite realistic looking. It's also cut as if you're seeing it behind some glass. This is something I'm struggling to find online, as the water is viewed as if its inside a container. Making normal map methods fail.

The ripples should make the top of the water 'bob' when someone/something touches it, and there aren't likely to be more then 10 making splashes at a time, but really the system should be able to handle as many as possible.

# Answer
> 1 votes
If you need to scale up to a large number of interacting objects, then handling them one-by-one in the shader won't be efficient.

Instead, you can dynamically render ripples into a heightfield texture, then pass that texture to your water shader to apply conventional displacement.

Set up a layer in your project for this heightfield rendering. Make an orthographic camera that sees only this layer, and place it to look down at your water, framing its extents in the camera bounds. Set its clear colour to solid black, and have it render to a RenderTexture of your desired resolution. Higher resolutions are naturally more expensive, so start small and scale up only if the result looks too jagged. Use a floating point colour format so we can go negative (to get both valleys and hills)

When an object contacts the water (e.g. using `OnTriggerEnter` or `Stay` on a box collider aligned with the water's surface), spawn a ripple particle in that heightfield rendering layer. Animate the particle to expand and fade over time, and use an additive blending mode. This way, multiple ripples can overlap and constructively/destructively interfere, just like real water waves. This can handle scaling up to large numbers of particles.

For the particle content itself, you can either use a pre-made ripple texture, or use sinusoid math in the shader as agone suggests to shape each wave.

Now replace your water mesh with a densely subdivided plane. In its shader, sample the corresponding height from the heightfield and use that value to displace each vertex vertically. You can also get a partial difference from the heightfield and use that to tilt the surface normals to get correct shading even for small ripples.

# Answer
> 1 votes
Use the sin x, or cos x, function create simple waves.

For crests, use tan or 1/cos x or 1/sin x added to the waves.

The number of "splashes" is an array passed to the shader.

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


# Question
Title: Issue with AttackArea Monitoring Before Attack in Godot 2D Game
I'm developing a 2D game where the player character can attack enemies using a designated attack area (Area2D node named AttackArea). I've encountered a problem where the AttackArea is active and monitoring for collisions from the start of the game, even before any attack actions are performed by the player. This causes enemies to register hits without any input from the player.

Expected Behavior: I expect the AttackArea to activate and begin monitoring for collisions only when the player presses the attack button, triggering the attack animation.

Actual Behavior: The AttackArea seems to be monitoring for collisions right from the beginning, resulting in enemies getting hit without the attack button being pressed.

Relevant Code Snippets: Here's how I've set up the AttackArea and the player's attack logic:

```

var can_attack = true
var attack_cooldown = 0.5
var is_attacking = false

func _ready():
    $AttackArea.set_monitoring(false)

func _process(delta):
    handle_movement_input(delta)
    handle_attack_input()

func _on_AnimatedSprite_animation_finished():
    if $AnimatedSprite.animation == "attack":
        $AttackArea.set_monitoring(false)
        is_attacking = false
        can_attack = true

func handle_attack_input():
    if Input.is_action_just_pressed("attack") and can_attack:
        $AnimatedSprite.play("attack")
        $AttackArea.set_monitoring(true)
        is_attacking = true
        can_attack = false
        yield(get_tree().create_timer(attack_cooldown), "timeout")
        $AttackArea.set_monitoring(false)

```

```

extends Area2D

var health = 100

func _on_EnemySoldier_area_entered(area):
    if area.is_in_group("player_attacks"):
        take_damage(30)

func take_damage(amount):
    print("Enemy hit!")
    health -= amount
    if health <= 0:
        die()

func die():
    queue_free()

```

Steps I've Taken:

I've verified the collision layers and masks are correctly set up for both the AttackArea and the enemy. I've ensured the AttackArea is set to not monitor in the \_ready function and only set to monitor within the handle\_attack\_input function. I've added print statements to confirm the monitoring state of the AttackArea, which shows it being disabled after the attack is complete, but it's still active beforehand. I'm looking for guidance on why the AttackArea might be monitoring for collisions even before an attack is initiated and how to ensure it's only activated upon pressing the attack button. Any insights or suggestions for further debugging this issue would be greatly appreciated.

Thank you for your time and help!

(and yeah this is my first time posting her so i got chatGPT to write this since it'll explain the issue better)

# Answer
> 0 votes
It is a quirk of Godot that physics object can interact when they enter the scene tree. To prevent that you need to set `monitoring` to false even before that.

You can do so by setting the `monitoring` to `false` in the inspector. Or if that is not viable, you can do it in `_init`.

And since you would be setting `monitoring` to `false` early, you would need to do it in `_ready`.

---

Futhermore, I think `handle_attack_input` does not need timer nor disable `monitoring`, since you are already doing that when the animation finishes...

Unless you are trying to define a portion of the animation in which it can cause damage, in which case the reponsability of disabling `monitoring` should not be when the animation finishes.

---

*Your code for the `Area2D` seems take damage when an enemy enters, instead of imparting damage to the enemy. Futhermore, it removes the `Area2D` (with `queue_free`). You might want to review that.*

---
Tags: 2d, collision-detection, godot, gdscript, godot-3
---


# Question
Title: Which properties should be included in attribute sets when using the Gameplay Ability System (GAS) in Unreal Engine
I am writing a mmorpg using Unreal Engine 5 and I plan to use the Gameplay Ability System but I am new to it. I have questions about some of the properties and if they belong as regular properties on the class or as part of an attribute set. The 3 classes concerned are Entity, Player and Monster, where Entity is the parent class of both Player and Monster. Likewise each class would have it's own corresponding attribute set resulting in the player and monster instances each having two attribute sets. Below is a breakdown of my properties and which attribute sets I think they belong in and also some other properties that I think belong on the classes but not in GAS. I am less concerned with feedback about something being in Entity vs player vs monster but would greatly appreciate any feedback about if you believe a property does or does not belong in a GAS attribute set. Thanks!

## Included in GAS:

**Entity (Parent of player and monster) Attribute Set**

* Level
* CurrentHealth
* CalculatedHealthRegen
* CalculatedMaxHealth
* CalculatedFireResistance
* CalculatedIceResistance
* CalculatedLightningResistance
* CalculatedPoisonResistance
* CalculatedCurseResistance
* CalculatedMagicResistance
* CalculatedMovementSpeed
* CalculatedAttackSpeed
* CalculatedCriticalRate
* CalculatedCriticalDamage

**Player Attribute Set**

* CurrentExperience *(not sure about this but it affects level, which affects other calculations)*
* CurrentMana
* CalculatedManaRegen
* CalculatedMaxMana
* CalculatedMP
* CalculatedHP
* CalculatedStrength
* CalculatedDexterity
* CalculatedIntelligence
* CalculatedAttack
* CalculatedDefense
* CurrentWeight *(based on strength which can be augmented by armor and skills)*
* CalculatedMaxWeightCapacity

**Monster Attribute Set**

* AggroRange *(potentially affected by a skill like provoke)*

## Maybes and No's: *(Would be regular properties on the class instead of being part of an attribute set)*

**Entity**

* Name

**Player**

* Nation
* Race
* StatPointsAvailable *(not sure about this because it is incremented on level up but not decremented on level down, and is consumed when applied to a stat)*
* SkillPointsAvailable *(not sure about this because it is incremented on level up but not decremented on level down, and is consumed when used to learn a skill)*
* MannerPoints *(points gained by doing nation or race related quests, does not effect anything other than nation standing which as of now has no effect)*
* Nation Standing

**Monster**

* MonsterType
* IsAggro *(Will this monster attack player in range automatically or wait to be attacked, not does this monster currently have a target)*

# Answer
As a general rule, I would put properties in Attribute Sets when you want them to be involved in the calculations applied by Gameplay Effects (e.g. damage taken might be affected by your current Shield health, so the Shield health would go in the attribute sets).

Or if you want it to be buffed/debuffed by status effects, or have different values based on your character's level. That's another good reason to have it be in an attribute set. If I have compelling reasons not to put it in an attribute set, then I might just have a multiplier attribute in the attribute set. Last game I worked on, I had all the weapon tuning in data assets, because I found that putting it in attributes was too annoying and fiddly for the designers, and in practice all we really wanted was the ability to do things like globally buff weapon damage (game was just an FPS so not as complicated as an RPG), so I just created a WeaponDamageMultiplier attribute.

Another thing that's worth doing in my experience, is if you have attributes that heavily relate to a certain concept like health for a example (everything that I want to be damageable must have all these attributes), just create a separate attribute set for that. That way if later you want to create something like a damageable prop without all the baggage of other irrelevant attributes that the player/NPC attribute sets have, you can just apply the HealthAttributeSet to it
> 1 votes

---
Tags: unreal
---


# Question
Title: How should I implement a terrain raise/lower brush?
I am trying to make an terrain editor. The terrain is described by a grayscale height map. When I click at somewhere in the terrain map with the brush, the terrain should raise or lower about that clicked point. However, I don't know what is the correct function that describe height change of pixels around the clicked point.

# Answer
As agone says, there is no one function that's aways used for this, but here are a few you can try (see "Falloff Functions" tab):

You can use Pythagorean theorem to get the distance between the clicked point and the pixel/vertex you want to modify. Then you can scale the amount of modification to apply by multiplying it by an "intensity" factor between zero and one. This works whether you're using the brush to raise/lower, smoothen, or blend with a sampled shape, texture, or noise map.

Here are a few ways to calculate that intensity factor, using a `minRadius` within which you always want to apply 100% effect, and a `maxRadius` outside which no pixels/vertices should be affected:

* **Step Function**: `(radius <= minRadius)? 1 : 0` this gives you a hard-edged disc-shaped brush with no antialiasing or feathering at the edges, appropriate if you want to create a sharp cliff, canyon, or well. But it will need some love to dress up the sharp sides.
* **Linear Falloff**: `Clamp(1 - (radius - minRadius)/(maxRadius - minRadius), 0, 1)` This gives a flat ramp between the high and low, with sharp corners where they meet. This is good for making artificial structures like earthen berms around road bridges.
* **Smoothstep**: `linear * linear * (3 - 2 * linear)` This modification to the linear falloff gives it an "ease in-out" curve, rounding out the sharp corners a the top and bottom of the ramp. This starts to look like a more natural eroded terrain, and will show fewer artifacts that need to be cleaned-up.
* **Smoothstep Squared**: `smoothstep * smoothstep` Raising the smoothstep function to a power makes it steeper, with a more gradual slope into the valley at the bottom, while keeping the curve at the top from pinching into a corner. You may find this looks more natural for some kinds of terrain.
* **Sinusoid**: `0.5 - 0.5 * Cos(linear * PI)` This looks almost identical to smoothstep, so you'd probably find the polynomial version works just as well.

There are lots more options you could try, but hopefully that gives you a framework for exploring some options. Many tools will give the user a choice between different brush modes with different falloff characteristics to let the terrain artist pick the right tool for the particular feature they're sculpting.
> 0 votes

# Answer
The term you are looking for is falloff defined as any mathematical function class that uses a radius as the variable.

The falloff function should be a selection from one of the classes of functions: Linear, Polynomial, Logarithmic, Exponential, Trigonometric(restricted) about the radius.
> 0 votes

---
Tags: algorithm, terrain, heightmap
---


# Question
Title: How to send an HTTP Request from an Unreal Blueprint?
I'm updating a little telemetry-logging blueprint that uses HTTP requests to log game events to a server.

In the past, I've used the Fetch plugin for this, though it's currently listed as "Not for Sale" and at least for now it's unclear why.

There's also HTTP Requests for Blueprints currently listed for $4.99, which isn't bad. (Though as I'm setting this up for students to use, I like to avoid imposing extra costs on them whenever I can, even if they're small)

In my search, I also found HTTP request and related nodes in the core Unreal 5.3 documentation - so I wondered if this functionality is built-in now and no longer requires a separate plugin?

The trouble is, when I create a blueprint class and try to search for http-related nodes to add in its event graph, it comes up empty:

Am I using the wrong type of blueprint, do I need to somehow enable/import the HTTP nodes as a library, or am I doing something else wrong here?

Or have I simply misunderstood the (regrettably sparse, as usual) Unreal documentation, and this is still a feature that requires extra C++ code or plugins to achieve?

# Answer
> 2 votes
After doing a quick search I found this video which says that you need to enable the experimental Epic "HTTP Blueprint" plugin, which isn't enabled by default.

To enable the plugin, the steps are:

1. Go to Edit \> Plugins
2. Search for HTTP
3. Check the box next to "HTTP Blueprint (Experimental)"

The HTTP Request node will now be available when searching in a Blueprint:

# Answer
> 0 votes
Here's how I ended up solving it with the Fetch plugin I'd used previously. Its GitHub page says:

> For non-commercial projects, you can also get it from GitHub.

Since I only needed this for educational use in my classes, that non-commercial license was enough for my purposes.

I downloaded the files off GitHub, then ran `package.bat` since its last commit message said "Add new packaging tools for 5.2".

This created a `To Package` folder with sub-folders for Unreal versions 4.6, 4.7, 5.0, 5.1, and 5.2.

Since I'm using Unreal 5.3, the 5.2 version was closest. I copied the contents of the `Fetch_52` folder to a subfolder of my Unreal project labelled `Plugins\Fetch`.

When I booted up Unreal and loaded my project, it gave a warning that this plugin was built for version 5.2, but after confirming I wanted to load it anyway, it worked without issues.

You can edit the "EngineVersion" line in the Fetch.uplugin file to read "5.3" to suppress this warning on load.

When I have some time, I'll try porting my blueprints to work with the built-in experimental nodes Adam showed how to enable. That will let me avoid this batch file fiddling for future projects, once I can verify that the experimental version handles what I need. Till then, going with the familiar version got me up and running faster.

# Answer
> -2 votes
Hey man check out if this is working for you :)

---
Tags: blueprints, unreal-5, http
---


title: How to manage UI sound effects?

text:
# Question
Title: How to manage UI sound effects?
I'm making the main menu for a small game I'm making, and when I was learning how to make buttons etc.

In order to make the buttons have a sound effect when pressed and so on, I was told to add an audio source to each button and have a script on the button receive a reference to the audio file and play it. However, I am wondering what's the most efficient and "elegant" way to do it.

Is it ok to leave it in a "button manager" script that each button has, that also manages the appearance of the button, and have each button have an audio source, or should I make one object with an audio source, have a script for UI audio management and an event fired whenever player hovers or clicks any of the buttons and have that one audio source play the correct sound?

Will the latter create problems when a player hover quickly over several buttons?

Will it be better for when I eventually make a sound manager for sound preferences?

Also, will the same work for background music or will I need another audio source for that?

# Answer
**AUDIO MANAGER**

The best solution in my opinion would be to have an AudioManager in your scene. You can give it an AudioSource and and some sort of 'AudioManager' script.

The script can just contain a List of sound effects or something, and you can play each one using the AudioSource.PlayOneShot(audioClip) function. If you want a reference to make it easy to understand, heres my AudioManager that I use:

```
using UnityEngine;

public class AudioManager : MonoBehaviour
{
    // Reference to the AudioSource on the object.
    private AudioSource m_Source;

    // Reference to a SoundsAsset (a custom data type I made to store sounds for my game)
    public SoundsAsset soundsAsset;

    // Reference to the Instance of the Singleton -- https://stackoverflow.com/questions/2155688/what-is-a-singleton-in-c
    public static AudioManager Instance;

    void Awake() {
        // Singleton pattern.
        if (Instance != null && Instance == this) {
            Destroy(gameObject);
        }
        else Instance = this;
        m_Source = GetComponent<AudioSource>();
    }

    public void PlaySoundEffect(string soundName) {
        // If the sound name we entered is empty or null, return.
        if (soundName == null || soundName == string.Empty) return;
        switch (soundName)
        {
            // If we typed sound1, play the sound1 sound found in the soundsAsset, you can replace this with an audioclip and sound name of your choice.
            case "sound1":
                m_Source.PlayOneShot(soundsAsset.sound1);
                break;
            case "sound2":
                m_Source.PlayOneShot(soundsAsset.sound2);
                break;
        }
    }
}

```

This is a simplified version but hopefully it helps you understand, in the button's onClick function, you can select the audiomanager, and call the playsoundeffect() function along with the name of your sound. In this case I use a SoundsAsset to store all the sounds, but you could just use a list of AudioClips too.

**MUSIC MANAGER**

In my music manager, I create an audiosource for each audioclip put in, this is purely so that multiple music clips can fade and play at the same time. If you dont want that, you can just create a MusicManager, that simply has one audiosource, and create a MusicManager script that changes the music playing. Don't forget to use DontDestroyOnLoad, to make sure the Manager isn't destroyed when loading a new scene.

Hope this helps.
> 1 votes

---
Tags: unity, unity-ui, resource-management, sound-effects
---


# Question
Title: How do I put 3 different tiles in the same place?
I'm trying to make a Color Rings game. When I try to set 3 tiles (rings) in the same cell of the board (same X/Y coord), it shows me only one, the last one in the script. For example, in this case:

```
tilemap.SetTile(Vector3Int.zero, red2);
tilemap.SetTile(Vector3Int.zero, red3);
tilemap.SetTile(Vector3Int.zero, red1);

```

You can only see the red1 tile. If you change the order and put say red2 in the end you will see red2 and only red2. There's no way they block each other, cause you can see the board behind them in the central part. What do I do wrong?

This is how the game should look:

And this is what I actually get when I run:

# Answer
The only good solution I can think of is to create 3 separate Tilemaps on 3 different layers. I have done this before, and it can be useful if you need a certain square to fire off separate methods when using scriptable objects.

If parts of your tile are transparent, you should be able to achieve the desired result.
> 3 votes

# Answer
Now you can set multiple tile in one place by changing Z-position:
> 0 votes

---
Tags: unity, tilemap, tiles
---