# Question
Title: HLSL Converting View Direction into Equiangular UVs
In Unity, I am attempting to create a custom skybox that use a single render texture to create a flat unmoving skybox (the render texture source will do it's own movement) and reflect off objects as if it were an equiangular cubemap. So far using the unity custom skybox documentation I have been able to create a skybox with a flat image, however I have no idea how to read from the 2D render texture as if it were an equiangular cubemap. I've tried just using same UV coordinates from the skybox rendering pass as the reflection pass, but this results in a very small tiled reflection that looks very poor. I have also tried converting the view direction into cubemap uvs but this has the same result but with the entire image tiled.

What I am basically looking for is one of the following (but I am open to suggestions for better approaches):
1.) A way I can convert a float3 view direction into the uv coordinates needed to read from my image as if it were an equiangular cubemap.
2.) A way to convert the texture2D into an equiangular cubemap in real time every frame.

Here are some images I have taken of my current progress to show what I am looking for: ```**Custom Skybox:**
Background Correct.
Reflection Wrong`
`**HDRI Skybox:**
Background Wrong.
Reflection Correct``
`Sample Image
`]``
`Test Pattern`` **(apologies for the crazy table, turns out markdown doesn't work as advertised on StackExchange.)*

Although this may not be helpful here is some of the shader code I am working on for reference:
```
Shader "Hidden/DontTouchMyStuff_OkayOnlyALittle_BeGentle/HDRP/Skyboxes/HdriFlatSky"
{
    HLSLINCLUDE

    // Some vertex shader stuff here, don't worry about it.

    ///////////////////////////////////////////////////////////////////
    // FRAGMENT SHADER
    ///////////////////////////////////////////////////////////////////
    float4 GetTextureColor(float4 screenPixelPosition)
    {
        return tex2D(_MainTex, float2(screenPixelPosition.x / _ScreenParams.x, screenPixelPosition.y / _ScreenParams.y));
    }

    // Renders reflected cubemap
    float4 FragBaking(Varyings input) : SV_Target
    {
        return GetTextureColor(input.positionCS); // tex2D(_MainTex, float2(4 * ((input.positionCS.x / _ScreenParams.x)), 4 * (1 - (input.positionCS.y / _ScreenParams.y))));
    }

    // renders sky, works perfectly so far.
    float4 FragRender(Varyings input) : SV_Target
    {
        UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
        float4 color = GetTextureColor(input.positionCS);
        color.rgb *= 1;// GetCurrentExposureMultiplier();
        return color;
    }

    // experiment to use direction as uvs. Didn't work, results in reflection like texture is every side of a cubemap.
    float4 Frag(Varyings input) : SV_Target
    {
        // Points towards the camera
        float3 viewDirWS = normalize(mul(float3(input.positionCS.xy, 1.0), (float3x3)_PixelCoordToViewDirWS));
        // Reverse it to point into the scene
        float3 dir = -viewDirWS;

        // Rotate direction
        float phi = 0.0;
        float cosPhi, sinPhi;
        sincos(phi, sinPhi, cosPhi);
        float3 rotDirX = float3(cosPhi, 0, -sinPhi);
        float3 rotDirY = float3(sinPhi, 0, cosPhi);
        dir = float3(dot(rotDirX, dir), dir.y, dot(rotDirY, dir));

        float3 dirAbs = abs(dir);
        float ma = 0;
        float2 uv = float2(0, 0);

        if (dirAbs.z >= dirAbs.x && dirAbs.z >= dirAbs.y)
        {
            ma = 0.5 / dirAbs.z;
            uv = float2(dir.z < 0.0 ? -dir.x : dir.x, dir.y);
        }
        else if (dirAbs.y >= dirAbs.x)
        {
            ma = 0.5 / dirAbs.y;
            uv = float2(dir.x, dir.y < 0.0 ? -dir.z : dir.z);
        }
        else
        {
            ma = 0.5 / dirAbs.x;
            uv = float2(dir.x < 0.0 ? dir.z : -dir.z, dir.y);
        }

        return float4(tex2D(_MainTex, uv * ma + 0.5).rgb, 1.0);
    }

    ENDHLSL

    SubShader
    {
        // For cubemap
        Pass
        {
            ZWrite Off
            ZTest Always
            Blend Off
            Cull Off

            HLSLPROGRAM
                #pragma fragment FragBaking
            ENDHLSL
        }

        // For fullscreen Sky
        Pass
        {
            ZWrite Off
            ZTest LEqual
            Blend Off
            Cull Off

            HLSLPROGRAM
                #pragma fragment FragRender
            ENDHLSL
        }
    }
}

```

# Answer
> 0 votes
As with most things in life, I seem to have found the answer almost immediately after asking for help (but not during the 3 days I spent trying to figure it out before hand). Using the formula for spherically mapping textures provided by Stephane Hockenhull I was able to substitute the theoretical spheres normal with my view direction vector to produce a similar result to what I was looking for in my cube map. After that I simply remapped the uvs (or specially just the u value) from the range of \[0, 1\] to, erm well, \[0, 1\], but with the added twist that \[0, 0.5\] is now mapped to \[0, 1\] and \[0.5, 1\] is mapped to \[1, 0\] (basically duplicate and flip the input texture. For reference please see the expected result, final result, and shader script below. As you can see the UVs are slightly off but close enough in this case where I think it is passible. If anyone knows a better algorithm I would be happy to mark them as the true correct answer.

Expected result (single image for Texture2D background, and image+mirrored image as equiangular cubemap texture) :

Actual result:

Shader Code:

```
Shader "Hidden/CosmicLab/HDRP/Skyboxes/HdriFlatSky2"
{
    HLSLINCLUDE

        ///////////////////////////////////////////////////////////////////
        // FRAGMENT SHADER
        ///////////////////////////////////////////////////////////////////
        float4 FragBaking(Varyings input) : SV_Target
        {
            float3 viewDirWS = GetSkyViewDirWS(input.positionCS.xy);

            // Reverse it to point into the scene
            float3 dir = -viewDirWS;

            // Spherically map UVs
            float u = atan2(dir.x, dir.z) / TWO_PI + 0.5;
            float v = dir.y * 0.5 + 0.5;

            if (u > 0.5)
            {
                u = 1 - u;
            }

            return tex2D(_MainTex, float2(2 * u, v));
        }

        float4 FragRender(Varyings input) : SV_Target
        {
            UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
            float4 color = tex2D(_MainTex, float2(input.positionCS.x / _ScreenParams.x, input.positionCS.y / _ScreenParams.y));
            color.rgb *= 1;// GetCurrentExposureMultiplier();
            return color;
        }

    ENDHLSL

    SubShader
    {
        // For cubemap
        Pass
        {
            ZWrite Off
            ZTest Always
            Blend Off
            Cull Off

            HLSLPROGRAM
                #pragma fragment FragBaking
            ENDHLSL
        }

        // For fullscreen Sky
        Pass
        {
            ZWrite Off
            ZTest LEqual
            Blend Off
            Cull Off

            HLSLPROGRAM
                #pragma fragment FragRender
            ENDHLSL
        }
    }

    Fallback Off
}

```

---
Tags: unity, shaders, hlsl, uv-mapping, skybox
---


title: Layer Problem After Build&Run

text:
# Question
Title: Layer Problem After Build&Run
I finished my game and it runs fine inside Unity. I exported it to WebGL and ran it there but the main menu background does not show. It looks the background color and is pretty annoying. Here are some snapshots:

It's supposed to look like this. It looks like this when I run in Unity.

But when I export the game, here is what I see:

Anyone know where should I look to fix this? Here are my player settings:

# Answer
I added an Image component to the GameObject that holds the sprite. Then I had to make that default sprite object transparent so that it wouldn't interfere with the actual sprite I wanted to show.
> 0 votes

---
Tags: unity
---


# Question
Title: Character falls through the Platform Effector 2D in Unity. How can I fix it?
Character falls through the Platform Effector 2D in Unity. How can I fix it?

Here is the demonstration: https://imgur.com/G5YkTxa.

I tried changing the **Edit** \- **Project Settings...** \- **Physics 2D** \- **Default Contact Offset** from the current **0.01** value to the **0.1** value. The result is the same and here is the demonstration of it: https://imgur.com/3TAOsNY.

Here are my settings for the platform:

Here are my settings for the character's RigidBody 2D:

Here is what character colliders look like when my character runs: https://imgur.com/CTialU3.

I basically run the recorded inside Unity animation of running and move my character with the help of the:

```
        private void FixedUpdate()
        {
            ... some code which computes the velocity vector depending on the input (the pressed buttons)
            characterRigidBody2D.velocity = velocityVector;
        }

```

I googled for a while now similar issues, but was not able to find a solution. I want to avoid the character falling down randomly during running.

# Answer
I really did not want to resort to the one collider per character solution. Even if it is a widespread approach, I feel satisfaction by making the character colliders as accurate as possible. So, I just added an edge collider under the character. A lot of my issues got gone after that. Including the issue described in the question.
> 0 votes

---
Tags: unity, 2d, collision-detection, platformer, collider
---


title: Capsule getting stuck on edge of block

text:
# Question
Title: Capsule getting stuck on edge of block
I'm making a first person game and when I jump and my character gets close to the top of the wall, the vertical movement stops, jitters, or suddenly snaps to the top of the wall.

Video

Here is my character controller code, based on this tutorial:

```
using UnityEngine;

[RequireComponent(typeof(CharacterController))]
public class PlayerController : MonoBehaviour
{
    private InputManager inputManager;
    private CharacterController controller;
    private Vector3 playerVelocity;
    private bool groundedPlayer;
    [SerializeField] private float playerSpeed = 2.0f;
    [SerializeField] private float jumpHeight = 1.0f;
    [SerializeField] private float gravityValue = -9.81f;

    private Transform cameraTransform;

    private void Start()
    {
        controller = GetComponent<CharacterController>();
        inputManager = InputManager.Instance;
        cameraTransform = Camera.main.transform;
    }

    void Update()
    {
        groundedPlayer = controller.isGrounded;
        if (groundedPlayer && playerVelocity.y < 0)
        {
            playerVelocity.y = 0f;
        }

        Vector2 movement = inputManager.GetPlayerMovement();
        Vector3 move = new Vector3(movement.x, 0f, movement.y);
        move = cameraTransform.forward * move.z + cameraTransform.right * move.x;
        move.y = 0f;
        controller.Move(move * Time.deltaTime * playerSpeed);

        // Changes the height position of the player..
        if (inputManager.PlayerJumpsThisFrame() && groundedPlayer)
        {
            playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
        }

        playerVelocity.y += gravityValue * Time.deltaTime;
        controller.Move(playerVelocity * Time.deltaTime);
    }
}

```

I also tried using other solutions by changing the physics material of the level and player, neither worked.

# Answer
This question has been answered, thanks to DMGregory for editing this, because if i didnt have those specific keywords i wouldnt have been able to find answer

Fix

In the character controller compoment i changed the step offset to 0
> 1 votes

---
Tags: unity, physics, 3d, platformer, character-controller
---


# Question
Title: How can I find the direction a sprite is moving?
I'm trying to get the direction a sprite is moving (up, down, left, right). My current approach is to get the x and y coordinates of the target and the sprite (the sprite is the thing that I'm trying to get the direction of), and then have booleans be true/false based on the the values of the x/y coordinates (if they are greater than, less than, etc.). I'm not trying to rotate the sprite or change anything about how it's drawn, just find the direction that it's moving in. This is what I'm currently trying (this is more of a general idea of what I'm doing, and is pretty rough):

```
if (Target.Position.X < Position.X && Target.Position.Y < Position.Y - 500)
{
    IsFacingUp = false;
    IsFacingDown = false;
    IsFacingLeft = true;
    IsFacingRight = false;
}
else if (Target.Position.X < Position.X && Target.Position.Y > Position.Y + 500)
{
    IsFacingUp = false;
    IsFacingDown = false;
    IsFacingLeft = true;
    IsFacingRight = false;
}
else if (Target.Position.X > Position.X && Target.Position.Y < Position.Y - 500)
{
    IsFacingUp = false;
    IsFacingDown = false;
    IsFacingLeft = false;
    IsFacingRight = true;
}
else if (Target.Position.X > Position.X && Target.Position.Y > Position.Y + 500)
{
    IsFacingUp = false;
    IsFacingDown = false;
    IsFacingLeft = false;
    IsFacingRight = true;
}
else if (Target.Position.Y <= Position.Y - 500)
{
    IsFacingUp = true;
    IsFacingDown = false;
    IsFacingLeft = false;
    IsFacingRight = false;
}
else if (Target.Position.Y >= Position.Y + 500)
{
    IsFacingUp = false;
    IsFacingDown = true;
    IsFacingLeft = false;
    IsFacingRight = false;
}

```

# Answer
Myself, I'd attack it a little something like this:

```
public enum Direction {
    Down,
    Left,
    None,
    Right,
    Up
}

public static DirectionFromTo(Vector2 from, Vector2 to) {
    Vector2 offset = to - from;
    Vector2 absolute = new Vector2(Abs(offset.x), Abs(offset.y));

    // In your code, it looks like you have a fudge factor to ignore
    // up to a +-500 change in height. You can add that like so...
    float verticalFudge = 500f;

    if (absolute.x > absolute.y - verticalFudge) {
        return offset.x > 0 ? Direction.Right : Direction.Left;
    }

    if (absolute.y > 0) {
        return offset.y > 0 ? Direction.Down : Direction.Up;
    }

    return Direction.None;
}

```

You can call this with your previous and current positions to get a direction of travel since last frame, or with your current and target positions to get a direction of travel to move in next.

Save the direction you were moving last frame, so you can leave it unchanged in case you have no movement and get `Direction.None` back from this method. That way you'll simply keep your old facing direction instead of flickering or other bugs.

Here's how it might look in place of your current code:

```
var newFacingDirection = DirectionFromTo(Position, Target.Position);

if (newFacingDirection != Direction.None)
   facingDirection = newFacingDirection;

```
> 1 votes

---
Tags: c#, xna, monogame
---


title: Creating Blender-like cavity shader

text:
# Question
Title: Creating Blender-like cavity shader
I'm trying to achieve in Godot something similar to cavity effect from Blender (this can be enabled in viewport options; cube on the left is displayed by viewport with this option enabled):

How would you replicate this?

# Answer
> 1 votes
Closest I've seen to recreating this effect as a shader

https://youtu.be/JMMy-xqrwdw

---
Tags: shaders, fragment-shader, godot
---


# Question
Title: How to calculate gravity vector based on device rotation?
I have basic scene where the cube sits on platform

What I want is if the device is rotated 90 degrees to the left, cube should fall down as shown below

I came up with a solution to tackle that by modifying the `Physics2D.Gravity` vector so it should be like following

1. Device rotation 0, vector(0, -9.81).
2. Device rotation -90, vector(-9.81, 0).
3. Device rotation 180, vector(0, 9.81). And so on (Rotation would be anything between 0 to 360 degrees).

I don't know how to calculate that vector based on rotation degree. Any suggestion is much appreciated.

Thanks

# Answer
> 5 votes
You can calculate the correct physics world gravity with the help of the acceleration method in the Input class.

`Physics2D.gravity = 9.82f * Input.acceleration.normalized;`

The code example above uses a gravity force of 9.82f, and by multiplying that value with the device' accelerometer value (normalized so it's between 0.0f and 1.0f), the physics world's gravity will be set based on the device orientation.

---
Tags: unity, physics, rotation
---


# Question
Title: Why would I want to set a minimal OpenGL version before creating the context?
Typical GLFW applications have these lines after `glfwInit()`:

```
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

```

And similarly:

```
glfwMakeContextCurrent(window);

```

I get that `glfwMakeContextCurrent` is needed before sending calls to the OpenGL API, but the doc says

> You can require a minimum OpenGL version by setting the `GLFW_CONTEXT_VERSION_MAJOR` and `GLFW_CONTEXT_VERSION_MINOR` hints before creation

But why would I want that? Why would I cut options for OpenGL versions? I did not understand that, if I am interpreting it correctly in the first place

# Answer
> 1 votes
Like many others, OpenGL is an evolving software. As time goes by, it needs to adapt to users needs and to the new and evolving hardware that the manufacturers such as Nvidia come up with.

As OpenGL version goes up, new features are offered, since sometimes those features require a more recent hardware, not every user can benefit from them. So this means that a shiny new thing you can do with OpenGL and show your players in your game will not be available for the users using older hardware.

By setting the minimal version of OpenGL, you're telling the API that you'll probably use more recent features, and it will help tell whether the user can run your game or not. It will also prevent the use of some older, deprecated features.

One of the side effects I can think of, is that software like NVIDIA Nsight will support calls only for the most recent OpenGL versions. So if you decide to build your game supporting an older OpenGL minimal version (because you want to support more users), you'll not be able that kind of tool to debug your code.

From what I understand, studios that have more resources will implement the same feature in a similar way using multiple OpenGL version, where the "more recent" way will be more beautiful and/or run faster.

# Answer
> 0 votes
You want to set a minimum version to have a functionality of that version available. That includes functionality of the shading language of the respective version.

Examples:

1. Set 4.0 to have tessellation in the shader pipeline
2. Set 4.2 to have a debug context
3. Set 4.5 to have DSA (Direct State Access) available

... and so on.

See also: https://www.khronos.org/opengl/wiki/OpenGL\_Context and https://www.glfw.org/docs/latest/context\_guide.html

The latest version, 4.6, was defined in 2017. Setting a minimum versions may give the driver opportunities to optimise and to not reserve resources for functionality that will not be used, but that's speculative from my side.

---
Tags: opengl, c, glfw
---


# Question
Title: Calculated surface normals for Perlin-noise are weird
I'm trying to use simplex Perlin-noise to create topography of a planet (procedurally generated). The basic sphere consists of 6 sided cube with normalized vertices.

Before adding noise the first problem was the Unity did not calculate the normals correctly at the edges of the sides so seams were visible.

According to this solution (Calculate mesh normals with added noise): the gradients are calculated for each vertex and normals are calculated from these gradients. It works with one layer of noise:

I'm trying to implement some features like in this video (\[Unity\] Procedural Planets (E03: layered noise)):

* multiple layers of noise
* shift the elevation value from (-1,+1) to (0,1)
* add strength
* add minimum value

**Multiple layers of noise**

Here is the base of my noise and normal generation method:

```
private float GetElevationAndNormal(Vector3 point,
                                    out Vector3 normal,
                                    float baseFrequency,
                                    float baseAmplitude,
                                    float roughness,
                                    float persistance,
                                    int layers)
{
    float frequency = baseFrequency;
    float amplitude = baseAmplitude;

    float noiseValue = 0;
    Vector3 gradients = Vector3.zero;

    for (int i = 0; i < layers; i++)
    {
        // Sample the noise value and gradient at our position.
        NoiseEvaluation evaluation = _noise.Evaluate(point * frequency);
        noiseValue += evaluation.Value * amplitude;
        gradients += evaluation.Gradient;

        if (i < layers - 1)
        {
            amplitude *= persistance;
            frequency *= roughness;
        }
    }

    // Zero out the component of the gradient perpendicular to the sphere.
    var surfaceGradient = gradients - point * Vector3.Dot(gradients, point);

    // Compute an updated normal - leaning away from the direction of increase.
    normal = (point - 25f * amplitude * frequency * surfaceGradient).normalized;

    // Convert our noise sample to an elevation.
    return 1.0f + noiseValue;
}

```

And the result is not correct:

I know the normal calculation is the following: \\$\vec{n} = \vec{x} − s \cdot \vec{h}\\$, where \\$\vec{h}\\$ is the `surfaceGradient` variable. (Surface normal to point on displaced sphere) So maybe the problem is with the value of \\$s\\$. I tried the following things:

* use the sum of amplitude and frequency of each layers
* use the last value of amplitude and frequency
* use other value than 25f

**Update #1:** I tried to sum the scaled gradients but it seems there is a little misalignment yet. At 2 layers of noise it is almost OK but the shading on the left is a little bit lighter. At 5 layers of noise there is a lot of differences.

2 layers of noise:

5 layers of noise:

Here is the modified code:

```
float frequency = baseFrequency;
float amplitude = baseAmplitude;

float noiseValue = 0;
Vector3 gradients = Vector3.zero;

for (int i = 0; i < layers; i++)
{
    // Sample the noise value and gradient at our position.
    NoiseEvaluation evaluation = _noise.Evaluate(point * frequency);
    noiseValue += evaluation.Value * amplitude;
    gradients += evaluation.Gradient * 25f * amplitude * frequency;

    if (i < layers - 1)
    {
        amplitude *= persistance;
        frequency *= roughness;
    }
}

// Zero out the component of the gradient perpendicular to the sphere.
var surfaceGradient = gradients - point * Vector3.Dot(gradients, point);

// Compute an updated normal - leaning away from the direction of increase.
normal = (point - surfaceGradient).normalized;

```

**Question #1**: how should I change the normal calculation in case of multiple noise layers? What is the relation between layer numbers and normal calculations? Do I modify amplitude and frequency wrong in the for loop?

**Shift elevation**

This works perfect I had to modify the noise value and also the gradient value:

```
NoiseEvaluation evaluation = _noise.Evaluate(point * frequency);
noiseValue += (evaluation.Value + 1) * 0.5f * amplitude;
...
gradients *= 0.5f;

```

**Strength**

I wanted to use this parameter to scale the noise, also works perfect, just had to multiply also the sum of noise values and the sum of gradient with the strength value:

```
noiseValue *= strength;
gradients *= strength;

```

**Minimum value**

It has an issue: when a noise value is below the minimum value than I use the minimum value as elevation. In this case the normal vector should be the vector pointing from the center point to the actual vertex point. But the gradient returned from the Evaluate function is calculated based on the original elevation not the minimum. The result:

I modified the algorithm in the following way: when an elevation is a minimum value then use the vector point from center point to the actual vertex point. This solved the issue but not perfectly because normals are not correct at the edge of "plains" (I get better result when use the Unity RecalculateNormals method):

**Question #2:** Is there any way to fix these few wrong normals at the edge of "plains"?

# Answer
I accept DMGregory's comment that this little difference does not seem to be an algorithm issue and I use this method in the future instead of the Unity built-in normal recalculations.
> 0 votes

---
Tags: procedural-generation, perlin-noise, normals
---


# Question
Title: How to morph a player character into another entity in MC JAVA 1.16-1.17?
I want to add morphs into my game. Is there any command/code/resource I can use to make someone morph into an entity?

# Answer
> 0 votes
Yes, there is a mod for this found here. Here is how to install the mod into your Minecraft client.

1. Download and Install **Fabric Installer** for Minecraft 1.16 found here.
2. Run Fabric's .jar file, choose the Minecraft version you want and press “Install.”
3. Next, run Minecraft, with the Fabric profile chosen.
4. Then, go into `/Appdata/Local/.minecraft/mods` and put the morph mod into the folder.
5. Finally, restart Minecraft in order for the mod to be imported.

---
Tags: minecraft-modding
---


# Question
Title: Unity display my generic list in the editor
I have the following class:

```
[System.Serializable]
public abstract class BaseBehaviour<T> : MonoBehaviour
{
    [SerializeField]
    public List<BaseAction<T>> Actions;
    protected int currentIndex = 0;
    public bool OptOut = false;
    public Intelligence.Intelligence Intelligence;
    public T BaseAiContext;
    public List<BaseConsideration> Considerations;

    public Dictionary<string, object> CacheValues = new Dictionary<string, object>();

    public abstract void UpdateBehaviour();

    public bool IsDone()
    {
        if (currentIndex > Actions.Count || OptOut)
        {
            return true;
        }

        return false;
    }

    public abstract float GetScore();
}

```

Then i have an implementation of this class:

```
[System.Serializable]
public class AttackTargetBehaviour : BaseBehaviour<ExampleAI>
{
    public override void UpdateBehaviour()
    {
        Actions[0].Execute(this);
    }

    public override float GetScore()
    {
        float currentScore = 1;
        for (int i = 0; i < Actions.Count; i++)
        {
            float score = 0; // Actions[i].GetScore(this);
            if (score <= 0.0f)
            {
                return 0;
            }
            else
            {
                currentScore *= score;
            }
        }

        return currentScore;
    }
}

```

However here the list doesn't show in the inspector window which ultimately means i can't add my `scriptableobject` actions.

Can anyone tell me how i can display such as list in the `Unity` inspector?

For reference my action looks like this:

```
    [System.Serializable]
public abstract class BaseAction<TContext> : ScriptableObject, IAction
{

```

And the implementation of this class is:

```
    [CreateAssetMenu(fileName = "Move to Target", menuName = "AnAppGames/AI/Example/Actions/MoveToTargetAction")]

public class MoveToTargetAction : BaseAction<ExampleAI>
{
    public override void Execute(BaseBehaviour<ExampleAI> context)
    {
        throw new System.NotImplementedException();
    }

    protected override void OnUpdate(BaseBehaviour<ExampleAI> context)
    {
        throw new System.NotImplementedException();
    }

    protected override void OnStop(BaseBehaviour<ExampleAI> context)
    {
        throw new System.NotImplementedException();
    }
}

```

# Answer
Unity 2020 can handle more instances of generic types without extra steps. So something like this will display in the editor out of the box:

```
public UnityEvent<int> myEvent;

```

In Unity 2019 or earlier, you can sometimes work around the restrictions by giving a concrete name to the generic variant you want to use. Like this:

```
[System.Serializable]
public class EventWithIntegerArgument : UnityEvent<int> {}
public EventWithIntegerArgument myEvent;

```

So for your example, you may be able to take:

```
public abstract class BaseBehaviour<T> : MonoBehaviour
{
    [SerializeField]
    public List<BaseAction<T>> Actions;

```

And make it...

```
public abstract class BaseBehaviour<T> : MonoBehaviour
{
    [System.Serializable]
    public class TypeSpecificAction : BaseAction<T> {}

    [SerializeField]
    public List<TypeSpecificAction> Actions;

```

Here, each concrete instantiation of `BaseBehaviour<T>` for a different type `T` will also create its own nested `TypeSpecificAction` type based on that T. Since it's a specific named type, not a generic, it *should* work with Unity's serializer. But I have not tested this specific case.
> 1 votes

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


# Question
Title: Translating conditions ("If A has B, then true") into objects that satisfy them ("A has B")
I have a system where I'm sifting through a large number and variety of objects in my game, looking for objects that match an arbitrary search criteria that can be simple or complex.

For example, suppose a Foo has three integer properties, A, B, and C. I might search the list of Foo objects three times. First, I want to find a Foo where A\>5. Second, I might want to find a Foo where A\<B or B=8. Third, I might want to find a Foo where A=2, B=6, C\>A, and C\<B. The point is that I could arbitrarily pass any of a very wide set of conditions into the search.

Now here's my problem. In *all* cases, if I can't find an item that matches these criteria, I want to create a new Foo that *does* match, and add it to the list of Foo objects.

The thing I'm wrestling with is figuring out an underlying system of representing conditions that allows me to then create an item that directly matches those conditions. So far I've got two ideas, neither of which I'm a fan of:

* Repeatedly generate random Foo objects across the span of possible properties, until applying the criteria to one of them results in true. Given the possible permutations involved, this feels like an absolute performance nightmare, and would probably require a ton of caching logic to track what possibility spaces have already been tried.
* Establish a list of individual conditions with isolated variables (such as a GreaterThan condition with the referenced property that indicates whether the property is A, B, or C; and the target value) and create a corresponding declaration (Make \[property\] a random value between \[targetValue\] and \[propertyMax\]). Not only is this incredibly tedious, but I'm also not really confident I understand how it would work, particularly in C# but more generally also. This feels like self-reading code and that's something I have no experience with.

My question is, basically, what designs and techniques can I use to address this sort of issue - the need to create objects that match criteria, when those criteria could be arbitrary? Surely this has come up in other projects. What kinds of constraints or frameworks are applied to make this doable?

# Answer
> 2 votes
As luck would have it, a colleague recently showed me a project called CatSAT, which seems to do exactly what you're looking for.

> CatSAT is a declarative language embedded in C# that makes it easy to write simple procedural content generators for games, such as character generators, enemies, etc. Being declarative means you tell it the space of possibilities for the generated objects, along with whatever constraints (requirements) you want to apply to them, and the system will automatically find random instances that satisfy the constraints without you having to write a specialized generator algorithm.

As an example of the kind of thing it does:

> As a simple example, suppose we want to generate a party of 3 non-player characters. Characters have:
>
> * Three possible races (human, electroid, insectoid)
> * Four possible classes (fighter, magic user, cleric, thief).
> * Humans additionally have one of 3 possible nationalities
> * Clerics have one of 4 possible religions.
>
> In addition, there are constraints on the possible solutions:
>
> * Party members should have different classes.
> * Electroids can’t be clerics.
> * One of the religions is outlawed in one of the nations
> * Another religion is mandatory in one of the other nations.
>
> This can be written as a 17-line ASP program.

CatSAT can then take this statement of the problem in an Answer Set Programming -like dialect and stochastically sample possible parties that meet all of these constraints, by providing valid assignments of values to the variables of "party member 1 race, party member 1 class, etc..."

You can read the paper describing the problem domain and CatSAT's approach here. The full C# source code and a precompiled DLL compatible with Unity are available for free, and under a permissive license that lets you use it in your own commercial projects.

---
Tags: procedural-generation, software-engineering, logic
---


title: OUT.worldPosition effect on shader

text:
# Question
Title: OUT.worldPosition effect on shader
I am trying to follow a shader tutorial from 2016 for unity.

I reached the point where the author is distorting the text by changing OUT.wordPosition

```
    v2f vert(appdata_t v)
    {
        v2f OUT;
        UNITY_SETUP_INSTANCE_ID(v);
        UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT);
        float4 vPosition = UnityObjectToClipPos(v.vertex);

        float4 offset = float4(
            0,
            tex2Dlod(_NoiseTex, float4(v.vertex.x / 1000, 0,0,0)).r,
            0,
            0);
        OUT.worldPosition = v.vertex + offset;
        OUT.vertex = vPosition ;

```

**I am trying to follow this code but any changes I make to OUT.worldPosition has no effect. Even if I just set it to 0 the test still displays without any change.**

I know that the rest of my code works correctly. If I instead of OUT.worldPosition change OUT.vertex there is an imact on the text, if not the desired effect.

The biggest difference between me and the tutorial author is that he is using unity 5.3.4 for the base code of his shader. As I am using Unity 2020.2 I used the Unity 2020.2 as the base of my shader code, and worked around the differences.

For some reason I just can't manipulate worldPosition .

Here is the tutorial I am following https://www.youtube.com/watch?v=VZOetdCvFTg

Snippet of his working code

Are there changes in Unity 202 requiring me to do anything different? Am I doing something else wrong?

Here is my complete code for the shader

```
Shader "Unlit/TextShader"
{
    Properties
    {
        [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
        _Color ("Tint", Color) = (1,1,1,1)

        _StencilComp ("Stencil Comparison", Float) = 8
        _Stencil ("Stencil ID", Float) = 0
        _StencilOp ("Stencil Operation", Float) = 0
        _StencilWriteMask ("Stencil Write Mask", Float) = 255
        _StencilReadMask ("Stencil Read Mask", Float) = 255

        _ColorMask ("Color Mask", Float) = 15
        _NoiseTex ("Noise Texture",2D)="white"

        _DistortionDamer ("Distortion Damper",float)=10
        _DistortionSpread ("Distortion Spread",float)=50

        [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip ("Use Alpha Clip", Float) = 0
    }

    SubShader
    {
        Tags
        {
            "Queue"="Transparent"
            "IgnoreProjector"="True"
            "RenderType"="Transparent"
            "PreviewType"="Plane"
            "CanUseSpriteAtlas"="True"
        }

        Stencil
        {
            Ref [_Stencil]
            Comp [_StencilComp]
            Pass [_StencilOp]
            ReadMask [_StencilReadMask]
            WriteMask [_StencilWriteMask]
        }

        Cull Off
        Lighting Off
        ZWrite Off
        ZTest [unity_GUIZTestMode]
        Blend One OneMinusSrcAlpha
        ColorMask [_ColorMask]

        Pass
        {
            Name "Default"
        CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma target 2.0

            #include "UnityCG.cginc"
            #include "UnityUI.cginc"

            #pragma multi_compile_local _ UNITY_UI_CLIP_RECT
            #pragma multi_compile_local _ UNITY_UI_ALPHACLIP

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

            struct v2f
            {
                float4 vertex   : SV_POSITION;
                fixed4 color    : COLOR;
                float2 texcoord  : TEXCOORD0;
                float4 worldPosition : TEXCOORD1;
                half4  mask : TEXCOORD2;
                UNITY_VERTEX_OUTPUT_STEREO
            };

            sampler2D _MainTex;
            sampler2D _NoiseTex;
            float _DistortionDamer;
            float _DistortionSpread;

            fixed4 _Color;
            fixed4 _TextureSampleAdd;
            float4 _ClipRect;
            float4 _MainTex_ST;
            float _UIMaskSoftnessX;
            float _UIMaskSoftnessY;

            v2f vert(appdata_t v)
            {
                v2f OUT;
                UNITY_SETUP_INSTANCE_ID(v);
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT);
                float4 vPosition = UnityObjectToClipPos(v.vertex);

                float4 offset = float4(
                    0,
                    tex2Dlod(_NoiseTex, float4(v.vertex.x / 100, 0,0,0)).r,
                    0,
                    0);
                OUT.worldPosition = v.vertex + offset;
                OUT.vertex = vPosition ;

                float2 pixelSize = vPosition.w;
                pixelSize /= float2(1, 1) * abs(mul((float2x2)UNITY_MATRIX_P, _ScreenParams.xy));

                float4 clampedRect = clamp(_ClipRect, -2e10, 2e10);
                float2 maskUV = (v.vertex.xy - clampedRect.xy) / (clampedRect.zw - clampedRect.xy);
                OUT.texcoord = TRANSFORM_TEX(v.texcoord.xy, _MainTex);
                OUT.mask = half4(v.vertex.xy * 2 - clampedRect.xy - clampedRect.zw, 0.25 / (0.25 * half2(_UIMaskSoftnessX, _UIMaskSoftnessY) + abs(pixelSize.xy)));

                OUT.color = v.color * _Color;
                return OUT;
            }

            fixed4 frag(v2f IN) : SV_Target
            {

                half4 color = IN.color * (tex2D(_MainTex, IN.texcoord) + _TextureSampleAdd);
                #ifdef UNITY_UI_CLIP_RECT
                half2 m = saturate((_ClipRect.zw - _ClipRect.xy - abs(IN.mask.xy)) * IN.mask.zw);
                color.a *= m.x * m.y;
                #endif

                #ifdef UNITY_UI_ALPHACLIP
                clip (color.a - 0.001);
                #endif

                color.rgb *= color.a;

                return color;
            }
        ENDCG
        }
    }
}

```

# Answer
The name "worldPosition" doesn't have any particular meaning to a shader. It's just a nickname you've given to a particular variable, and naming it that doesn't actually cause it to control the world space position of the vertex.

What gives meaning to these variables are the tags after the colons in this structure:

```
struct v2f
{
    float4 vertex   : SV_POSITION;
    fixed4 color    : COLOR;
    float2 texcoord  : TEXCOORD0;
    float4 worldPosition : TEXCOORD1;
    half4  mask : TEXCOORD2;
    UNITY_VERTEX_OUTPUT_STEREO
};

```

Or here:

```
fixed4 frag(v2f IN) : SV_Target
{
    //...
}

```

These labels are called "Semantics", and they're the shipping labels that tell the graphics pipeline where to send each piece of data and what to do with it.

The `TEXCOORD1` semantic on `worldPosition` means the graphics pipeline will treat this as an extra channel of UV data, piping it through to the fragment shader to do its texturing work. But it won't actually accomplish anything on its own unless you write code that reads and acts on it.

The semantic that controls the rendered on-screen position of the vertex is `SV_POSITION`. So if we want to modify where a vertex is drawn, our data needs to somehow make its way to the variable with that semantic, specifically `OUT.vertex` in your vertex shader.

In the tutorial code you screenshotted, that's accomplished with these two lines:

```
OUT.worldPosition = IN.vertex + offset;
OUT.vertex = mul(UNITY_MATRIX_MVP, OUT.worldPosition);

```

Here we not only assign a value to our world position variable, we also *use that value* to update the `vertex` output, that ultimately drives the projected vertex position we see on the screen via the `SV_POSITION` semantic.

> **Minor quibble:** unless this is in a batch, `worldPosition` here is actually an object space position. To make a world space position, we should write something more like...
>
> ```
> OUT.worldPosition = mul(unity_ObjectToWorld(IN.vertex) + offset;
> OUT.vertex = mul(UNITY_MATRIX_VP, OUT.worldPosition);
>
> ```
>
> This separates out the object-to-world matrix multiplication as an initial step, then applies the view and projection multiplications separately.

So, moral of the story: if you're following a tutorial, follow it completely. It does not suffice to copy the same variable names. You also need to make use of the values in those variables to get the effect shown in the tutorial.
> 1 votes

---
Tags: unity, shaders, shaderlab
---


title: Change 3D Render Resolution in Godot

text:
# Question
Title: Change 3D Render Resolution in Godot
I'm making a Mario-Like platformer in Godot, and am going for a N64 style, and I want to lower the resolution of the render, while still having the window being resizable, like in Blender. Is there any way to do this?

Thanks in advance!

# Answer
> 2 votes
Simpler approach is to set "Stretch Mode" (in project settings under Display -\> Window -\> Stretch) to "Viewport".

With "Stretch Mode" set to "Viewport", the rendered resolution will match the design resolution (in project settings, under Display -\> Window -\> Size). This may result in enlarged "pixels".

Adjust "Aspect" (in project settings under Display -\> Window -\> Stretch) to the behavior you want (e.g. "Keep" will keep the aspect ratio, but may introduce black bars, but "Ignore" may use rectangular "pixels").

Refer to the article Multiple resolutions for details.

---

If you want to change the resolution of the Viewport at runtime, you can do the following:

```
    var root =  get_tree().root;
    root.size = Vector2(100,100);

```

Note: store the root in a variable, then edit it. Trying to edit it directly will result in a runtime error. This is a bug.

The following code also works:

```
    $"/root".size = Vector2(100,100);

```

Which is equivalent to:

```
    get_node("/root").size = Vector2(100,100);

```

---

You can also change the size of the window from code like this:

```
    OS.window_size = Vector2(100,100);

```

---
Tags: 3d, platformer, godot, gdscript
---


# Question
Title: Problems with porting LWJGL code to C++ (glDrawElements call returns error 1281/GL_INVALID_VALUE)
So, as the title might suggets, I'm currently trying to port a gui stack for my game engine from LWJGL(Java) to C++.
I originally had this following code in java:

```
        if(guiFramebuffer != 0 && colorTexture != 0)
        {
            glBindFramebuffer(GL_FRAMEBUFFER, 0);

            GL30.glDisable(GL_CULL_FACE);
            GL30.glDisable(GL_DEPTH_TEST);

            GL30.glBlendFunc(GL30.GL_SRC_ALPHA, GL30.GL_ONE_MINUS_SRC_ALPHA);
            GL30.glEnable( GL30.GL_BLEND );

            imageShaderProgram.start();
            GL30.glBindVertexArray(screenFillingQuad.getVAOId());
            GL30.glEnableVertexAttribArray(0);
            GL30.glEnableVertexAttribArray(1);

            GL30.glActiveTexture(GL30.GL_TEXTURE0);
            GL30.glBindTexture(GL_TEXTURE_2D, colorTexture);

            // Returns 0
            System.out.println("Error before: " + GL30.glGetError());
            GL11.glDrawElements(GL11.GL_TRIANGLES, screenFillingQuad.getVertexCount(), GL11.GL_UNSIGNED_INT, 0);
            // Returns 0
            System.out.println("Error after: " + GL30.glGetError());

            GL30.glDisableVertexAttribArray(1);
            GL30.glDisableVertexAttribArray(0);
            GL30.glBindVertexArray(0);

            imageShaderProgram.stop();
            GL30.glDisable(GL30.GL_BLEND);
        }
        else
            throw new NullPointerException("The framebuffer doesn't exist");

```

Now, let's get to the method that ports this whole thing to C++ (note that we use a nullptr as the last argument for glDrawElements here too, this will later be important.)
C++ code:

```
    basicImageShader.bindShader();

    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);

    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_BLEND);

    glBindVertexArray(planeVAO->getVAO());
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, colorTexture);

    std::cout << "BEFORE: ";
    GLint beforeError = glGetError();
    OUTPUT_OPENGLERR(beforeError); // Returns 0 (no error)

    // The issue seems to be that the indices buffer isn't being recognized.
    // If we take a look, we see the nullptr passed in as the last argument. If we change
    // it, we can achieve a similar effect as having a indices buffer, but only to an extend,
    // as this feature might be heavily slowing down the IO bus between graphics card and CPU.
    glDrawElements(GL_TRIANGLES, planeVAO->getVerticesAmount(), GL_UNSIGNED_INT, nullptr);

    GLint error = glGetError();
    OUTPUT_OPENGLERR(error); // Returns 1281 (GL_INVALID_VALUE)

    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(0);

    basicImageShader.unbindShader();

```

As you can see, the problematic gl call is equivalent to the java lwjgl code, but this call returns an error value of 1281.
**Now, to an important observation:**
This is not the case if we replace the nullptr in the draw call with an actual array. I'm not sure why this is the case. I'd be happy if you could provide any information and point out what I did wrong.
Edit: The user @MaximusMinimus pointed out that I should try glDrawArrays to narrow down the problem, so I've called glDrawArrays(GL\_TRIANGLES, 0, 3), and this indeed worked. I should maybe add that he/she isn't proposing glDrawArrays as a solution, but rather as a step to narrow down the issue I have.
So, here is the code that loads the indices buffer:
IndicesVBOLoader.h

```
#pragma once

#include "AbstractVBOLoader.h"
#include <vector>

class IndicesVBOLoader : public AbstractVBOLoader
{
private:
    std::vector<GLuint> indices;

public:
    IndicesVBOLoader(std::vector<GLuint>& indices);

    virtual GLuint loadVBO() override;
};

```

IndicesVBOLoader.cpp:
```
#include "IndicesVBOLoader.h"

IndicesVBOLoader::IndicesVBOLoader(std::vector<GLuint>& indices) : AbstractVBOLoader(-1, -1)
{
    this->indices = indices;
}

GLuint IndicesVBOLoader::loadVBO()
{
    GLuint vbo;
    glGenBuffers(1, &vbo);

    glBindBuffer(1, vbo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size(), indices.data(), GL_STATIC_DRAW);

    return vbo;
}

```

Also, here is my old code, written in Java:
```
package de.budschie.engine.assets_management.geometry;

import org.lwjgl.opengl.GL30;

public class IndicesVBOAssignment extends ArrayVBOAssignment<int[]>
{

    public IndicesVBOAssignment(int[] array)
    {
        super(-1, -1, array);
    }

    @Override
    public int loadVBO()
    {
        int vbo = GL30.glGenBuffers();

        GL30.glBindBuffer(GL30.GL_ELEMENT_ARRAY_BUFFER, vbo);
        GL30.glBufferData(GL30.GL_ELEMENT_ARRAY_BUFFER, array, GL30.GL_STATIC_DRAW);

        return vbo;
    }
}

```

And, finally, here is the way I load VAOs:

```
#include "VAOLoader.h"

VAO VAOLoader::loadVAO(std::vector<AbstractVBOLoader*>& loader)
{
    std::vector<GLuint> vbos = std::vector<GLuint>();

    GLuint vao;
    glCreateVertexArrays(1, &vao);

    std::optional<GLuint> currentVerticesAmount = std::optional<GLuint>();

    for (size_t i = 0; i < loader.size(); i++)
    {
        AbstractVBOLoader* currentVBOLoader = loader[i];

        glBindVertexArray(vao);

        if (!currentVerticesAmount.has_value())
        {
            std::optional<GLuint> optVerticesAmount = currentVBOLoader->getAmountPerVertex();
            if (optVerticesAmount.has_value())
                currentVerticesAmount = optVerticesAmount;
        }

        vbos.push_back(currentVBOLoader->loadVBO());
    }

    return VAO(vbos, vao, currentVerticesAmount.value());
}

```

# Answer
> 0 votes
Alright, I found the issue: When I loaded the indices in, I (for whatever reason) decided to put a 1 instead of an enum (more precicely, GL\_ELEMENT\_ARRAY\_BUFFER) to the glBindBuffer call that was being made whilest loading the indices. So, this is the corrected code:

```
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size(), indices.data(), GL_STATIC_DRAW);

```

Luckily, everything works fine now (or at least without any errors).

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


# Question
Title: How to move through a game object - while getting the normal of the initial contact
**In Unity, how can I detect a collision between two game objects, but have them pass through one another, i.e. not block each other?**

Specifically, I need the collision normal provided by the `Collision2D` object that comes with the `OnCollisionEnter2D` method. But I want to be able to move through the object that detected the collision, not get blocked by it.

*PS: Checking the `Is Trigger` checkbox would mean the argument passed into the trigger method no longer contains the collision normal!*

# Answer
> Is there no way to tell Unity to "give me collision information", but "do not interfere with my game objects' movement"?

As I explain in this answer, the contact information you get from collision events is generated as part of the collision resolution process, where the engine is figuring out how to change the positions and movements of the colliding objects to remove penetration.

That's costly extra work it doesn't need to do to simply detect overlaps, so if you haven't asked it to alter the objects' trajectories, then it doesn't do all this extra work, helping your game run faster.

And that's not a problem, because for the rare cases where we need contact information without altering motion, we can get that through other means: the rich set of raycasting and shape-casting methods the physics engine gives us.

So, we can keep our moving object (or its obstacle) as a trigger collider, to save the costly collision resolution work and avoid fighting with the engine to undo it. Then we can use a script to fire shape casts to reconstruct the impact normal when we detect a new trigger overlap.

Here's an example of how we could do that with a circular body. Here I assume the circle is centered on the object's origin, but we can adapt this to work with off-center colliders too.

```
[RequireComponent(typeof(CircleCollider2D), typeof(Rigidbody2D)]
public class TriggerEdgeDetector : MonoBehaviour {

     public LayerMask layersToDetect;

     public UnityEvent<Vector2> OnHitWithNormal;

     Vector2 _oldPosition;
     CircleCollider2D _collider;
     Rigidbody2D _body;

     void Awake() {
         _collider = GetComponent<CircleCollider2D>();
         _body = GetComponent<Rigidbody2D>();
     }

     void FixedUpdate() {
         _oldPosition = _body.position;
     }

     void OnTriggerEnter2D(Collider2D other) {
         Vector2 travel = _body.position - _oldPosition;

         var hit = Physics2D.CircleCast(
                        _oldPosition,
                        _collider.radius,
                        travel,
                        travel.magnitude,
                        layersToDetect);

         if (hit && (OnHitWithNormal != null))
             OnHitWithNormal.Invoke(hit.normal);
     }
}

```
> 2 votes

---
Tags: unity, collision-detection, physics
---


# Question
Title: Behavior Trees or GOAP for Rimworld-like game?
I am currently making a Rimworld-like game. For now, it is identical in appearance, how the map works and how the pawns (colonists) are supposed to function.

Core world-generation logic and A\* pathfinding is done, so my next step is to implement AI.

The question - for a game such as Rimworld (since the original author of the game never mentioned what sort of technology he used), is it preferable to use Behavior Trees or Goal Oriented Action Planning AI methods?

I use Unity and have found assets for both of the technologies:

GOAP

Behavior Trees

I am expecting large map sizes, anywhere from 200x200 to 400x400, and an AI agent might have to take a lot of things into consideration (his environment, the position of his allies and enemies, possibly nearby items and structures).

I am leaning towards GOAP because even though it seems harder to implement at first, it seems easier to maintain later, because the agents figure out stuff on their own based on the information they are given, so I won't have to hard-code every single action or pattern (please correct me if this is wrong.) I also have no experience with either of the technologies so this might be something to take into account, but I am willing to learn.

Any suggestions, comments or ideas are much appreciated and I'm open for discussion.

# Answer
> 1 votes
In a Rimworld-like game you are dealing with NPCs who need to be able perform complex multi-step tasks (transport materials to workplace, craft item, transport crafted item to storage). And players expect their NPCs to perform those steps in a smart way and while considering all kinds of other priorities. Such complex multi-step tasks are far easier to implement using GOAP than using behavior trees.

However, you might use simpler behavior trees for entities with less far-sighted behavior. Like animals, for example.

# Answer
> 2 votes
I'll only speak of Planning.

Unity provides a planner: you may wish to check that first instead of jumping into some GOAP Plugin (as amazing as they can be :-), or embarking into developping your own.

If you wish to develop a planner, GOAP's principles are:

0. NPCs have goals; have a procedure compute a goal for an NPC; this can be a method for each NPC class.
1. Actions as classes: one abstract action class and then subclass according to behaviors (combat, ambiant, etc).
2. Actions have costs; Jeff Orkin's advice is "abstract actions have higher costs".
3. Use Path-Planning A\* with action cost to search for a plan.
4. Actions have procedural preconditions : use these to drastically reduce the number of applicable actions in one game-state (i.e. limit A\*'s branching factor). This is very powerful to reduce search size, but is time consuming: use clever sensors to store the information you need to avoid recomputing for every action you could consider.

You may wish to begin without action costs.

You may wish to have dynamic action costs; for instance the MoveTo action can get its cost from distance. Obviously this is more complex.

Create a set of actions for each NPC type: for instance when planning for a grunt, use the action set for a grunt.

You may wish to run planning for meaningful NPCs only and have, say, a finite-state machine for others (e.g. animals).

So the idea is: compute a goal, find a plan achieving this goal and then, execute the plan.

Plan-execution-module's tasks are: updating game states, goals, and sensors accordingly, so that you don't spend your time replanning if goal hasn't changed, for instance, or so that you DO replan when game state forbids the execution of one action of a plan. Crucial issue is sampling: how often do you want to check your data to trigger planning again?

Enjoy Planning!

# Answer
> 1 votes
"In other words, I heard GOAP was better for projects where you have player made environment (or perhaps procedurally generated)."

Please, who told you that "GOAP was better for ..."? I'd really like to know.

What is at stake here is the following: planning need not be aware about the game. You can drop actions one morning, have the planner search for plans with these actions and change all these the next day.

And that's one of the best selling point of planning in a video-game. If not the best.

In a game, you can directly drop actions in a Smart Object Node (SON), for instance through a DLL (providing your code architecture can handle that). Then, any game object colliding with this SON can pass these actions to the planner when needed.

DLLs mean you provide actions yourself. You may wish to dynamically create actions.

For instance, you may wish to have the player create actions and then have the planner use these actions. An interesting point is that game design can generate situations when the player doesn't even know he's creating actions.

Or you can, first iteration, modify actions costs, according to what your game has been able to grasp from the player's emotional state.

But you won't escape the problems I listed in my previous post. The more actions available for search, the larger the branching factor.

---
Tags: unity, c#, ai, procedural-generation, behavior-tree
---


title: Refresh UI after changing source code

text:
# Question
Title: Refresh UI after changing source code
I was trying following things.

GameManager :

```
bool gameHasEnded = false;
public GameObject completeLevelUI;

public void CompleteLevel(){
    completeLevelUI.SetActive(true);
}

public void EndGame(){
    if(gameHasEnded == false){
        gameHasEnded = true;
        Invoke("Restart",2f);
    }
}

void Restart(){
    SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}

```

EndTrigger :

```
public GameManager gameManager;

void OnTriggerEnter(){
    gameManager.CompleteLevel();
}

```

I get a log in the console "`END`". Earlier I was using `Console.Log("END");` on `CompleteLevel()`, but I changed that source code. The old code seems to be working and not the new one. It's like Unity couldn't refresh that source code. (And I am sure that I have successfully saved the `C#` file.)

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

public class PlayerCollision : MonoBehaviour
{

    public PlayerMovement movement;

    void OnCollisionEnter(Collision collisionInfo)
    {
        Debug.Log(collisionInfo.collider.name);
        if (collisionInfo.collider.tag == "obstacle")
        {
            movement.enabled = false;
            FindObjectOfType<GameManager>().EndGame();
        }
    }

}
```

# Answer
> 1 votes
As *Zibelas* said in the comments, you are using the incorrect method in `OnTriggerEnter()`. By not adding anything into the parentheses, the program doesn't know when it should activate the method, thus causing it not to do anything, because it isn't being called. In order to fix this, simply replace `OnTriggerEnter()` with `OnTriggerEnter(Collider other)`. This will tell it when to run the method.

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


title: Leaning with Player Controller

text:
# Question
Title: Leaning with Player Controller
I'm adding leaning to my player controller and I can't find out how to stop the rotation overriding the tilt

```
  void Look() {
      transform.Rotate(Vector3.up * Input.GetAxisRaw("Mouse X") * mouseSensitivity);

      verticalLookRotation += Input.GetAxisRaw("Mouse Y") * mouseSensitivity;
      verticalLookRotation = Mathf.Clamp(verticalLookRotation, -90f, 90f);

      cameraHolder.transform.localEulerAngles = Vector3.left * verticalLookRotation;

  }

  void TiltCamera(float angle) {
      cameraHolder.transform.rotation = Quaternion.Euler(0, 0, angle);
  }

```

Thanks

# Answer
Found the solution add a second game object to parent the camera holder game object
> 0 votes

---
Tags: unity, rotation
---


title: How to Make Border of 2D Game in Unity

text:
# Question
Title: How to Make Border of 2D Game in Unity
I have a border by default. But, I'm having trouble detecting if my object collides with the border. I am looking for efficient ways to do this, and I am not sure what should I use. I thought using a `Tilemap` might work. But, it was only giving me a grid, not a `Tilemap`. Even then, I was unable to figure out how to use the grid. How should I go about creating this?

# Answer
As far as I can understand, you are trying to stop the player from moving out of the border. I would recommend doing this by using a Tilemap and adding a `Tilemap Collider` to the Grid inside the Tilemap GameObject. Then, simply just create a tile palette and add the chosen image for the border. Then, you can "draw" with the tile painter in the Palette Window. Also, by doing this, you can easily expand or shrink the border while developing, just by using the **Palette Tools**. You will also want to make sure you have the `IsTrigger` button unticked in the Grid Properties.
> 1 votes

# Answer
You can do it such as suggested in the comment section (using tilemap collision) or you can do it programmatically:

```
if (playerX >= borderX && playerX <= borderX + borderWidth &&
    playerY >= borderY && playerY <= borderY + borderHeight)
   you touch a border
else
   player move

```
> 1 votes

# Answer
I used `Sprite` and added `OnCollisionEnter2D`.

```
void OnCollisionEnter2D(Collision2D collision){
    if(collision.collider.tag =="obstacle"){
       Debug.Log("Finish");
    }
}

```

This way I am able to detect collision.
> 0 votes

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


title: Unity "static" references

text:
# Question
Title: Unity "static" references
I have been researching this for 2 days now and I cannot seem to find a proper response. I am trying to figure out a good way to store constant variables within my game.

Basically, does it make more sense to create a singleton script that holds all my prefabs inside it so I can easily access them and instantiate through the game? Or does it make more sense to keep all my assets inside the Resources folder and then call Resources.Load throughout the game (or through a Static class that holds references to all the resource paths and loads the resources on start up)

I have the same question regarding variables used within runtime. Would it be better to run through the Static class that is holding all these prefabs through the Resources folder? Or would it make sense to also hold these values inside the singleton.

Thank you!

# Answer
Although this question is fairly old, it popped up in the feed recently and I thought it might be worth un updated answer.

> Basically, does it make more sense to create a singleton script that holds all my prefabs inside it so I can easily access them and instantiate through the game?

If this singleton gets loaded into memory, it will also load all its dependencies, meaning you have all the prefabs in memory at the same time, even if you're using only a few of them.

If your game has the headroom to do this, then it's a convenient way to go. But if you're trying to conserve memory, then this should be avoided.

> Or does it make more sense to keep all my assets inside the Resources folder and then call `Resources.Load` throughout the game

In modern Unity versions, you can use Addressables to get more control over loading and unloading assets at runtime.

You can use `AssetReference` variables to hold a reference the assets you want to load, without actually loading them until you ask them to load. Then you're not tied to a specific string that might change when you move the asset around or rename it. And the asset can be in the build, in a separate asset bundle, or even downloaded from a remote server, and your consuming code doesn't need to know the difference.

I'd recommend phasing out use of the `Resources` folder entirely. It's very easy to inadvertently bloat your build with this folder, because every asset inside will always be included in your build, even if nothing ever uses them. Addressables solve all the same problems, better.

> I have the same question regarding variables used within runtime. Would it be better to run through the Static class that is holding all these prefabs through the Resources folder?

For this type of thing, I like to use a `ScriptableObject`

```
[CreateAssetMenu(fileName="SharedData.asset", menuName="Shared Data")]
public class SharedData : ScriptableObject {

    public Transform someCommonlyUsedPrefab;

    public float someCommonlyUsedValue;

    // ... etc.
}

```

This will let you right-click in your project folder and create a new asset that acts as a data container whose contents you can edit in the Inspector.

Your other scripts can hold a reference to it the same way they'd reference a prefab, (or you can make a static getter or resource locator to look it up) but you don't need to create a `GameObject` for it to sit on. It persists between scenes like `static` data, but unlike `static` classes or variables, it's easy to use the Inspector to review or edit its current contents.
> 2 votes

# Answer
Keep it simple. As zcabjro said, the conventional method is to add prefab references to the scripts that need them. If you have a GameObject with a script attached called 'Boy' and he wants access to the prefab called 'ball' to instantiate a game object then write it into his script.

```
 [SerializeField] private GameObject ball;

 void InstantiateGameObjects()
 {
       GameObject newBall = GameObject.instantiate(ball);
 }

```

It's unnecessary to hold them all as static objects or singletons throughout the game, just reference them as you need them.
> 1 votes

# Answer
Half answer to your unclear question. In order to truly understand the **Resource.Load** you need to consider these points.

1. If you put it all in Resource directories then it will be included in the build - no matter if you stop using it - normally only assets that are actually being used in a built scene will be included in the actual executable. So putting everything in Resources is a bit of a nightmare because you have to work out whether you are still using things or your executable starts to fill with wasted stuff - big problem on phones.
2. Used for loading assets that are rarely used so that they are not loaded as part of any of the scenes. " For example, there may be a character or other object that can appear in any scene of the game but which will only be used infrequently (this might be a "secret" feature, an error message or a highscore alert, say). ", says Unity
3. If you want WebPlayers to load a game quickly then you can make a lightweight scene that loads only the minimum required assets, then use Resources.load as needed to load the remaining assets. (for more)
> 0 votes

# Answer
You can also use player prefs to store data. This will also carry on between plays, although the downside is that it's a bit slow to access and you can't save loads of data types

```
//You can get data from player prefs like:
m_Health = PlayerPrefs.GetFloat("Health", 0);
//And set it like:
m_Health = PlayerPrefs.SetFloat("Health",100);

```
> -2 votes

---
Tags: unity, assets, resource-management
---


# Question
Title: How do I make buttons function on the cursors click in roblox studio?
I would just like to know how to add buttons in roblox studio because when I play roblox and see all those great games with buttons that I can click! How do I make a button, and how do I make it work?

# Answer
> 2 votes
According the the Roblox developer website, you can create a button by right clicking in the Explorer window and clicking the button you want. There are two types of buttons as described on the website.

> **Text Button:** A TextButton is very similar to a TextLabel, except that a player can activate it with a click. Internally, it also shares many of the same visual properties as a text label — font, background color, stroke color, etc.
>
> **Image Button:** Similarly, an ImageButton is like an interactive version of the ImageLabel object and it uses a custom image that you upload to Roblox. It also shares most of the same properties as its non-button counterpart.

In order to add a function that occurs when a button is pressed, simply create a local script inside the button and add this code:

```
function leftClick()
    print("You can replace this line with any function you want on a left click.")
end

script.Parent.MouseButton1Click:Connect(leftClick)

```

For more information on GUI buttons in Roblox, go to their official website here.

---
Tags: gui, roblox
---


# Question
Title: Sever-side physics simulation and client 'inputs' send rate in a fast multiplayer game
I am building a very tiny first-person multiplayer game. I'm just aiming to get the basic rights: client-side prediction and reconciliation + entity interpolation. I have read many articles on these topics but I have a question that I can't find answer for. Consider the following problem:

* There's a queue on the server where the client inputs are stored (movement keys + camera vectors)
* Server runs the physics simulation 60 times per second. This means that each input from a client will be simulated for 16.6 ms.

Now, consider that I have two clients: one with a beefy computer able to run the game loop 100 times per second, and a slower one that is only able to run it 30 times per second.

My game will send the 'client inputs' packet to the server on every iteration of the game loop. This means that the 100 fps client will send 100 packets, while the 30 fps client only 30.

What this means is that the fast client will get more simulation time on the server, since each input is simulated for 16ms. So the fast client will move significantly more than the slower client.

What is the appropriate way to design the 'client input' packet send rate? What is a solution that ensures that fast clients and slow clients receive an equal or roughly equal amount of simulation time?

Thanks for your time!

# Answer
> 1 votes
I had this exact same issue with my multiplayer game engine. As others have pointed out you could decouple the rendering and simulation on the client side to keep the client side simulation at a consistent tick rate, but I still wanted my system to be resilient against fluctuating tick rate on both the server and clients.

My solution was to include the tick-duration of the client on each input message that was sent to the server. The server will then make sure to simulate the clients input message for the time specified in the message.

---
Tags: multiplayer, game-loop, client-server, movement-prediction
---


# Question
Title: How do I get roblox studio on a Chromebook?
I have seen Youtube videos of people having roblox studio on their chromebook, but I have tried to install it and it didn't work.

How can I get it to work?

# Answer
> 1 votes
Currently, you cannot natively install Roblox onto a Chromebook, due to the lack of Linux support, but you can still run it using an emulator such as **Grapejuice**. Here's how to do that.

1. Make sure the Chromebook is set up to use Linux applications.
2. Use this command in the terminal for 32-bit support: `sudo dpkg --add-architecture i386`
3. Next, install WINE, a Windows application emulator using this command: `sudo apt install -y wine git python3-pip pkg-config libcairo2-dev libdbus-1-dev gtk-update-icon-cache desktop-file-utils xdg-utils libgirepository1.0-dev gir1.2-gtk-3.0`
4. Next, get the files for Grapejuice with this command, which allows Roblox Studio to run on Linux: `git clone https://gitlab.com/brinkervii/grapejuice.git`
5. Finally, run these two commands to install Roblox Studio and Grapejuice: `cd grapejuice` and lastly, `python3 ./install.py`

Although this will function, **some areas of the application will not work as well (or at all) as they would on a native machine.** Here is the official project information on Grapejuice here.

---
Tags: roblox
---


# Question
Title: My Circle Collider 2D can't pass through Edge Collider 2D
I'm trying to make Flappy Bird, but when I put an `EdgeCollider2D`on the Pipe, the bird can't pass through the collider and gets stuck.

Bird code:

```
{
    Rigidbody2D Rb;
    public float jumpForce;

    float score;

    void Start()
    {
        Rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Rb.velocity = Vector2.up * jumpForce;
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.gameObject.tag=="Point")
        {
            score++;
        }
    }
}

```

# Answer
As far as I am understanding your question, you are trying to give the player a point when he collides with the collider in between the pipes. Just simply add the “Point” tag to your GameObject with the EdgeCollider2D attribute. Then, set the **IsTrigger** box to checked. This makes it trigger the `OnTriggerEnter2D(Collider2D other)` method on collision instead of colliding with the player.
> 0 votes

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


# Question
Title: What sounds need to be transcripted when using Closed Captions?
I have no experience with captioning, but we are developing a game and we want to make it as accessible as possible so we thought of 2 levels of subtitles: dialogues and Closed Captions (dialogues + sound effects).

The problem I can think of is what sounds need to be transcripted in Closed Captions? All sounds of the game could clutter the screen with subtitles and distract the player. Too few sounds and the player could miss some details.

For example we could have an electric door which makes some sound when opened or closed, this kind of sound should be transcripted always? Or just the first time it's encountered, and then the user will know that all the similar doors should make the same sound? And is it too much to put 2 subtitles (one for opening, one for closing)?

# Answer
The main question to ask is: would a player hearing this sound play differently as a result?

If so, that's a strong clue that the sound is carrying relevant gameplay information.

Take the example of the electrical door sound. If that sound could alert me to the fact that an enemy has just entered the room off-screen, then that could be a very important thing to know, and you'd want to find some way to convey that information without sound too (though that doesn't necessarily have to be through captions - a nearby enemies pointer or minimap could also address this potential barrier).

Here's what Game Accessibility Guidelines says on the matter:

> Communicating all sound by text is usually neither practical or desirable, but anything that’s **important** should be. To judge this, consider whether the sound could be totally removed without much impact to story, gameplay or atmosphere. If not, reinforce them with either captions or visuals.
> 3 votes

---
Tags: accessibility, subtitles
---


# Question
Title: Problem with Parameters for polymorphism class
This is going to be a bit tricky but it is really bothering me so I hope you will have the patience to follow along :)

Here is my very basic architecture:

So in the framework, I am creating I have `Actions` these currently have a list of `Conditions` or Considerations (same thing different name).

While each `Condition` share some of the same functionality such as:

* Returning a float score
* Using an evaluation formula

They implement these in very different ways depending on the situation.

Take a look at the following code:

```
[CreateAssetMenu(fileName = "Consider my health vs max health",
    menuName = "AnAppGames/AI/Example/Decisions/Health Consideration")]
public class MyHealth : BaseConsideration
{
    private float health;
    public float maxHealth;

    public override float Consider<T>(BaseAiContext context, BaseAction action, T value)
    {
        health = value as float;
        return EvaluateValues(health / maxHealth);
    }

}

```

What you are looking at is my first attempt at making some sort of "reusable" `Consideration`.

Now in the continuation of my development, I had to make the following `Consideration`:

```
public class DistanceFromMe : BaseConsideration
{
    public float minRange;
    public float maxRange;

    private float ConsiderWithValues(Transform target, Transform caller)
    {
        return EvaluateValues(new FloatData(Vector3.Distance(target.transform.position, caller.position),
            minRange,
            maxRange).GetNormalizedData());
    }

    public override float Consider<T>(BaseAiContext context, BaseAction action, T value)
    {
        Transform target = value as Transform;
        if (target == null)
        {
            return 0;
        }
        return ConsiderWithValues(target.transform, context.transform);
    }

    public override float Consider(float x)
    {
        return EvaluateValues(new FloatData(x,
            minRange,
            maxRange).GetNormalizedData());
    }

}

```

And now the trouble begins I thought "This is not a scaleable solution" as soon as I need more than 1 generic parameter I am screwed and have to create additional overrides of this `Consider` function.

So what I need is somehow to add different types of parameters to the `Consideration` however these parameters will vary a lot.

Another problem I have with this is that when I loop through the list I won't be able to tell what parameters i needed and how to fulfill the needs of the `Consideration`.

I thought of different ways of dealing with this inside the editor but I have come up empty :(

Can anyone help me out with this architectural mess? :)

It is worth mentioning that at the current point each of these are ScriptableObjects I am not 100 set in the fact that they should be but i am just not sure how to deal with this problem.

# Answer
> 2 votes
You aren't using generics correctly.

```
public override float Consider<T>(BaseAiContext context, BaseAction action, T value)
{
    health = value as float;
    return EvaluateValues(health / maxHealth);
}

```

This function takes a generic type `T` but expects `T` to be a float. If the function only works if `T` is a float, the function should not be generic.

It's hard to grasp the bigger picture because there's no relation between your diagram and your example code, and you haven't shown how you are using the "considerations". My impression is that you are going about the architecture entirely the wrong way. You should use abstraction and polymorphism when they make sense, not just for the sake of using them.

You could do this, but I think this is making your code pointlessly complex, and it doesn't work with multiple values:

```
abstract public class BaseConsideration<T> {
    abstract public float Consider(BaseAiContext context, BaseAction action, T value);
    public float EvaluateValues(float value) {
        //etc
    }
}

public class MyHealth : BaseConsideration<float>
{
    private float health;
    public float maxHealth;

    public override float Consider(BaseAiContext context, BaseAction action, float value)
    {
        health = value;
        return EvaluateValues(health / maxHealth);
    }
}

```

You might try something more like this, defining the conditions on each type of action:

```
public interface IHealth {
    int HP { get; set; }
    float NormalizedHP { get; }
    bool IsAlive { get; }
}

abstract public class Action {
    abstract public bool ShouldBegin();
    abstract public void Begin();
}

public class GetHealthAction {
    public float NormalizedHPThreshold { get; set; } = .2f;
    public IHealth Health { get; set; }
    override public bool ShouldBegin() {
        return Health.NormalizedHP  < NormalizedHPThreshold;
    }
    override public void Begin() {
       //etc
    }
}

```

or you could do it this way if you prefer the conditions to be defined in reusable classes (it doesn't make sense to use ScriptableObjects here):

```
abstract public class Condition {
    abstract public bool Evaluate();
}

//C# might already have a built-in enum like this somewhere
public enum Comparison {
    Less, LEqual, Greater, GEqual, Equal, NEqual
}

public class FloatCondition : Condition {
    public float Threshold { get; set; }
    public float CurrentValue { get; set; }
    public Comparison Comparison { get; set; }
    override public bool Evaluate() {
        if (Comparison == Comparison.Equal) return CurrentValue == Threshold;
        else if (Comparison == Comparison.Less) return CurrentValue < Threshold;
        //etc etc
    }
}

public class HealthCondition : FloatCondition {
    public IHealth Health { get; set; }
    override public bool Evaluate() {
        CurrentValue = Health.NormalizedHP;
        return base.Evaluate();
    }
}

abstract public class Action {
    [SerializeField] private List<Condition> conditions = new List<Condition>();
    public bool ShouldBegin() {
        foreach (var condition in conditions) {
            if (!condition.Evaluate()) return false;
        }
        return true;
    }
    abstract public void Begin();
}

public class FindHealthAction : Action {
    public FindHealthAction(IHealth entity) {
        var condition = new HealthCondition();
        condition.Health = entity;
        condition.Comparison = Comparison.Less;
        condition.Threshold = .2f;
    }
    override public void Begin() {
        //etc
    }
}

```

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


# Question
Title: Shading a concave cube as a convex cube with forced perspective
## Context

I'm building a graphics pipeline for voxel volumes. I'm using an existing game engine (Bevy) which provides a way to put an object in 3D space. In my application, the voxel volumes can be oriented arbitrarily and are not necessarily axis aligned with respect to the world space. The pipeline does front-face culling of these voxel volumes to allow the camera to go inside the bounds of the volume without clipping (imagine a player walking into a sparsely populated volume and looking around). The voxel volumes are rendered using ray marching, starting from a ray's contact point with the front face of the voxel volume.

## The Problem

Now of course, this works if there are front faces, but as I said I'm culling them. So what really happens is my frag shader is shading the near side of the cube's back faces. What I need to do is: given the point of contact with the cube's back face, and the direction to the camera, find the point that would have been hit on the front face. This will allow the rest of the program to ray march as though the ray hit a "convex" cube. I've spent quite a while looking at this answer but so far I've been unable to implement it into my shader -- I think it's relevant: https://stackoverflow.com/questions/4248090/finding-the-length-of-a-ray-within-a-cube

**Assumptions:**

* Voxel volume axes are perpendicular to each other, but are not necessarily the same length
* A ray from the camera to a back face can hit any one of the 3 back faces, and will only pass through any one of the 3 front faces

## Expected Result

Here's an example of what I expect. Below (first image) is what is rendered without "simulating" the front face positions. The second image is what would be rendered with correct front face simulation.

## Partial Code

I've removed the irrelevant code. Right now what is rendered for a voxel\_volume\_size = (16, 16, 16) is 3 16x16 walls along the axes. Of course what *should* be seen is a 16x16x16 voxel cube.

**voxel.vs**

```
#version 450

layout(location = 0) in vec3 Vertex_Position;
layout(location = 1) in vec3 Vertex_Normal;
layout(location = 2) in vec2 Vertex_Uv;

layout(location = 0) out vec3 v_Position;
layout(location = 1) out vec3 v_Normal;
layout(location = 2) out vec2 v_Uv;

layout(set = 0, binding = 0) uniform Camera {
    mat4 ViewProj;
    mat4 View;
};

layout(set = 1, binding = 0) uniform Transform {
    mat4 Model;
};

void main() {
    v_Normal = Vertex_Normal;
    v_Position = Vertex_Position;
    v_Uv = Vertex_Uv;
    gl_Position = ViewProj * vec4((Model * vec4(Vertex_Position, 1.0)).xyz, 1.0);
}

```

**voxel.fs**

```
#version 450

layout(location = 0) in vec3 v_Position;
layout(location = 1) in vec3 v_Normal;
layout(location = 2) in vec3 v_Uv;

layout(location = 0) out vec4 o_Target;

layout(set = 0, binding = 0) uniform Camera {
    mat4 ViewProj;
    mat4 View;
};

layout(set = 1, binding = 0) uniform Transform {
    mat4 Model;
};

layout(set = 3, binding = 0) buffer VoxelVolume {
    vec3 voxel_volume_size;
};

void main(void) {
    vec3 Normal = mat3(Model) * v_Normal;

    vec3 scale = voxel_volume_size / 16.0;

    mat4 InverseView = inverse(View);
    vec3 CameraPosition = (Model * vec4(vec3(InverseView[3]), 0.)).xyz;

    vec3 BackFacePosition = v_Position;
    vec3 BackFaceModelPosition = (Model * vec4(BackFacePosition, 1.0)).xyz;
    vec3 BackFaceRayDirection = normalize(BackFaceModelPosition - CameraPosition);

    vec3 FrontFacePosition = ?;
    vec3 FrontFaceRayDirection = ?; // Differs from BackFaceRayDirection when front face is perpendicular to back face

    vec3 ScaledPosition = ((FrontFacePosition + (scale / 2.0)) / scale) * voxel_volume_size;

    o_Target = vec4(floor(ScaledPosition) / voxel_volume_size, 1.0);
}

```

I would be extremely grateful if someone could help me fill in those missing variables! Thanks.

# Answer
I ended up solving this with a little of guesswork. I suppose this can be optimized further.

---

## Matrix setup

First, some mental health. I declared a `convert` function:

```
vec3 convert(mat4 matrix, vec3 vector)
{
    return (matrix * vec4(vector, 1.0)).xyz;
}

```

And then in the fragment shader I have my matrices like this:

```
    mat4 ModelToWorld = Model;
    mat4 WorldToModel = inverse(Model);
    mat4 CameraToWorld = inverse(View);
    mat4 WorldToCamera = View;
    mat4 ModelToCamera = WorldToCamera * ModelToWorld;
    mat4 CameraToModel = WorldToModel * CameraToWorld;

```

I will prefix the variables with the space in which they are. For example:

```
    vec3 Model_BackFacePosition = v_Position;

```

And if I want that in Camera space I do this:

```
    vec3 Camera_BackFacePosition = convert(ModelToCamera, Model_BackFacePosition);

```

This is somewhat verbose, but it is less error prone. I can see if I'm converting from the wrong space using the wrong matrix. Or if I'm mixing vectors of different spaces unintentionally.

Makes sense? Ok.

---

## Solution

We know:

```
    vec3 Model_BackFacePosition = v_Position;

```

That the is position, in model coordinates, we got from the vertex shader.

We also know that:

```
    vec3 Camera_RayOrigin = vec3(0.0, 0.0, 0.0);

```

Because the origin of the ray is the camera. And the position of the camera respect to the camera is 0. Let us pass that to Model space:

```
    vec3 Model_RayOrigin = convert(CameraToModel, Camera_RayOrigin);

```

And we also need the direction of the ray, which we get like this:

```
   vec3 Model_RayDirection = normalize(Model_BackFacePosition - Model_RayOrigin);

```

---

Now we need to figure out the normals of the front faces. There are at most three front faces (at least one). And they are aligned to the axis *in Model space*. So let us get them in Model space.

```
    vec3 Model_XN = vec3(-sign(Model_RayOrigin.x), 0.0, 0.0);
    vec3 Model_YN = vec3(0.0, -sign(Model_RayOrigin.y), 0.0);
    vec3 Model_ZN = vec3(0.0, 0.0, -sign(Model_RayOrigin.z));

```

As you can see, we are taking normals for the faces that go in the opposite direction of the ray. Those are the front faces.

Now let us figure out where the ray intersect the models. For that I'll be using the algebraic method for Ray-Plane Intersection, which looks like this:

```
    Ray   -> P = RayOrigin + t * RayDirection
    Plane -> P · N + d = 0
=>
    t = -(RayOrigin · N + d) / (V · N)
    P = RayOrigin + t * RayDirection

```

We, of course, do that for each of the three front planes, which looks like this:

```
    float Xd = -0.5;
    float Yd = -0.5;
    float Zd = -0.5;

    float Xt = -(dot(Model_RayOrigin, Model_XN) - Xd) / dot(Model_RayDirection, Model_XN);
    vec3 Model_PX = Model_RayOrigin + Xt * Model_RayDirection;

    float Yt = -(dot(Model_RayOrigin, Model_YN) - Yd) / dot(Model_RayDirection, Model_YN);
    vec3 Model_PY = Model_RayOrigin + Yt * Model_RayDirection;

    float Zt = -(dot(Model_RayOrigin, Model_ZN) - Zd) / dot(Model_RayDirection, Model_ZN);
    vec3 Model_PZ = Model_RayOrigin + Zt * Model_RayDirection;

```

---

This is where we get to the guesswork. I needed a way to check which plane is the correct one to use. My first guess was it would be the one further from the camera. And that is correct when we have all three front planes.

We can reuse `Xt`, `Yt` and `Zt` (which are distance along the ray) to figure out which point if further away from the camera. But we also need to discard the planes that we don't need. Since we want the further away, we can discard them by making the value 0. By trial and error I got it working like this:

```
    float Check_X = Xt * sign(floor(abs(Model_RayOrigin.x) * 2.0));
    float Check_Y = Yt * sign(floor(abs(Model_RayOrigin.y) * 2.0));
    float Check_Z = Zt * sign(floor(abs(Model_RayOrigin.z) * 2.0));

```

We, of course, still need to pick the one with greater value. Which will mean branching. If you can optimize the guesswork and the branching, kudos to you.

I also introduced a check to see if all these are greater than zero. If none of them are, it means the camera is inside the voxel volume.

```
    vec3 best = Model_BackFacePosition;
    if (Check_X > 0.0 || Check_Y > 0.0 || Check_Z > 0.0)
    {
        best = Model_PX;
        float best_length = Check_X;
        if (Check_Y > best_length)
        {
            best = Model_PY;
            best_length = Check_Y;
        }
        if (Check_Z > best_length)
        {
            best = Model_PZ;
        }
    }

```

Finally, you get your output:

```
    vec3 center_offset = vec3(0.5, 0.5, 0.5);
    vec3 ScaledPosition = (best + center_offset) * voxel_volume_size;
    vec4 o_Target = vec4(floor(ScaledPosition) / voxel_volume_size, 1.0);

```

---

At the end, I only used `convert` once. And the matrix I used with it was `CameraToModel`, which is `inverse(Model) * inverse(View)` (consider passing that as uniform). Replacing that into the code, this is the final code listing:

```
    mat4 CameraToModel = inverse(Model) * View;

    vec3 Camera_RayOrigin = vec3(0.0, 0.0, 0.0);
    vec3 Model_BackFacePosition = v_Position;
    vec3 Model_RayOrigin = (CameraToModel * vec4(Camera_RayOrigin, 1.0)).xyz;
    vec3 Model_RayDirection = normalize(Model_BackFacePosition - Model_RayOrigin);

    vec3 Model_XN = vec3(-sign(Model_RayOrigin.x), 0.0, 0.0);
    vec3 Model_YN = vec3(0.0, -sign(Model_RayOrigin.y), 0.0);
    vec3 Model_ZN = vec3(0.0, 0.0, -sign(Model_RayOrigin.z));

    float Xd = -0.5;
    float Yd = -0.5;
    float Zd = -0.5;

    float Xt = -(dot(Model_RayOrigin, Model_XN) - Xd) / dot(Model_RayDirection, Model_XN);
    vec3 Model_PX = Model_RayOrigin + Xt * Model_RayDirection;

    float Yt = -(dot(Model_RayOrigin, Model_YN) - Yd) / dot(Model_RayDirection, Model_YN);
    vec3 Model_PY = Model_RayOrigin + Yt * Model_RayDirection;

    float Zt = -(dot(Model_RayOrigin, Model_ZN) - Zd) / dot(Model_RayDirection, Model_ZN);
    vec3 Model_PZ = Model_RayOrigin + Zt * Model_RayDirection;

    float Check_X = Xt * sign(floor(abs(Model_RayOrigin.x) * 2.0));
    float Check_Y = Yt * sign(floor(abs(Model_RayOrigin.y) * 2.0));
    float Check_Z = Zt * sign(floor(abs(Model_RayOrigin.z) * 2.0));

    vec3 best = Model_BackFacePosition;
    if (Check_X > 0.0 || Check_Y > 0.0 || Check_Z > 0.0)
    {
        best = Model_PX;
        float best_length = Check_X;
        if (Check_Y > best_length)
        {
            best = Model_PY;
            best_length = Check_Y;
        }
        if (Check_Z > best_length)
        {
            best = Model_PZ;
        }
    }

    vec3 center_offset = vec3(0.5, 0.5, 0.5);
    vec3 ScaledPosition = (best + center_offset) * voxel_volume_size;
    vec4 o_Target = vec4(floor(ScaledPosition) / voxel_volume_size, 1.0);

```

---

## Addendum: Optimizing

When we do dot product, we are taking the sum of the component wise product. Now look at how we defined `Model_XN`, `Model_YN` and `Model_ZN`. They only have one non-zero component. Thus we can replace the dot products with simple products on the corresponding components. While we are at it, let us make it a single vector `Model_N`.

We also have these `Xd`, `Yd`, and `Zd`. Make them into a vector `d`. Which also happens to be `-center_offset`.

Now, this code (I'm skipping `Model_PX`, `Model_PY`, and `Model_PZ`, soon we will not need them):

```
    vec3 Model_XN = vec3(-sign(Model_RayOrigin.x), 0.0, 0.0);
    vec3 Model_YN = vec3(0.0, -sign(Model_RayOrigin.y), 0.0);
    vec3 Model_ZN = vec3(0.0, 0.0, -sign(Model_RayOrigin.z));

    float Xd = -0.5;
    float Yd = -0.5;
    float Zd = -0.5;

    float Xt = -(dot(Model_RayOrigin, Model_XN) - Xd) / dot(Model_RayDirection, Model_XN);
    float Yt = -(dot(Model_RayOrigin, Model_YN) - Yd) / dot(Model_RayDirection, Model_YN);
    float Zt = -(dot(Model_RayOrigin, Model_ZN) - Zd) / dot(Model_RayDirection, Model_ZN);

```

Looks like this:

```
    vec3 Model_N = -sign(Model_RayOrigin);
    vec3 d = -center_offset;

    float Xt = -(Model_RayOrigin.x * Model_N.x - d.x) / (Model_RayDirection.x *  Model_N.x);
    float Yt = -(Model_RayOrigin.y * Model_N.y - d.y) / (Model_RayDirection.y *  Model_N.y);
    float Zt = -(Model_RayOrigin.z * Model_N.z - d.z) / (Model_RayDirection.z *  Model_N.z);

```

Well, make `Xt`, `Yt` and `Zt` a vector `t`, and we can write that like this:

```
    vec3 Model_N = -sign(Model_RayOrigin);
    vec3 d = -center_offset;
    vec3 t = -(Model_RayOrigin * Model_N - d) / (Model_RayDirection * Model_N);

```

We were using the old `Xt`, `Yt` and `Zt` to do so. With some added factors. Let us make those factors a vector too. So write this:

```
    vec3 f = sign(floor(abs(Model_RayOrigin) * 2.0));

```

Ok, those could be a vector too.. But wait! Why don't we just pick the best right away?

```
    float best_t = max(max(t.x * f.x, t.y * f.y), t.z * f.z);

```

Now the code inside the conditional can look like this (and we don't need `Model_PX`, `Model_PY` and `Model_PZ` anymore):

```
    best = Model_RayOrigin + best_t * Model_RayDirection;

```

This is how the code looks like now:

```
    mat4 CameraToModel = inverse(Model) * inverse(View);

    vec3 Camera_RayOrigin = vec3(0.0, 0.0, 0.0);
    vec3 Model_BackFacePosition = v_Position;
    vec3 Model_RayOrigin = (CameraToModel * vec4(Camera_RayOrigin, 1.0)).xyz;
    vec3 Model_RayDirection = normalize(Model_BackFacePosition - Model_RayOrigin);

    vec3 center_offset = vec3(0.5, 0.5, 0.5);

    vec3 Model_N = -sign(Model_RayOrigin);
    vec3 d = -center_offset;
    vec3 t = -(Model_RayOrigin * Model_N - d) / (Model_RayDirection * Model_N);
    vec3 f = sign(floor(abs(Model_RayOrigin) * 2.0));
    float best_t = max(max(t.x * f.x, t.y * f.y), t.z * f.z);
    vec3 best = Model_BackFacePosition;
    if (f.x > 0.0 || f.y > 0.0 || f.z > 0.0)
    {
        best = Model_RayOrigin + best_t * Model_RayDirection;
    }

    vec3 ScaledPosition = (best + center_offset) * voxel_volume_size;
    vec4 o_Target = vec4(floor(ScaledPosition) / voxel_volume_size, 1.0);

```

---

## Godot

By the way, I used Godot to write the shader, so I could go straight to it (just add a mesh instance with a shader material, start typing and see the changes in real time). Godot shader language is based on GLSL, with some minor differences. This is the glue code I used:

```
shader_type spatial;
render_mode unshaded, cull_front;
uniform vec3 voxel_volume_size;

void fragment()
{
    mat4 View = INV_CAMERA_MATRIX;
    mat4 Model = WORLD_MATRIX;
    vec3 v_Position = (inverse(WORLD_MATRIX) * CAMERA_MATRIX * vec4(VERTEX.xyz, 1.0)).xyz;

    // THE CODE ABOVE HERE

    ALBEDO = o_Target.xyz;
}

```

And this is how it looks in engine:

Cheers!
> 2 votes

---
Tags: shaders, fragment-shader, voxels
---


title: How to add time delay in Unity C#

text:
# Question
Title: How to add time delay in Unity C#
So I'm trying to make a camera zoom in, but `Thread.Sleep` doesn't work. Here is the code:

```
    void Start() {
    for (int a = 0; a > 1000; a = a + 1)
    {
        Debug.Log("Done!");
        Thread.Sleep(100);
    }
}

```

The error code is this:

```
Assets\StartScene\CamScript.cs(12,13): error CS0103: The name 'Thread' does not exist in the current context

```

# Answer
> -3 votes
You are getting this error message because you are missing a line that accesses the API for this. Simply add `using System.Threading;` at the top of your script. This will access the API for it. Or **use a coroutine**, which won’t freeze the entire game as a whole and is a much better alternative, as DMGregory suggested.

# Answer
> 5 votes
You want a Coroutine.

```
// IEnumerator tells Unity to run this as a coroutine
// that can suspend and wait, without stalling the whole game.
IEnumerator Start() {
    // Your loop condition was backwards,
    // so it would never execute the body.
    // It looks like you want a < here instead.
    for (int a = 0; a < 1000; a++)
    {
        Debug.Log("Done!");
        // yield return means "suspend this method"
        // and the WaitForSeconds tells us when to resume it.
        yield return new WaitForSeconds(0.1f);
    }
}

```

An important thing to understand about Unity is that the `MonoBehaviour` message methods like `Start()` and `Update()` are called on the main thread (ie. single-threaded). So if you stall one of them by hitting a long-running loop or sleeping the thread, you cause the entire game to hang.

So, if you want to add a delay, it needs to be by `yield`ing control back to the engine temporarily - so it can continue running other update functions, accepting input, rendering frames, etc. - until you are ready to resume your work.

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


# Question
Title: Unreal virtual function causing unresolved external error
I'm making a base gun cpp class that just has the stuff all the other guns will have. I have a virtual function called PullTrigger that doesn't do anything, I just want to have it on the base gun so i can implement it on the derived classes without recreating it. in my header file under private, I have this code

```
virtual void PullTrigger();

```

I tried adding override after the parantheses, but it gave me an error. As is, VS is uncomplaining, but Unreal says the function has an "Unresolved external symbol". I have no clue what that is. How do i fix this?

# Answer
An Unresolved External Symbol usually means that although you have declared the function in the header, you haven't created it in the CPP file.
> 1 votes

---
Tags: unreal-4, error-management
---