# Question
Title: How can I round out the corners of a quad in OpenGL?
Even though I think the image is pretty self-explanatory, I'm going to explain what I am trying to achieve:

I was working on a game, and I needed a GUI framework, that I decided to build myself. As a first thing, I tried rendering a simple 2d quad with an orthographic projection. I was not satisfied with the boxy shapes windows had, so I tried fixing the problem by adding a texture; all this worked until I tried implementing resizing: whenever I changed the window size, the texture was warping, and it did not look good. Now I'm trying to use more than just two triangles, to smooth the corners of the windows. Now, my question is: how can I determine the number of triangles each window should have to have in order to obtain smoother corners? I would like to have some sort of "smooth" variable, that specifies how smooth(how many triangles are used) the window is. Thanks everyone for the help

EDIT:

I was thinking about this: do you guys think that generating the vertices of the window based on a condition in real time would be a good idea?

something like(proto code):

```
if(smooth == 1)
{
    //define quad vertices
    float vertices[] =
    {
       bla,bla,
       bla,bla,
       bla,bla....
    }
}

if(smooth == 2)
{
    float vertices[] =
    {
       bla,bla,
       bla,bla,
       bla,bla....
    }
}

```

In a way, this would work, but I'm pretty sure there is a much better way to do this...

# Answer
> 12 votes
This is not technically an answer to your question, but is a better work around in my opinion.

You can pass the dimensions of the boxes and the radius of the corners to the fragment shaders and round the corners that way.

Basically, you take the current texture coordinates, multiply each coordinate of it by the dimensions of the window to get the coordinates of the current fragment relative to the window. Then if the distance between this position and each of the edges is less, than the radius of the corner, then you throw it away.

This way you don't need to upload separate vertices for each window.

Sample code in GLSL (I don't know what you're using)

```
in vec2 a_uv;

uniform vec2 u_dimensions;
uniform float u_radius;

void main(void) {
    vec2 coords = a_uv * u_dimensions;
    if (length(coords - vec2(0) < u_radius ||
        length(coords - vec2(0, u_dimensions.y) < u_radius ||
        length(coords - vec2(u_dimensions.x, 0) < u_radius ||
        length(coords - u_dimensions) < u_radius) {
        discard;
    }
    // Do everything else otherwise
}

```

# Answer
> 2 votes
The main problem with drawing round 2D objects using 3D geometry is that there's no real fixed mapping between the pixels on the screen and the 3D world-space. Making sure they look at all resolutions and various transformations can get really tricky real fast, and you don't really want to spend time on something that doesn't really improve the game quality. But you're right that you can't stretch a single texture and get a good effect either.

One typical way this is done in 2D GUIs is 9-sliced scaling. Instead of having one logical texture, you have nine - one for each corner, one for each edge and one for the rest. The corners aren't scaled at all, only moved to their proper place. The edges are repeated (or sometimes scaled) in their proper direction (e.g. the top edge will be repeated in the X-direction). The center is repeated in both directions. This allows you to resize the window at will.

If you want to keep 3D geometry, pixel shaders sound like the best way to go - after all, you're trying to scale the effect to the *screen*, not the world-space. Drawing a simple circle section is trivial with just a bit of math, though making sure you get good looking anti-aliasing etc. can make this trickier. The main advantage over the texture method is you can arbitrarily scale it without stretching the textures; the main disadvantage is that you'll only ever do very simple patterns (and the more complicated the pattern, the more taxing to the GPU). Of course, you can also combine both approaches - have a texture that's applied to the "solid" parts of the window but not the transparent parts, and repeated as needed.

# Answer
> 0 votes
I'll extend on Bálint's excellent answer by adding my own idea of a possible fragment-shaded approach:

```
in vec2 vUV;

uniform vec2 uExtents;
uniform float uRadius;

float calcDistance() {
    vec2 coords = abs(vUV) * (uExtents + uRadius);
    vec2 delta = max(coords - uExtents, 0);
    return length(delta);
}

void main() {
    float dist = calcDistance();
    if (dist > uRadius) discard;
    /* ... */
}

```

Here I take as inputs the vertex UV `vUV ∈ [-1, 1] × [-1, 1]`, rectangle extents `uExtents = (width/2, height/2)`, and the corner radius `uRadius`. From these we produce a distance to the rectangle where `0` represents inside and all other (positive) values represent outside.

---
Tags: opengl, c++, glsl, gui
---


# Question
Title: A Native Collection has not been disposed, resulting in a memory leak. Enable Full StackTraces to get more details
`A Native Collection has not been disposed, resulting in a memory leak. Enable Full StackTraces to get more details.`

In working on saving to file the `NativeArrays` used to fetch BlendShapeCoefficients in ARFoundation, I encountered the error above.

How does one enable the type of full stack trace this error requires to decipher where things went wrong?

* I tried the full stack checkboxes on the bottom of Player Settings, but it still does not reveal further details.
* I have tried to `.Dispose()` both upon beginning a new recording and on saving. Calling .Dispose led to another error `InvalidOperationException: The NativeArray has been deallocated, it is not allowed to access it`
* I also tried using brackets `[DeallocateOnJobCompletion]` above the NativeArray variable declarations (still occurs)

# Answer
> 12 votes
**Unity 2020+**, in it's infinite wisdom, removed the ability for you to easily find the cause for this message. They provided a workaround, but as you will see following these steps, it is extremely hacky:

* Go Window -\> Package Manager
* Click the `+` icon at the topleft, select `add package from git URL`
* Enter `com.unity.jobs` (It's not a git URL, but that's what Unity wants you to do)

You now have the `Jobs` tab at the top of your Editor.

* Go Jobs -\> Leak Detection -\> Full Stack Traces (Expensive)
* Close and open the editor again, then rerun the game

# Answer
> 2 votes
> How does one enable the type of full stack trace this error requires to decipher where things went wrong?

Jobs \> Leak Detection \> Full Stack Traces

When you do this, instead of getting "just" an error that there was **a** memory leak, it will also tell you on which line the thing that's leaking was allocated. This can help you determine which script is creating the memory leak and which part of that script is leaking.

As for *when* you should dispose - you do it when you're done with the thing. Part of when you're "done" with it will depend on what Allocator you're using; Temp, Persistent, etc.

# Answer
> 2 votes
in the 2022 version it's moved to the Preferences/Jobs tab

# Answer
> 0 votes
get package com.unity.entities then you can enable the full stack traces option in menu. which will eventually tell you the reason of leakage.

---
Tags: unity, debugging
---


# Question
Title: How to animate a Text Mesh Pro font color transition in Unity when the initial color is unknown?
I have some text where different letters can be different colors:

I'd like to use the Animation feature to transition each letter frame-by-frame until they are white, like this:

The challenge is that each letter is made using a Prefab ("White Letter"), where the Text Mesh Pro Font Color starts off as White. So the Animation tab looks like this, with the RGBA values all set to 1:

After the prefab is instantiated, then the start values for the Font Color look like this:

I'd like to have the initial RGBA values of the Font Color to be "whatever the current color is" and then transition all of the Font Colors to white.

Is it possible to have the Animation tab start values initialize as the current Font Color of the GameObject?

# Answer
Hackish solution:

Put two texts on top of each other, with the only difference that the one on top is colored and the one below is white. So the colored text completely obscures the white text. Then animate the alpha-property of the colored text to go from 1 to 0, so the white text becomes more visible.
> 2 votes

---
Tags: unity, text-mesh-pro
---


# Question
Title: GrooveJoint2D - why does the Godot editor enforces a minimum value of 1 for initial_offset?
When you add a `GrooveJoint2D` to the scene tree, the Godot editor limits the minimum value of the `initial_offset` property to `1 px`:

The documentation doesn't say anything about a minimum value of `1`.

Setting the property to zero through code *before* assigning `node_a` and `node_b` seems to work though and doesn't exhibit any adverse effect for my use case.

```
$MyGrooveJoint.initial_offset = 0
$MyGrooveJoint.node_a = $MyNodeA.get_path()
$MyGrooveJoint.node_b = $MyNodeB.get_path()

```

Still there might be cases where an `initial_offset` of `0` could cause problems, which I'd like to know.

# Answer
An `initial_offset` of `0.0` is OK.

*The rest of this answer is how I confirmed that.*

---

A good excuse to check the source code.

We find `initial_offset` declared like this (source):

```
real_t initial_offset = 25.0;

```

And looking for usage (in joint\_2d.cpp) does not reveal any issue with it bean zero. However, it is used to compute a variable `anchor_B` which is passed to `joint_make_groove` in `joint_make_groove` (source):

```
void GrooveJoint2D::_configure_joint(RID p_joint, PhysicsBody2D *body_a, PhysicsBody2D *body_b) {
    Transform2D gt = get_global_transform();
    Vector2 groove_A1 = gt.get_origin();
    Vector2 groove_A2 = gt.xform(Vector2(0, length));
    Vector2 anchor_B = gt.xform(Vector2(0, initial_offset));

    PhysicsServer2D::get_singleton()->joint_make_groove(p_joint, groove_A1, groove_A2, anchor_B, body_a->get_rid(), body_b->get_rid());
}

```

As you can see, a value of zero in `initial_offset` results in `anchor_B` being set at the origin of the `GrooveJoint2D`.

We find `joint_make_groove` in godot\_physics\_server\_2d.cpp (source):

```
void GodotPhysicsServer2D::joint_make_groove(RID p_joint, const Vector2 &p_a_groove1, const Vector2 &p_a_groove2, const Vector2 &p_b_anchor, RID p_body_a, RID p_body_b) {
    GodotBody2D *A = body_owner.get_or_null(p_body_a);
    ERR_FAIL_COND(!A);

    GodotBody2D *B = body_owner.get_or_null(p_body_b);
    ERR_FAIL_COND(!B);

    GodotJoint2D *prev_joint = joint_owner.get_or_null(p_joint);
    ERR_FAIL_COND(prev_joint == nullptr);

    GodotJoint2D *joint = memnew(GodotGrooveJoint2D(p_a_groove1, p_a_groove2, p_b_anchor, A, B));

    joint_owner.replace(p_joint, joint);
    joint->copy_settings_from(prev_joint);
    memdelete(prev_joint);
}

```

Which ends up passing the `p_b_anchor` to `GodotGrooveJoint2D`... Which we find in godot\_joints\_2d.h and godot\_joints\_2d.cpp. First of all, it will convert it to the local space of the second body in the constructor (source):

```
B_anchor = B->get_inv_transform().xform(p_b_anchor);

```

And then, in `setup` the computation of `rB` would be the zero vector (source):

```
    rB = B->get_transform().basis_xform(B_anchor);

    // calculate tangential distance along the axis of rB
    real_t td = (B->get_transform().get_origin() + rB).cross(n);
    // calculate clamping factor and rB
    if (td <= ta.cross(n)) {
        clamp = 1.0f;
        rA = ta - A->get_transform().get_origin();
    } else if (td >= tb.cross(n)) {
        clamp = -1.0f;
        rA = tb - A->get_transform().get_origin();
    } else {
        clamp = 0.0f;
        //joint->r1 = cpvsub(cpvadd(cpvmult(cpvperp(n), -td), cpvmult(n, d)), a->p);
        rA = ((-n.orthogonal() * -td) + n * d) - A->get_transform().get_origin();
    }

```

Although, I believe that is no problem. Then we pass `rB` to `k_tensor`:

```
    // Calculate mass tensor
    k_tensor(A, B, rA, rB, &k1, &k2);

```

Which looks like this (source):

```
static inline void
k_tensor(GodotBody2D *a, GodotBody2D *b, Vector2 r1, Vector2 r2, Vector2 *k1, Vector2 *k2) {
    // calculate mass matrix
    // If I wasn't lazy and wrote a proper matrix class, this wouldn't be so gross...
    real_t k11, k12, k21, k22;
    real_t m_sum = a->get_inv_mass() + b->get_inv_mass();

    // start with I*m_sum
    k11 = m_sum;
    k12 = 0.0f;
    k21 = 0.0f;
    k22 = m_sum;

    r1 -= a->get_center_of_mass();
    r2 -= b->get_center_of_mass();

    // add the influence from r1
    real_t a_i_inv = a->get_inv_inertia();
    real_t r1xsq = r1.x * r1.x * a_i_inv;
    real_t r1ysq = r1.y * r1.y * a_i_inv;
    real_t r1nxy = -r1.x * r1.y * a_i_inv;
    k11 += r1ysq;
    k12 += r1nxy;
    k21 += r1nxy;
    k22 += r1xsq;

    // add the influnce from r2
    real_t b_i_inv = b->get_inv_inertia();
    real_t r2xsq = r2.x * r2.x * b_i_inv;
    real_t r2ysq = r2.y * r2.y * b_i_inv;
    real_t r2nxy = -r2.x * r2.y * b_i_inv;
    k11 += r2ysq;
    k12 += r2nxy;
    k21 += r2nxy;
    k22 += r2xsq;

    // invert
    real_t determinant = k11 * k22 - k12 * k21;
    ERR_FAIL_COND(determinant == 0.0);

    real_t det_inv = 1.0f / determinant;
    *k1 = Vector2(k22 * det_inv, -k12 * det_inv);
    *k2 = Vector2(-k21 * det_inv, k11 * det_inv);
}

```

We see that it gets the `rB` argument in the `r2` parameter. We also see that `r2` is offset by the center of mass of the second body. And finally that if this somehow resulted in an invalid matrix, we would have an error.

Thus, as long as you are not getting an error in the output of your code, it is fine.
> 1 votes

---
Tags: 2d, joints, godot-4
---


# Question
Title: How do I select more Raycast Mask layers for XR Ray Interactor at run time?
I want to select more layers for Raycast Mask at runtime when I click a button.

I tried `GetComponent<XRRayInteractor>().raycastMask.` but couldn't find an option to select more layers

# Answer
> 0 votes
This is a bitmask, so you can shift a `1` bit into the position corresponding to each layer's index, then use `|` (bitwise OR) to combine these into a mask with exactly those chosen bits set to `1` and the rest left at `0`.

```
int firstLayer  = 1 << LayerMask.NameToLayer("First Layer Name Here");
int secondLayer = 1 << LayerMask.NameToLayer("Second Layer Name Here");
int thirdLayer  = 1 << LayerMask.NameToLayer("Third Layer Name Here");

GetComponent<XRRayInteractor>().raycastMask = firstLayer | secondLayer | thirdLayer;

```

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


# Question
Title: Storing achievement code logic in JSON vs in source-code
I am creating an achievement system for my game engine. I represent an achievement as a class takes a predicate function to determine if requirement for unlock has been met.

```
class Achievement {
    name: string
    description: string
    requirement: (event: GameEvent): bool

    constructor(name: string, description: string, requirement: (event: GameEvent): bool) {
        this.name = name
        this.description = description
        this.requirement = requirement
    }
}

```

An example achievement might look like

```
const firstItem = new Achievement(
    "First Item",
    "You picked up your first item!",
    (event: GameEvent) => { return event.label == "itemCollected" }
)

```

I'm wondeing what the best approaches are for storing and loading achievements. I could encode them in a JSON document

```
// assets/achievements.json
{
    "firstItem": {
        "name": "First Item",
        "description": "You picked up your first item!",
        "requirement": "event.label == 'itemCollected'"
    }
}

```

But it feels awkward to store the requirement code as a string, having to read it and pass it to `eval()`

```
class AchievementLoad {
    path: string

    constructor(path: string) {
        this.path = path
    }
    recursiveLoad(path: string): Achievement[] {
        const json = JSON.parse(path)
        const achievements = []
        for (const key in json) {
            const achievement = json[key]
            const requirement = eval(achievement.requirement)
            achievements.push(new Achievement(achievement.name, achievement.description, requirement))
        }
        return
    }
}

```

This introduces coupling between my source code and the asset save format, which seems to violate the Single-Responsibility Principle as changing the way one behaves may require me to change the other, and is further worsened by there being no type safety mechanism to alert me of incompatible changes. The ergonomics and safety suffer.

Alternatively I've considered storing the achievements in the source code itself, either as objects to be manually instantiated and exported

```
// src/achievements.ts
const firstItem = new Achievement(
    "First Item",
    "You picked up your first item!",
    (event: GameEvent) => { return event.label == "itemCollected" }
)
const firstQuest = new Achievement(
    "First Quest",
    "You completed your first quest!",
    (event: GameEvent) => { return event.label == "questCompleted" }
)
export { firstItem, firstQuest }

```

Or as classes themselves extending `Achievement`

```
// src/achievements/FirstItem.ts
class FirstItem extends Achievement {
    constructor() {
        super(
            "First Item",
            "You picked up your first item!",
            (event: GameEvent) => return event.label == "itemCollected"
        )
    }
}

export { FirstItem }

```

In either case, I'm not sure how professional this would be, especially given that I *am* going the JSON approach for other types of assets in my game.

What are the standard approaches and best practices here? Are there worthwhile alternatives I haven't considered or details I've overlooked?

# Answer
The usual caution with JSON is that it's easy for end users to edit. That can be a plus for allowing flexible modding of your game, but it means you should treat the data as untrusted.

**Never call eval() on untrusted data.**

If this is just a player hacking their (local) game to unlock all the achievements just for walking 2 steps, or give themselves unlimited money, no biggie - as long as it's not impacting fairness in online multiplayer or leaderboards.

But a bad actor could release a community mod for your game that does something popular superficially, while smuggling spyware into the executable code of the achievement condition. You want to avoid exposing your players to a threat vector like this, in case your game gets popular and develops a thriving modding community that can attract hackers preying on less tech-savvy folks.

---

What I did when implementing something similar in a recent jam game was to establish a vocabulary of "types" of achievements that needed distinct behaviours, which I could then specialize into specific achievements by setting parameters.

In that example, I only needed two types:

* Count - triggers when you've created enough blobs of a certain type (parameters: type, threshold count, and a flag to choose between simultaneous or lifetime total)
* Connection - triggers when you have enough blobs of a certain type surrounding another type (parameters: center type, connected type, threshold count)

Individual achievements were then data objects that specified which behaviour type they needed, and the corresponding parameters.

On load I could then take those objects and put them into lists to be evaluated against the relevant events, using the (hard-coded) predicate function indicated by their type data.

In your example that JSON might look something like this:

```
{
    "firstItem" : {
        "name": "First Item",
        "description": "You picked up your first item!",
        "unlock-rule": "gameEventLabel",
        "match": "itemCollected"
    }
}

```

If you need more complex rules for your achievements and want to avoid making a unique code path for every one, you can compose them out of simpler rules, something like...

```
{
    "defeatGruntsWithFire": {
        "name": "Playing With Fire",
        "description": "You defeated 5 grunts using fire magic",
        "repeats": 5,
        "criteria": [
            {
                "rule": "gameEventLabel",
                "match": "defeatEnemy"
            },
            {
                "rule": "enemyType",
                "match": "grunt"
            },
            {
                "rule": "damageElement",
                "match": "fire"
            }
        ]
    }
}

```

Each achievement then gets an array of criteria to check, and only when they all match do you increment the achievement counter (for multi-step achievements) or award the achievement. Each criterion is an object with a parameter it's looking to match, and a rule for what it's matching against. As your vocabulary of criteria grows, you'll soon be able to make new achievements by composing existing criteria rather than writing new criterion types into the system.

In code, this looks like a switch statement in your loading routine, checking for the key strings (or using enums if your environment makes that convenient), and populating your new `Achievement` object with a new `Criterion` object of the correct subtype, or list thereof.
> 2 votes

---
Tags: assets, savegame, loading, asset-management, achievements
---


# Question
Title: Keep export_presets.cfg in source control without exposing secrets
The source for my **Godot 4** game is public and open. With exports targeting Web, Linux, or Windows this was just fine. However, now I'm trying to target macOS with an export as well. This includes signing and notarizing the app (as I *suspect* Android and iOS targets would need too) with specific secrets.

**These secrets should not go into the public source** but, well... be kept secret. I cannot find any good documentation on how to do this. I've checked:

As well as other bits of the documentation and online search results. None of them have any definitive advice on how to handle this situation. But perhaps I've not been reading of searching precisely enough?

The closest I've come is what the `.gitignore` from godot-demo-projects seems to do: just ignore `exports_presets.cfg` and presumably have secrets inside that file. That has two major downsides for me:

1. A ton of other non-secret export settings are now no longer under source control;
2. You're one git mistake away from making your secrets public.

I must be missing something, because anyone who wants to make a notarized macOS export for a Godot game will encounter this situation. Even if your source code is private, you'd not want to have secrets in there in plaintext, right?

**How do you keep export secrets safely outside of the game code repository, without giving up on *all* source control of non-secret export settings?**

I'm happy to utilize any Godot 4 feature as I'm on the latest major release, but I reckon others might be interested in a Godot 3.x solution as well.

# Answer
The way I currently handle this is as follows:

* The developer responsible for release keeps a local branch with the changes that add the secret details to `exports_presets.cfg`.
* When we want to release, that developer merges the main branch into that local branch, so he can export the release build of the game.

The shared `exports_presets.cfg` can have enough information to make some debug builds, which are useful for testing by other members of the team. However it does not contain enough information to make the release builds which require additional credentials.

---

## On safeguards

First of all, if you automate your build process (which you can with Godot command line arguments) then you can have your build script merge in the correct way.

---

Now, if you want to prevent people from merging the wrong way, you could use Git Hooks. You want a pre-merge-commit. Which you create with a shell script called `pre-merge-commit` (no extension) in your `.git/hooks` folder. Git will honor the shebang (`#!`) at the start of the file.

To prevent the merge, the script must end with a non-zero exit code. *Also, if Git fails to execute the script (e.g. it could not resolve the shebang) it will not merge.*

Notes for the shebang in Windows:

* The path using `/` as folder separator character will work.
* You need to escape spaces and dots with `\`.
* You don't need to include the executable extension `.exe`.
* A path that starts with `/` will be relative to the installation folder of Git.

As a result `#!/bin/bash` and `#!/bin/sh` will resolve to `\bin\bash.exe` and `\bin\sh.exe` respectively, in the Git installation folder (e.g. `C:\Program Files\Git\`). In fact, `\bin\bash.exe` and `\bin\sh.exe` are provided with the installation of Git for Windows. So you can use either `#!/bin/bash` or `#!/bin/sh` cross platform.

Here is an example of what you want: pre-merge-commit.

---

Be aware that the Git Hooks are in the `.git/hooks` folder, and thus not in source control.

You might not need to deploy the Git Hooks, since only the developer that builds the game would be in the situation to make the mistakes necessary to leak the information.

However, one option to deploy them would be to use a template directory which would have to be part of the development environment on the target machines. *And you could protect that with OS level security, and you want the option to boot from another device protected with a password so they don't bypass OS level security, and and you want physical security to prevent other means.*

But assuming you can trust your developers, then adding a script in your repository that deploys the Git Hooks should be sufficient.

In fact, we can assume that you trust in particular the developer that has the `exports_presets.cfg` with extra credentials, since they have extra credentials. So probably you can trust they will run the script to build the game, and you don't need Git Hooks.
> 3 votes

---
Tags: version-control, godot-4
---


# Question
Title: Mouse-Click Movement Using Unity NavMeshAgent Causes Stuttering Upon Reaching Destination
Alrighty, so I've seen a lot of stuttering-related questions about `NavMeshAgents` but my problem is a little specific to my use case since it has nothing to do with `NavMesh` itself as a system. The system works great for me, it's simply a problem with how I am implementing it. I'm sure there is a solution, I'm just not sure what it is.

So, onto the actual issue. I am using `NavMesh` and `NavMeshAgents` to facilitate a mouse-click style movement system (think **Diablo** or **Path of Exile**). When the mouse is held down, the player will constantly move towards that location using a `Raycast` from the camera to the `NavMesh` to get and set the destination.

However, despite using the `stoppingDistance` variable on `NavMeshAgents`, it doesn't matter because if the player holds down the mouse button near the threshold of the stopping distance, the character will constantly switch states between *destination reached* to *new destination found*.

My code is a bit messy, so apologies for that, this is a quickly thrown together prototype of my movement system. That being said, I don't actually think my code is the problem, I think this is simply a very niche problem I don't know how to solve.

```
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.InputSystem;

[RequireComponent(typeof(NavMeshAgent))]
public class PlayerController : MonoBehaviour
{
    [SerializeField] private LayerMask navigableMask;

    private NavMeshAgent _agent;
    private Camera _followCamera;

    private void Start()
    {
        _followCamera = Camera.main;
        _agent = GetComponent<NavMeshAgent>();
    }

    private void Update()
    {
        HandleMovement();
    }

    private void OnEnable()
    {
        movementInput.Enable();
    }

    private void OnDisable()
    {
        movementInput.Disable();
    }

    private void HandleMovement()
    {
        if (movementInput.ReadValue<float>() == 1f)
        {
            Ray ray = _followCamera.ScreenPointToRay(Mouse.current.position.ReadValue());

            if (Physics.Raycast(ray, out var hit, 100, navigableMask))
            {
                Move(hit.point);
            }
        }
    }

    private void Move(Vector3 destination)
    {
        _agent.SetDestination(destination);
    }
}

```

Here is a gif of the problem, in action.

# Answer
This looks like a problem you could solve with a bit of hysteresis.

While the mouse button is held:

* If the character is already in the current stopping distance, change the stopping distance to a "large" distance (so that they don't start moving from a small mouse move - they'll let it get a little farther away before chasing).
* If the character is *not* already in the current stopping distance, change the stopping distance to a "small" distance (so that they have some room to move without stopping short after only half a step).

This can still create some stop-and-start, but by tuning the sizes of the large and small distances, you can change it from jerky hesitation to a more deliberate-looking pause & run to catch up.
> 0 votes

---
Tags: unity, c#, movement, navmesh
---


# Question
Title: Jedi Outcast VR Port - Lightsaber effect
Dr. Beef's VR port of Jedi Outcast has the best implementation of the lightsaber effect I've seen. It's far better than the lightsaber effect in ILM's own Vader Immortal.

The lightsaber in Vader Immortal is clearly just cylinder that scales up and down (and gets extruded when you wave it) to mimic that pulsing effect with a billboard texture for the glow of the lightsaber. See a video of it in action here.

But I'm still trying to figure out how it's done in the VR port of Jedi Outcast. It's clearly more than just a billboard texture when you hold the lightsaber down and look at it from the hilt. Is it using an outline shader on the lightsaber blade geometry and applying the pulsating glow texture to the outline, or maybe using a bloom effect for the glow of the saber? Any ideas on how this effect is pulled off so I can do something similar in my game? Here's a video of it in action.

# Answer
> 0 votes
As only the actual devs of the VR port of Jedi Outcast can say for sure, Here's my guess on how I'd attempt this same effect.

I think the bright part of the lightsaber is still a cylinder or capsule with a clever texture and animation. Now that bloom is a thing, pulsating the emission values can give a nice effect.

I think the blue glow is actually a string of blue particles that blend nicely together and flicker. I think the blend mode is something other than additive, so that the value's don't stack when viewing from different angles.

I Didn't know Jedi Outcast was ported to VR, I'm going to have to check it out myself one day!

---
Tags: shaders, particles, graphic-effects, virtual-reality
---


# Question
Title: Player body getting stuck between static bodies
This is a self-answered question. While it might be pretty obvious, this still catched me by surprise, so I believe there is some value in this Q&A.

There is a player-controlled `RigidBody2D` that gets stuck between two `StaticBody2D` instances.

As long as there is only a single collision between the `RigidBody2D` and one of the `StaticBody2D`'s, it works mostly as expected (though I did notice high friction at certain angles, when sliding the `RigidBody2D` alongside the edge of the `StaticBody2D`).

The `RigidBody2D` gets stuck only if it touches *both* of the `StaticBody2D`'s at the same time (as in the image above). Sometimes the `RigidBody2D` could be freed by the player using a high force, but sometimes not.

I made sure that friction for all bodies was set to `0.0`, but the bodies still get stuck.

# Answer
> 3 votes
It turned out the `StaticBody2D`'s had a **scale factor** of `1.004` along the x-axis. This visibly unnoticable scale factor was enough to trip up the physics.

Well, I had read the physics introduction, where it's made very clear, that you should never ever scale your collision shapes:

> Be careful to never scale your collision shapes in the editor. The "Scale" property in the Inspector should remain `(1, 1)`. When changing the size of the collision shape, you should always use the size handles, **not** the `Node2D` scale handles. Scaling a shape can result in unexpected collision behavior.

Still I must have accidentally scaled the collision shape, which can easily happen when you are in scale mode and miss the handles for resizing the collision shape.

To be safe, double check that you are **not** in scale mode `S`. Use select mode `Q`, in which case miss-clicking only moves the collision shape, which is easy to notice. To be really safe, don't resize by mouse but type the values into the shape properties in the inspector.

---
Tags: collision-detection, physics, godot-4
---


title: Animatedsprite at godot 3.1

text:
# Question
Title: Animatedsprite at godot 3.1
In Scene Player, I changed the sprite to animated sprite and created two modes, stand and walk, and wrote these scripts to move the player. But when I play the scene, the characters don't show their animations. I don't know what is problem.

```
func _physic_ptocess(delta):
  if Input.is_action_pressed("ui_right"):
    acceleration_player.x = player_speed
    $Sprite.play("walk")
    $Sprite.flip_h = false

  if Input.is_action_pressed("ui_left"):
    acceleration_player.x = -player_speed
    $Sprite.play("walk")
    $Sprite.flip_h = true

  if Input.is_action_pressed("ui_up"):
    acceleration_player.y = -player_speed
    $Sprite.play("walk")

  if Input.is_action_pressed("ui_down"):
    acceleration_player.y = player_speed
    $Sprite.play("walk")

  else:
    $Sprite.play("stand")

```

# Answer
> 1 votes
Look at this code:

```
if Input.is_action_pressed("ui_down"):
    acceleration_player.y = player_speed
    $Sprite.play("walk")

else:
    $Sprite.play("stand")

```

I want you to focus on the `else` branch:

```
if Input.is_action_pressed("ui_down"):
    # ...
else:
    $Sprite.play("stand")

```

It says that if you are not pressing the action `"ui_down"` the animation will be `"stand"`. In which case the rest of calls to `play` do not matter.

*I suppose a solution is to make most of these `if` into `elif`. But then you won't be able to combine vertical and horizontal input. Instead...*

---

I want to encourage to separation of concerns. Let us separate the visuals which is what you care about:

```
if Input.is_action_pressed("ui_right"):
    acceleration_player.x = player_speed

if Input.is_action_pressed("ui_left"):
    acceleration_player.x = -player_speed

if Input.is_action_pressed("ui_up"):
    acceleration_player.y = -player_speed

if Input.is_action_pressed("ui_down"):
    acceleration_player.y = player_speed

# visuals

if abs(acceleration_player.x) < 0.00001 and abs(acceleration_player.y) < 0.00001:
    $Sprite.play("stand")
else:
    $Sprite.play("walk")
    if acceleration_player.x < 0:
        $Sprite.flip_h = true
    else:
        $Sprite.flip_h = false

```

Note: the reason I check `abs(acceleration_player.x) < 0.00001` instead of `acceleration_player.x == 0.0` is just in case the value does not hit `0.0` exactly due to floating point errors, which I don't know if they are possible or not in your code. *I would have used `is_zero_approx` in Godot 3.2 or newer.*

I submit to your consideration to leave only the check for `acceleration_player.x` in the conditional. In particular if `"walk"` does not represent an appropriate animation for vertical motion.

By the way the second part can be more compact if you want:

```
    $Sprite.flip_h = acceleration_player.x < 0

```

---
Tags: sprites, godot
---


title: Callable string as variable

text:
# Question
Title: Callable string as variable
I followed an old tutorial about a card game and, after finishing it, I started removing some code I didn't like or it was simply not compatible with Godot 4.

Anything went fine, except for one thing.

In the game are declared two unneeded one-shot timers: they do the exact same thing, with the same delay but, once fired, they must call two different functions.

I refactored the code to have only one timer.

One solution worked, but I wanted to know why the other one didn't.

In the `_ready` function there's a function setupTimers, where I have:

```
c = Callable(self, method)
flipTimer.connect("timeout", c)

```

`method` is a global containing the -variable- string name of a function:

I change its value just before calling `flipTimer.start(1)`, but problem is, once declared the `Callable`, `method` takes its current value and it cannot change anymore (I even tried using a function to `return` the current method value).

Is there any way to make it work the way I hoped?

The solution that worked is a little bit different:

* I provide the name of a function directly;
* the function is called on timeout;
* inside the body of the function I `expression.execute` the function names;

This way it works, but why the other don't? I suppose Callable stores a value that can't be variable but I'd like to know if there's a way to get around this limitation.

# Answer
The types `Callable`, `String` and `StringName` for that matter, are all value types. Anywhere you pass them, you are passing a copy. *`StringName` is an internal string.*

So when you pass the name of the method to create the `Callable`, the `Callable` has a copy. And when you pass the `Callable` to connect the signals, that is a copy.

To reiterate, they are not references. So changing the string that has the name of the method you passed to the `Callable` has nothing to do with the `Callable`, nor the signal connection.

In fact, `Callable`, and `StringName` are immutable. *`String` can be manipulated, but we rarely do that.* So no, you cannot change the method that the `Callable` points to.

---

By the way, this code:

```
c = Callable(self, method)
flipTimer.connect("timeout", c)

```

Is equivalent to this:

```
c = Callable(self, method)
flipTimer.timeout.connect(c)

```

You don't need to use a `String` to reference signals anymore.

---

Now, since `Callable` are value types, any local `Callable` is freed when it goes out of scope. So they work very well for short lived values.

Thus, you don't need to use `expression.execute` to call a method by name, you can do this:

```
Callable(obj, method_name).call()

```

In fact, you don't need a `Callable` for this, since `Object` has a `call` method:

```
obj.call(method_name)

```

Which - by the way - was valid in Godot 3.

---

Anyway, you have two one shot `Timer`s. Instead of trying to combine them into one one shot `Timer`, I suggest you use the `SceneTreeTimer`s:

```
var c := Callable(obj, "actual_method")
get_tree().create_timer(timeout_seconds).timeout.connect(c)

```

In fact, since you would know which one shot `Timer` you are supposed to call, you can connect the method directly:

```
get_tree().create_timer(timeout_seconds).timeout.connect(obj.actual_method)

```

Notice that I'm not adding `()` after the method name, and thus I'm not calling it. That is `obj.actual_method()` calls the method, `obj.actual_method` references the method (the equivalent of making a `Callable`).

Godot will free the `SceneTreeTimer` once they emit their `timeout` signal.

*Not not `free` your `SceneTreeTimer` manually, otherwise others timers will start behaving incorrectly due to Godot still referencing invalid memory (where a timer created afterwards could be allocated into).*

---

You might also be interested in anonymous inline methods ("lambda functions"). For example:

```
get_tree().create_timer(timeout_seconds).timeout.connect(
    func():
        prints("hello world")
)

```

*It could also be all in a single line.*

The lambda function is also a `Callable`.
> 4 votes

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


# Question
Title: Modeling a naturally circular relationship between three classes
I have three classes `Location`, `Item`, `Character`.

Every `Location` needs to know what items and characters are currently present within itself, every `Character` and `Item` need to know what `Location` they're in, every `Character` needs to know what items they're holding, and every `Item` needs to know what `Character` its currently being held by.

```
class Location {
    items: Item[]
    characters: Character[]

    constructor(items: Item[], characters: Character[]) {
        this.items = items
        this.characters = characters
    }
}
class Item {
    location: Location
    heldBy: Character

    constructor(location: Location, heldBy: Character) {
        this.location = location
        this.heldBy = heldBy
    }
}
class Character {
    location: Location
    inventory: Item[]

    constructor(location: Location, inventory: Item[]) {
        this.location = location
        this.inventory = inventory
    }
}

```

These circular references are convenient for quick lookup and feel natural to reason about, but make for a more tricky construction setup - in order to make a single instance of any of the three classes, I must have already made instances of the other two, chicken before the egg.

With this approach, I will have to have two rounds of construction:

1. Construct all three instances with every field set as empty or null initially
2. Loop back over the instances to stitch them together

```
class Location {
    items: Item[]
    characters: Character[]
    constructor() {
        this.items = []
        this.characters = []
    }
}
class Item {
    location: Location | null
    heldBy: Character | null
    constructor() {
        this.location = null
        this.heldBy = null
    }
}
class Character {
    location: Location | null
    inventory: Item[]
    constructor() {
        this.location = null
        this.inventory = []
    }
}
let location = new Location()
let item = new Item()
let character = new Character()

location.items.push(item)
location.characters.push(character)
item.location = location
item.heldBy = character
character.location = location
character.inventory.push(item)

```

Is this an acceptable approach? Are there better alternatives?

# Answer
> 1 votes
It really is not a good idea to have Inventory with an array directly inside the Character. You should have a class Inventory to hold every method/data that works with the Inventory.

The Inventory should not know that is being held by a Character. You want to keep the possibility to be able to reuse the script for other aspect of your game such as Chest or Shop without requiring to create a whole Character for it.

The exact same thing is true for the Location. The Location should not know that it holds a Character but instead work with an appropriate interface. Otherwise, a Location will never be able to manipulate other objects and concepts.

If were to say more formally, I would say that you are violating the Dependency Inversion Principle from the SOLID principles. While it is not require to follow the principles, they are good guideline to find what is wrong with your architecture.

# Answer
> 0 votes
Generally, you implement the buffs/enchantments taking effect when you equip the item. This can give rise to bugs such as:

> *Aztec monks with 1/55 HP no longer die when picking up or dropping a relic.*

Source

This was caused by an implementation where a monk holding a relic was a different unit than a monk not holding a relic (this game allows for new technology discoveries upgrading existing units - like cavalry becoming mobile infantry when automobiles get invented). A rounding error caused the unit to appear to have less than 1 hit point and therefore it died.

One only has the Sword of Awesomeness glow if it is equipped and also if there is an orc nearby. Or that torches only give off light when equipped, not when stored in a backpack.

Your location class should only contain the x, y and z coordinates in your grid/world. I think it would be smarter to have Coordinates separate from Location. Think of it as "coordinates are a place" and "a location is a place with a name".

My suggested changes are:

```
class Coordinates {
    x: int;
    y: int;
    z: int;
}
class Location {
    name: string; /* Example: this is the restaurant named W at the corner of High Street and Broadway */
    coordinates: Coordinates;
    constructor(coordinates: Coordinates, name: string) {
        this.coordinates = coordinates
        this.name = name
    }
}
class Item {
    /* stuff like weight, is it magic, what icon to show, */
}
class Character {
    coordinates: Coordinates;
    inventory: Item[]; /* collection of all items you have */

    /* Include other relevant body positions in your game */
    rightHand: Item; /* equipped in right hand, also included in inventory */
    leftHand: Item;
    shirt: Item;
    helmet: Item;

    constructor(coordinates: Coordinates, inventory: Item[]) {
        this.coordinates = coordinates;
        this.inventory = inventory;
        /* nothing is equipped, is it all in your backpack? */
    }
}

```

Answering questions like "who is at location x, y, z?" would require querying the coordinates of all characters & NPCs in the vicinity. You might want to consider "stuff laying on the ground" as some sort of NPC. Some games display anything on the ground as a little box or bag. Other games display things on the ground just as they display it when held.

---
Tags: architecture, oop, dependency-injection, typescript
---


# Question
Title: How to rotate a player to orient their up with a landing normal?
I'm making a skateboarding prototype in Unity, and like in skate 3, I'd like the player to sort of "align" gradually to their predicted landing slope. I've written the code that gets the predicted point at which the player will land, but actually rotating the player to it is proving difficult.

How can I make it so the player (by default) has their upward orientation gradually adjusted for a smooth landing, but still allow the player to spin in-air?

I've tried using LookRotation with the player's forward direction, and the predicted hit normal as the up, calculated when the player leaves the ground. This results in the player being unable to spin midair, and also tends to flip/spin out randomly.

Here's the code I'm using: (executed the frame they leave the ground)

```
predictedLandingRotation = Quaternion.FromToRotation(transform.up, predictedLandingInfo.normal);

```

In air, I do this every frame:

```
transform.rotation = predictedLandingRotation;

```

(I typed this on mobile so sorry if the formatting is a bit funky)

# Answer
> 0 votes
You can use the formula I've given in quite a few past answers to update the `up` direction while respecting your current `forward` direction as well as possible:

```
Quaternion TurretLookRotation(Vector3 approximateForward, Vector3 exactUp) {
    Quaternion zToUp = Quaternion.LookRotation(exactUp, -approximateForward);
    Quaternion yToz = Quaternion.Euler(90, 0, 0);
    return zToUp * yToz;
}

```

(Fun fact: you can actually get the 90 degree rotation without a full quaternion multiplication if you want to get fancy)

So the orientation with `up` aligned to our `landingNormal` and `forward` as close as possible to our current facing direction is:

```
var targetRotation = TurretLookRotation(transform.forward, landingNormal);

```

Then we can gradually blend there, so we don't snap all at once. There are a lot of ways to do this, but here's one to start with:

```
// Keep a member variable to help maintain smooth continuity
// in the motion from frame to frame.
Vector3 _tiltCorrectionVelocity;

void AlignUpWith(Vector3 targetUp, float blendWindow) {

    Vector3 smoothedUp = Vector3.SmoothDamp(
                            transform.up, // Start from current orientation
                            targetUp,     // Blend to target vertical
                            ref _tiltCorrectionVelocity, // Maintain continuity
                            blendWindow   // How many seconds should it take
                         );

    transform.rotation = TurretLookRotation(transform.forward, smoothedUp);
}

```

This helps take the harshest snaps out of the rotation, by ensuring your up axis carries some momentum from frame to frame, and won't suddenly swing in a different direction. Though you will notice it change momentum when your `targetUp` changes - good to disguise this when you can with animations of your skater, so that it looks like the energy is coming from somewhere rather than just spooky magnetism.

There's a lot you can layer onto this basic idea to dial in the feel - see the section on world impact reactions around 20 minutes into this video for how we handled this on Starlink.

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


# Question
Title: Flickering in mesh created procedurally using compute shaders and compute buffers
I'm attempting to create a mesh using compute buffers in Unity(2022.2.11). So far I've got the mesh rendering however parts of it periodically flicker frame to frame.

I'm assuming I've done something wrong but I'm having trouble figuring out what is wrong.

There are 4 relevant unity assets.

1. A Material
2. A CG Shader
3. A Compute Shader
4. A C# script

***TriangleRenderShader.shader***

```
Shader "Custom/TriangleRenderShader"
{
    Properties { }
    SubShader
    {
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            struct appdata
            {
                uint vertexID : SV_VertexID;
            };

            struct v2f
            {
                float4 vertex : SV_POSITION;
            };

            struct DrawTriangle
            {
                float3 vertices[3];
            };

            StructuredBuffer<DrawTriangle> _DrawTrianglesBuffer;

            float4 _Color;

            v2f vert(appdata v)
            {
                v2f o;

                DrawTriangle tri = _DrawTrianglesBuffer[v.vertexID / 3];

                o.vertex = UnityObjectToClipPos(tri.vertices[v.vertexID % 3]);

                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                return fixed4(1.0, 0.0, 0.0, 1.0);
            }
            ENDCG
        }
    }
}

```

***TriangleComputeShader.compute***

```
#pragma kernel CSMain

struct DrawTriangle
{
    float3 vertices[3];
};

AppendStructuredBuffer<DrawTriangle> _DrawTrianglesBuffer;

struct IndirectArgs
{
    uint numVertices;      // Number of vertices to render
    uint numInstances;     // Number of instances to render
    uint startVertex;      // Index of the first vertex to render
    uint startInstance;    // Index of the first instance to render
    uint unused;
};

RWStructuredBuffer<IndirectArgs> _IndirectArgsBuffer;

[numthreads(8, 8, 8)]
void CSMain (uint3 dispatchThreadID : SV_DispatchThreadID,
             uint3 groupThreadID : SV_GroupThreadID,
             uint3 groupID : SV_GroupID)
{
    // Calculate the offset for this thread group
    float3 offset = float3(groupThreadID.x, groupThreadID.y, groupThreadID.z * 2) * 2;

    DrawTriangle tri = (DrawTriangle)0;
    tri.vertices[0] = float3(0, 1, 0) + offset;
    tri.vertices[1] = float3(1, 1, 0) + offset;
    tri.vertices[2] = float3(1, 0, 0) + offset;
    _DrawTrianglesBuffer.Append(tri);

    // Update the number of verticies to match the number in "_DrawTrianglesBuffer"
    InterlockedAdd(_IndirectArgsBuffer[0].numVertices, 3);
}

```

***TriangleRenderer.cs***

```
using UnityEngine;
using UnityEngine.Rendering;

public class TriangleRenderer : MonoBehaviour
{
    [SerializeField]
    private ComputeShader computeShader;

    private int kernelIndex;
    private uint threadGroupsX;
    private uint threadGroupsY;
    private uint threadGroupsZ;

    private ComputeBuffer drawTrianglesBuffer;
    private ComputeBuffer indirectArgsBuffer;

    private uint[] argsBufferData = new uint[5]
    {
        0,  // Number of vertices to render (Calculated in the compute shader with "InterlockedAdd(_IndirectArgsBuffer[0].numVertices, 3);")
        1,  // Number of instances to render (should only be 1 instance since it should produce a single mesh)
        0,  // Index of the first vertex to render
        0,  // Index of the first instance to render
        0   // Not used
    };

    [SerializeField]
    private Material rendererMaterial;

    private Bounds renderBounds = new Bounds(Vector3.zero, Vector3.one * 1000); // just use a big box so nothing is culled.

    private void Start()
    {
        kernelIndex = computeShader.FindKernel("CSMain");
        computeShader.GetKernelThreadGroupSizes(kernelIndex, out threadGroupsX, out threadGroupsY, out threadGroupsZ);

        int numTriangles = (int)threadGroupsX * (int)threadGroupsY * (int)threadGroupsZ;
        int triangleDataSize = sizeof(float) * 3 * 3;
        drawTrianglesBuffer = new ComputeBuffer(numTriangles * triangleDataSize, triangleDataSize, ComputeBufferType.Append);
        computeShader.SetBuffer(kernelIndex, "_DrawTrianglesBuffer", drawTrianglesBuffer);

        indirectArgsBuffer = new ComputeBuffer(1, argsBufferData.Length * sizeof(uint), ComputeBufferType.IndirectArguments);
        computeShader.SetBuffer(kernelIndex, "_IndirectArgsBuffer", indirectArgsBuffer);
    }

    private void Update()
    {
        drawTrianglesBuffer.SetCounterValue(0); // clear append buffer so new triangles are appended to the beginning
        indirectArgsBuffer.SetData(argsBufferData);
        computeShader.Dispatch(kernelIndex, (int)threadGroupsX, (int)threadGroupsY, (int)threadGroupsZ);

        rendererMaterial.SetBuffer("_DrawTrianglesBuffer", drawTrianglesBuffer);

        Graphics.DrawProceduralIndirect(rendererMaterial, renderBounds, MeshTopology.Triangles, indirectArgsBuffer, 0, null, null, ShadowCastingMode.Off, true, gameObject.layer);
    }

    private void OnDestroy()
    {
        drawTrianglesBuffer.Dispose();
        indirectArgsBuffer.Dispose();
    }
}

```

*Setup Notes:*

* Create the 3 files above and an empty scene
* Make a new material apply the ***TriangleRenderShader.shader*** to it
* Make an empty game object, and apply the ***TriangleRenderer.cs*** script to it
* Drag the compute shader and material into the slots

*Initial Assumptions:*

* My initial assumption was that the compute shader hasn't finished running by the time the render shader attempts to render the triangle buffer, however I've attempted to forcibly wait for for the compute shader to finish using "GetData" on one of the buffers but that didn't seem to help at all, so I'm at a loss as to what it could be.
* My next assumption was I man be creating the drawTrianglesBuffer compute buffer wrong by using an incorrect size or something, but most things I try when changing that only appear to make it worse, so I'm assuming its something else...

*Example of the bug:* Here is the mesh being rendered incorrectly on the currently paused frame. The green circled areas are spots where only the top rows of the mesh are rendered for whatever reason. These areas are not consistent frame to frame, some frames they all show up, other frames random chunks are missing.

# Answer
> 2 votes
So I've finally figured out the issue, it was an oversight on my part when calling `computeShader.Dispatch`, I had forgotten/overlooked that the parameters that associate with the number of thread X/Y/Z groups effectively acts like a multiplier. This was resulting in append buffer attempting to write beyond its max index since in the example I allocate a buffer size of `sizeof(float) * 3 * 3 * numTriangles` which was resulting in a buffer size of 18,432 `(8*8*8) triangles`, but when the compute shader was running, it was effectively doing that `((8*8) * (8*8) * (8*8)) triangles`. TD;DR: Double check to make sure you're dispatching the expected number of thread groups.

---
Tags: unity, compute-shader, dynamic-mesh
---


# Question
Title: Why do texture samplers seem to bleed into other instances when rendering multiple instances of the same mesh with differing textures
So I will start off by laying out the relevant structure of my program.

I am using vulkan to render the same mesh over a few instances. To do this I have:

* a vertex buffer, used per vertex, which is an array of the following structure

```
pub struct ShaderVertexData {
    pub position: na::Vector3<f32>,
    pub uv: na::Vector2<f32>,
    pub normal: na::Vector3<f32>,
}

```
* an "instance" buffer, used per instance, which is an array of this structure.

```
pub struct InstanceData {
    pub model: [[f32; 4]; 4],
    pub texture_index: u32,
}

```
* An array of textures provided via a descriptor set

```
let descriptor_binding_flags = [vk::DescriptorBindingFlags::VARIABLE_DESCRIPTOR_COUNT];
let mut descriptorset_layout_binding_flags =
    vk::DescriptorSetLayoutBindingFlagsCreateInfo::builder()
        .binding_flags(&descriptor_binding_flags);

let layout_bindings = [DescriptorSetLayoutBinding::builder()
    .stage_flags(vk::ShaderStageFlags::FRAGMENT)
    .binding(0)
    .descriptor_count(MAX_IMAGES)
    .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
    .build()];

let descriptor_set_layout_info = vk::DescriptorSetLayoutCreateInfo::builder()
    .bindings(&layout_bindings)
    .push_next(&mut descriptorset_layout_binding_flags);

let descriptor_set_layout_texture = unsafe {
    logical_device.create_descriptor_set_layout(&descriptor_set_layout_info, None)
}?;

let descriptor_pool_sizes = [vk::DescriptorPoolSize::builder()
    .ty(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
    .descriptor_count(MAX_IMAGES * 3)
    .build()];

let descriptor_pool_info = vk::DescriptorPoolCreateInfo::builder()
    .pool_sizes(&descriptor_pool_sizes)
    .max_sets(3);

let descriptor_pool =
    unsafe { logical_device.create_descriptor_pool(&descriptor_pool_info, None) }?;

let desc_layouts_texture = vec![descriptor_set_layout_texture; 3];
// TODO: Move this into the texture code to allocate as needed. For now I just hard-code 2 textures.
let mut variable = DescriptorSetVariableDescriptorCountAllocateInfo::builder()
    .descriptor_counts(&[2, 2, 2]);
let descriptor_set_allocate_info = vk::DescriptorSetAllocateInfo::builder()
    .descriptor_pool(descriptor_pool)
    .set_layouts(&desc_layouts_texture)
    .push_next(&mut variable);

let descriptor_sets =
    unsafe { logical_device.allocate_descriptor_sets(&descriptor_set_allocate_info) }?;

let descriptor_set_layouts = [descriptor_set_layout_texture];

let pipelinelayout_info = vk::PipelineLayoutCreateInfo::builder()
    .push_constant_ranges(&push_constant_ranges)
    .set_layouts(&descriptor_set_layouts);

//------------------------------------------------
// Later I copy in the texture info
//------------------------------------------------
let descriptor_image_infos = self.texture_store.get_descriptor_image_info();
let descriptor_writes = [vk::WriteDescriptorSet {
    descriptor_type: vk::DescriptorType::COMBINED_IMAGE_SAMPLER,
    dst_set: self.graphics_pipeline.descriptor_sets
        [frame_buffer_info.image_index as usize],
    dst_binding: 0,
    dst_array_element: 0,
    p_image_info: descriptor_image_infos.as_ptr(),
    descriptor_count: 2,
    ..Default::default()
}];

```

I then have the following shaders

```
// vertex
#version 450

layout(push_constant)uniform constants{
    mat4 proj;
}PushConstants;

layout(location=0)in mat4 model;
layout(location=4)in uint tex_id;
layout(location=5)in vec3 position;
layout(location=6)in vec2 uv;
layout(location=7)in vec3 normal;

layout(location=0)out vec2 uv_for_fragment_shader;
layout(location=1)out uint tex_id_for_fragment_shader;

void main(){
    gl_Position=PushConstants.proj*model*vec4(position,1);
    tex_id_for_fragment_shader = tex_id;
    uv_for_fragment_shader=uv;
}

// fragment
#version 450
#extension GL_EXT_nonuniform_qualifier : require

layout(set=0,binding=0)uniform sampler2D tex_samplers[];

layout(location=0)in vec2 uv_from_vertex_shader;
layout(location=1)in flat uint tex_id_from_vertex_shader;

layout(location=0)out vec4 output_colour;

void main(){
    output_colour = texture(tex_samplers[tex_id_from_vertex_shader], uv_from_vertex_shader);
}

```

Finally I draw the instances like so

```
self.logical_device.cmd_push_constants(
    commandbuffer,
    self.graphics_pipeline.layout,
    vk::ShaderStageFlags::VERTEX,
    0,
    &std::mem::transmute::<[[f32; 4]; 4], [u8; 64]>(projection),
);

self.logical_device.cmd_bind_descriptor_sets(
    commandbuffer,
    vk::PipelineBindPoint::GRAPHICS,
    self.graphics_pipeline.layout,
    0,
    &[self.graphics_pipeline.descriptor_sets
        [frame_buffer_info.image_index as usize]],
    &[],
);
self.cube.bind(&self.logical_device, commandbuffer);

self.logical_device.cmd_bind_vertex_buffers(
    commandbuffer,
    VertexBufferBindings::InstanceBuffer as u32,
    &[self.instance_buffer.buffer],
    &[0],
);

self.logical_device.cmd_draw_indexed(
    commandbuffer,
    self.cube.index_count() as u32,
    4,
    0,
    0,
    0,
);

```

With that out of the way we can get to the problem at hand, The texture samplers seem to bleed over into the separate instances

I have checked that the texture index itself is consistent across the entire instance by rendering

```
output_colour = vec4(tex_id_from_vertex_shader, 0,0,1);

```

And I get no artefacts

So it seems like the sampler itself is hanging around where it shouldn't. Any idea what might be causing this to happen?

If it matters I am on an AMD Radeon 7900 XTX and using the latest drivers

# Answer
> 3 votes
I finally got an answer on the AMD Forums.

The issue was that you need to tell the GPU when you plan on indexing resource arrays with non uniform values.

My shader now looks like this:

```
#version 450
#extension GL_EXT_nonuniform_qualifier : require

layout(set=0,binding=0)uniform sampler2D tex_samplers[];

layout(location=0)in vec2 uv_from_vertex_shader;
layout(location=1)in vec3 normal_from_vertex_shader;
layout(location=2)in flat uint tex_id_from_vertex_shader;

layout(location=0)out vec4 output_colour;

void main(){
    vec4 albedo = texture(tex_samplers[nonuniformEXT(tex_id_from_vertex_shader)], uv_from_vertex_shader);
    float light = clamp(dot(normal_from_vertex_shader, normalize(vec3(1,1,1))), 0.2, 1);
    output_colour =  vec4(albedo.rgb * light, albedo.a);
}

```

The important part is the `nonuniformEXT` that wraps the index

It is also worth mentioning that technically this also requires that you enable `shaderSampledImageArrayNonUniformIndexing` on your `VkPhysicalDeviceDescriptorIndexingFeatures`

---
Tags: graphics, vulkan
---


title: MonoBehaviour Wouldn't Work

text:
# Question
Title: MonoBehaviour Wouldn't Work
I was writing the character controller for my player character, but Unity said that there was no mono behavior script in the file I'd written the file right and I included the mono behavior `public class ScriptName : MonoBehaviour` in the code, is there something missing, or did I write it wrong?

# Answer
> 0 votes
Please make sure that you include the proper packages or libraries with the **using** statements at the top of the file.

For example, this is a simple script that should work:

```
using UnityEngine;
using UnityEngine.UI;
using System;

public class My_First_Script : MonoBehaviour
{
}

```

---

If you can post your whole script to your question, then we can help you better.

---
Tags: unity, unityscript, monobehaviour
---


# Question
Title: How to handle UI when logical and screen sizes are different?
I am programming a game in SDL2 and I am looking for advice on how to handle interactivity of UI components when the screen resolution and logical resolutions are different. Up to now I have been developing the game with common logical and screen solutions, I am working at 2560x1440 and all my UI components (buttons, scroll bars) are defined relative to the screen resolution. If I decide to use `SDL_RenderSetLogicalSize` to downscale the rendering to say 1920x1080 how should I handle the UI?

If I do nothing, the UI is now off the window screen, I can alternatively set the position of UI components relative to the logical resolution to bring my buttons back within the screen window but then the interactivity is broken - for example the mouse over for a UI box is now checking for a collision at the "logical position" which is different from the screen position.

One thought I had was to keep the UI component positions relative to the screen resolution but at rendering time adjust the drawing of all UI components by the ratio between the logical and screen resolution to make them appear within the window.

My game eventually will have a lot of UI components so before I start putting effort into coding I want to get a sense of what my options are - or if I am going about this the wrong way.

# Answer
> 2 votes
In case anyone is wondering, I figured it out on my own, the issue was that the mouse position in SDL2 is always given in terms of the screen resolution regardless of what the logical resolution is set to, the solution is to use `SDL_RenderWindowToLogical` to scale the mouse coordinates appropriately. Then the UI can be completely drawn in terms of the logical resolution and the mouse will react appropriately.

---
Tags: gui, sdl2, resolution
---


title: How to rotate a mesh in shader graph?

text:
# Question
Title: How to rotate a mesh in shader graph?
I want to rotate a mesh in a way that the Z axis arrow always points towards the camera. For a script I would do something like this:

```
Vector3 directionVector = camera.position - myObject.position;
myObject.forward = directionVector.normalized; // I cannot replicate this in shader graph

```

I can do something similiar in shader graph, but don't know how to apply it.

I am well aware that you cannot simply change the `Transform` component's value using a shader but I would like to rotate the mesh in a way that is similar as if we point its Z axis arrow towards the camera. How can I do this?

# Answer
> 2 votes
Here's an example in URP shader graph, which expects vertex position/normal/tangent vectors in object space. Different shader graphs sometimes use different conventions, so be sure to specify in your question if you need a solution for a different convention.

Click the image to zoom to a level where you can read all the text:

Here's a walkthrough of the strategy:

1. Convert the camera's world space position into object space. This gives us a vector in our local working coordinate system from our origin (the object pivot) toward the camera. Normalize it to ensure it's unit length - this will become our new "forward" direction, and we'll rotate our vertices so those on the "+z" side of our model will face this way.
2. Pick a reference "up" vector to try to align our "+y" side toward. Unfortunately, due to the Hairy Ball Theorem, there's no perfect way to do this without discontinuities. So we'll choose two candidates, world up (preferred), and world right (fallback), and convert them to local space.

To decide which one to use, we compute the dot product of the local-world-up with our "to-camera" (desired forward) vector, and take the absolute value. If it's close to 1.0, then these vectors are very close to parallel (or anti-parallel), and we use our fallback, otherwise we use our first choice.
3. Cross our selected reference up vector against our desired forward (all in local space). This gives us a local right vector that's guaranteed parallel to our forward - though it might not be exactly unit length, if our reference up and forward were not quite perpendicular, so we normalize it to make sure.
4. Cross our desired forward with our new right vector to get a local up vector that's *definitely* perpendicular to both and unit length (to within a tiny rounding error).
5. Assemble these three vectors into a rotation matrix, and use it to rotate our local vertex position, normal, and tangent (if you care about lighting and normal mapping, respectively). Output our rotated vectors to the vertex shader result pins.

Note that if this model gets batched with others, the origin we get in the shader math will be the origin of the batch, not the origin of this individual mesh, which can cause our rotation to occur around the wrong point. If you observe this happening, disable batching on this material. (Or, if you need batching, you may have to encode offsets from the local pivot point into vertex colours so they survive the batching tansformation).

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


title: Timer for each level godot 3.1

text:
# Question
Title: Timer for each level godot 3.1
I want to set a timer for each level of my game, so that when the player eats item number one, 10 seconds will be added to the time of that level, and when the player eats item number two, 5 seconds will be subtracted from the time of that level. The total playing time in each level should be 60 seconds. How can I script it?

And to display the timer in the scene of each level (60:00), should I use a special command?

# Answer
Before we get into Godot specific stuff: What you want is a countdown.

*Do not confuse this with a stopwatch, which counts up, and then you stop it and see the time it war running for.*

---

We could implement a countdown over something that ticks over time.

You could have - for example - a one second timer that decrements a variable with the remaining time. However, since you want fractions of seconds, assuming you don't need more precision than a frame, let us use `_process` directly instead.

It is trivial to increment the remaining time, since that is just incrementing the variable. And to check if the remaining time is over the upper bound is trivial too.

You get pauses for free. When the game is paused, the timer does not trigger the code to decrement the remaining time, so the countdown is automatically stopped.

---

Something like this:

```
extends Node
class_name Countdown

signal time_up
signal time_changed(seconds)

export var max_seconds:float setget set_max_seconds
var remaining_seconds:float setget set_remaining_seconds

func _ready() -> void:
    self.remaining_seconds = max_seconds

func _process(delta: float) -> void:
    self.remaining_seconds -= delta

func set_max_seconds(mod_value:float) -> void:
    max_seconds = max(0.0, mod_value)
    self.remaining_seconds = min(remaining_seconds, max_seconds)

func set_remaining_seconds(mod_value:float) -> void:
    mod_value = clamp(mod_value, 0.0, max_seconds)
    if remaining_seconds == mod_value:
        return

    remaining_seconds = mod_value
    emit_signal("time_changed", mod_value)
    if mod_value == 0.0:
        emit_signal("time_up")

```

Any other scripts that tries to set `max_seconds` or `remaining_seconds` will result in a call to the corresponding set method (`set_max_seconds` and `set_remaining_seconds` respectively.

From the same script - in Godot 3.x - that is not true. Instead we have to use `self` to trigger the set method. For example setting the `remaining_seconds` with `self` (`self.remaining_seconds`) will trigger the set method `set_remaining_seconds`.

Notice I'm setting the `remaining_seconds` to `max_seconds` at the start. Also that `max_seconds` is an exported variable (so you set it from the inspector). *If you hard code `max_seconds` (perhaps as a `const`) so it does not need a set method, you can make the code shorter.*

---

The other thing you want is to show it, which will require adding a `Label` to your UI.

I have added a signal `"time_changed"` to the script above, that you can connect to a method that formats and sets the text to the `Label`.

```
func _on_Countdown_time_changed(seconds:float) -> void:
    text = str(seconds)

```

**Addendum**: This is one solution to format the time: `("%02.2f" % seconds).replace(".", ":")`.

Since it is changing every frame anyway, you could use `_process` to read the value. Although I have made it so the `"time_changed"` stops triggering when it is not ticking (e.g. when it reached zero). In fact, the check `remaining_seconds == mod_value` will prevent triggering the signal, if there is no change in value. *If you consider that you don't need `"time_changed"`, you might remove it to make the code shorter.*

Speaking of reaching zero, there is also a `time_up` signal you can connect for that.

---

And you say that when the player gets an item it increments the time. So you need to find a reference to the countdown. Which brings the question of where do you place it. It could be on the root of the edited scene, like this:

```
Main
└ Countdown

```

Then you can find it like this:

```
owner.get_node("Countdown")

```

And as part of your collision you would so something like this:

```
func _on_Area_body_entered(body):
    # ...
    owner.get_node("Countdown").remaining_seconds += 10.0

```
> 0 votes

---
Tags: timer, godot-3
---


# Question
Title: Animation Rigging stops working when transitioning between animations
I've followed all the online guides, I've changed characters (from a character taken from the Unity Asset Store to one from Mixamo), I've used animations taken from three different sites, but the problem remains.

Between one animation and another, the character does not keep aiming at the target (see images). It does the same thing also with the classic transitions (not the blend tree), as long as there is only one animation the IK is correct and points to the target, as soon as it mixes between one animation and the other it points to the top right.

**This is the correct position (`MoveX=0` and `MoveY=1` only one animation running)**

---

**This is the wrong position (`MoveX=0` and `MoveY=0.61` merging of two animations)**

The structure of the Rig seems correct to me. Can you give me an indication of what to look at? if you need more information just ask.

**This is my structure tree**

Thanks for your help.

**UPDATE**

I tried to look into the problem. And to make it easier for those who want to help me I made a video explaining the problem.

Youtube video

# Answer
I solved the problem by switching from the Unity version `2022.2.1f1` to the beta version `2023.1.0b12`. I don't know which of the intermediate versions solves this problem, but at least in the current beta version it works fine.
> 0 votes

---
Tags: unity, animation, rigging, inverse-kinematics
---


# Question
Title: How to create a default binding for an InputAction?
When I have an `InputAction` in a Unity component, like this:

```
[SerializeField] InputAction jump = new InputAction(type: InputActionType.Button);

```

I can add one or more bindings to that action through the Inspector. This has the disadvantage that other people using my component cannot just use it as-is - they have to manually add bindings.

Alternatively, I can add bindings in my code, like this:

```
private void Awake() {
    jump.AddBinding("<Keyboard>/space");
}

```

Then anyone can use my component out-of-the-box. However, this binding cannot be changed through the inspector.

Is there a way to set a "default binding" for an InputAction, that is available for anyone using the component without any need for a manual action, but still can be modified through the inspector?

This is possible for other input types, e.g. when I write:

```
[SerializeField] float maxSpeed = 10.0f;

```

it gives a default value that can be modified through the inspector. Is the same possible for an InputAction?

# Answer
This looks like a job for `OnValidate`

```
public class DefaultInput : MonoBehaviour
{
    public InputAction jump;
    public InputAction moveHorizontal;

    void OnValidate() {
        if (jump == null) {
            jump = new InputAction(type: InputActionType.Button);
        }
        if (jump.bindings.Count == 0) {
            jump.AddBinding("<Keyboard>/space");
        }
        if (moveHorizontal == null) {
            moveHorizontal = new InputAction(type: InputActionType.Value);
        }
        if (moveHorizontal.bindings.Count == 0) {
            moveHorizontal.AddCompositeBinding("1DAxis").With("Positive", "<Keyboard>/rightArrow").With("Negative", "<Keyboard>/leftArrow");
        }
    }
}

```

`OnValidate` gets called in the Unity editor in a number of cases:

* When this component is first added to an object
* When a value on this component is changed in the Inspector
* When the C# assembly containing this script is reloaded
* When entering play mode

...but it's not called in game builds, so it doesn't add any runtime overhead to your game the way an `Awake`, `OnEnable`, or `Start` method does.

You'll notice I chose not to use field initializers on these actions, but instead check in `OnValidate` if they're `null` and populate them if so. The reason for that is that `InputAction` is a reference type, so constructing a `new` instance of it involves a memory allocation and garbage collection book-keeping, in addition to the work done by its constructor. This happens even if the default initialized value later gets overwritten by a serialized value the designer provided in the inspector, so you waste cycles on an allocation for a throwaway object. This isn't a problem for value types like numbers/vectors/etc. because they don't need separate GC tracking, but for more complex types that do more work on construction, it's good to avoid redundant initialization.

Doing it this way does the work of building and inserting the default value only if necessary, and only ever at edit time, while still giving you the freedom to make the default binding logic as complex as you need. You can replace the defaults with your own versions in the Inspector and they'll be preserved - the code only restores default bindings when no binding is present. And at runtime, it's just as efficient as a version that was keyed-in by hand.
> 1 votes

---
Tags: unity, input
---


# Question
Title: How would someone validate authenticity of music samples?
I'm nowhere near ready for this step, but I prefer to gather information in advance, rather than waiting until it's necessary. I plan to ask any potential composers to provide their 2 best compositions and 1 composition created using a provided list of guidelines. This is simply to decide if they're right for the job. How do I authenticate the 3 compositions they'll provide, to verify that they aren't providing someone else's work?

# Answer
> 2 votes
I'm not a lawyer, this is not legal advice, situations vary by jurisdiction. The sort answer is: it's complicated.

Before addressing the authentication issue, I want to be clear that at least in the U.S., the core of this question **is** an issue. Secondary infringement occurs when a third party enables or supports infringement and can therefore be held responsible. The U.S. Copyright Act does not explicitly cover secondary liability for infringement, and thus various federal appellate courts have develop separate interpretations. This is why a lot of legal questions result in answers of "ask a lawyer" - case law is complicated.

For attempting to authenticate the originality of audio files, there are a couple of things you could try.

You could run the content past Google's Content ID. Basically, you make a video, add the music and upload it as a private video. The system then scans the content and informs you if it violates Google's copyright criteria. However this isn't a perfect process:

* the system may incorrectly flag something as previously copyrighted that isn't
* the system may incorrectly fail to flag something as copyrighted that is
* this isn't the intended use of the system and Google may change to prevent using it in this way

Also, from what I understand, you *must* include video with the audio to try this.

Another option is to use a service like Pex's MixScan. Their services claim to identify the *most* uses of copyrighted content, including speed and pitch changes used to avoid detection. Unlike Content ID, MixScan/Pex Search *is* intended to inform licensing, attribution, and compliance decisions. However it still has some of the same potential problems - it can make mistakes.

Because there's no way to guarantee that originality of music that your contractors might turn in, it's important to consider ways to guard against secondary infringement. This post from Legal SO on avoiding IP infringement by contracted work covers the basics:

* Take reasonable steps to avoid knowing use of infringing material
    + For example, use some sort of search even if you know it isn't a guarantee
* Use contracts (the word contract is literally in the word contractor)
    + Include an indemnification clause in your agreements with your contractors
* Carry liability insurance

The issue of sheet music has some additional complications. In the U.S. copyright is not just one right, but a collection of rights granted to the creator of an original work. This collection includes the right to control copying, distribution, and adaptation. Your performance of the sheet music is very likely also a creative work. The interaction between your rights as the performer can interact with the contractors rights as the composer. This is why copyright law has evolved such that each right must be negotiated separately. Do not assume that you automatically get all the rights you want from your contractors. Buying the sheet music is simply a legal transfer of a copy of the work.

On the matter of contracts, consider:

* Hiring a lawyer to make your contract.
* Doing careful research & using a reputable contract template. For example, Legal Zoom has on-line templates as well as some advice for deciding when legal templates aren't good enough.
* Doing enough research to become a legal expert and drawing up your own contracts. By this I mean, to the point where you would accept legal liability for giving out legal advice. Because this what you are doing: giving yourself legal advice and accepting the associated liability.

---
Tags: legal, music
---


title: Drawing a box using rule tiles in unity

text:
# Question
Title: Drawing a box using rule tiles in unity
SO I have a tile sprite like so :

I want to use this to draw boxes on a 2d map using rule tiles. But I can't seem to get how to set rules for it in unity.

These are the rules I have :

And this is what I get when I try to draw a map:

I understand why I get this, as the rules 4 and 5 are redundant and rules 2 and 3 take precedence but I included them any to tell what I am aiming for.

I tried using custom rule tile, even there it seem like its more for connecting different tile rather then dealing with sprites of same tile

PS: also ignore the mirroring on rule 2, it has no purpose, just something I forgot take away when I took the screen shot

# Answer
> 0 votes
So I ended up creating two rule tiles ,

1. For the top left border

2. For the bottom right border

Then made sure I use those tile on the respective edges like so:

```
using UnityEngine.Tilemaps;

void Start() {
    tm = GetComponent<Tilemap>();
}

void placeBoxBorder( int width, int height, RuleTile bottomRightTile, RuleTile topLeftTile) {
        for (int row = 0; row < height; row++) {
            for (int col = 0; col < width; col++) {
                Vector3Int vector3Int = new Vector3Int(row, col, 0);
                // Draw top left edge
                if ((col == 0 || row == height - 1)) {
                    tm.SetTile(vector3Int, topLeftTile);
                }

                // Draw bottom right edge excluding the top right corner
                if ((row == 0 || (col == width - 1 && row != height - 1))) {
                    tm.SetTile(vector3Int, bottomRightTile);
                }
            }
        }
    }

```

# Answer
> 0 votes
Switch tile 2 from mirroring (↔) to fixed (⚪). The mirror rule is letting it sub-in for the job of tile 5, which you don't want.

For all the straight wall segments (tiles 2-5), add an arrow in the direction pointing away from the wall. e.g. for tile 2 that would look like:

```
  ⬆
⬅⚪✖
  ⬇

```

Think of these as the directions someone standing in the center of the tile could move without leaving the walled area. They can walk along the wall or away from the wall toward the interior, but not through the wall to the outside.

It's this extra "this way inside" information that lets the rule decide when to place a left wall or a right wall, a top wall or a bottom wall.

---
Tags: unity, tilemap, tiled
---


title: Blender Texture Painting Problem

text:
# Question
Title: Blender Texture Painting Problem
I'm trying to texture paint a character in blender, however I'm running into a problem. I'm able to use the fill tool to color in the mesh, but the draw doesn't do anything.

For example, when I use the fill tool and choose a color like blue, then click the character, it turns blue. But when I select the draw tool and try to color the character, nothing happens.

Here's a picture of my UV's. I think I got everything for the texture painting to work. Does anybody know why it doesn't?!?

# Answer
I've found out the answer; I went over to the textures properties tab, and then deleted the texture that I had applied to the brush unknowingly. Because I didn't have any texture painting texture, the brush didn't output anything.
> 0 votes

---
Tags: textures, blender
---


# Question
Title: What does each byte in DXGI_FORMAT_R8G8B8A8_UNORM store?
I'm studying DX12. I came across this texture format:

> **DXGI\_FORMAT\_R8G8B8A8\_UNORM**
> A four-component, 32-bit unsigned-normalized-integer format that supports 8 bits per channel including alpha.

It's not clear to me exactly - what values does each RGBA element store? As it is clear from the description above, these values are from 0 to 1 i.e. UNORM. But how, for example, can 1 byte R8 store a real number from 0.0f to 1.0f?

# Answer
The format modifiers like `_UNORM` / `_SNORM` / `_FLOAT`, etc... are documented on the DXGI\_FORMAT Page:

> ### Format Modifiers
>
> Each enumeration value contains a format modifier which describes the data type.
>
> `_UNORM`
> Unsigned normalized integer; which is interpreted in a resource as an unsigned integer, and is interpreted in a shader as an unsigned normalized floating-point value in the range \[0, 1\]. All 0's maps to 0.0f, and all 1's maps to 1.0f. A sequence of evenly spaced floating-point values from 0.0f to 1.0f are represented. For instance, a 2-bit UNORM represents 0.0f, 1/3, 2/3, and 1.0f.

In your example format `DXGI_FORMAT_R8G8B8A8_UNORM` there are 8 bits per channel, so 28 = 256 possible values (0-255).

Those will map to float values in the range 0-1 like the given example in the documentation:

```
Int Value          Float Value
0                    0 / 255 = 0.0f
1                    1 / 255 ≈ 0.00392156862f
2                    2 / 255 ≈ 0.00784313725f
3                    3 / 255 ≈ 0.01176470588f
...                ...
127                127 / 255 ≈ 0.49803921568f
128                128 / 255 ≈ 0.50196078431f
...                ...
253                253 / 255 ≈ 0.99215686274f
254                254 / 255 ≈ 0.99607843137f
255                255 / 255 = 1.0f

```
> 8 votes

---
Tags: directx12
---


# Question
Title: Making a countdown time readout in Godot 3.1
I wrote this script to design countdown in my game:

```
extends Container

export (int) var minutes = 0
export (int) var seconds = 0
var dsec = 0

func _physics_process(delta):

    if seconds > 0 and dsec <= 0 :
        seconds <= 1
        dsec = 10

    if minutes > 0 and seconds <= 0:
        minutes -= 1
        seconds = 60

    if seconds >= 10:
        $sec.set_text(str(seconds))
    else:
        $sec.set_text("0"+str(seconds))

    if dsec >= 10:
        $dsec.set_text(str(dsec))
    else:
        $dsec.set_text("0"+str(dsec))

    if minutes >= 10:
        $minutes.set_text(str(minutes))
    else:
        $minutes.set_text("0"+str(minutes))

func _on_Timer_timeout():
    dsec -= 1

```

Here's what the UI section looks like:

When I play I get this error:

> Error: attempt to call function 'set\_text' in base 'null instance' on a null instance.

Where is the problem with my script?

And I also wrote 00 in the text section of the `minutes` inspector, 00 in the `seconds` inspector, and 0 in the `dsec` inspector.

When I want to move them separately, I can't and they are all stacked on top of each other.

I want to know how I can move them so that 00:00:0 can be seen next to each other?

# Answer
> 1 votes
`Container`s control how the children nodes are positioned. The base `Container` class does nothing special, it simply leaves the children in a default position.

You could try a `HBoxContainer` if you want a `Container` that positions the children in a row (Please notice that you would require some control having the `":"`). *I describe how some of the `Container`s work elsewhere.*

Or if you don't want the `Container` positioning the children, don't use a `Container`. `Control`s that are not `Container` can also have children, which would be positioned by their anchors and margins. *I have an explanation of the different ways things are positioned in Godot elsewhere.*

*I would have tackled your problem with a single `Label` and `String` concatenation. See also GDScript format strings.*

---
Tags: timer, gdscript, godot-3
---


# Question
Title: Unity NetCode - How to call a function when a server or client connects
I want to do a number of things after calling the functions `NetworkManager.Singleton.StartHost()` and `NetworkManager.Singleton.StartClient()`.

Is there a hook or something to do this?

# Answer
> 1 votes
There are two methods that can be registered: OnClientConnectedCallback and OnServerStarted.

As an example for registering OnClientConnectedCallback, you would do the following:

```
private void Start()
{
    if (IsClient)
    {
        NetworkManager.Singleton.OnClientConnectedCallback += OnClientConnected;
    }
}

```

And then define the callback

```
private void OnClientConnected(ulong clientId)
{
    if (clientId == NetworkManager.Singleton.LocalClientId)
    {
        Debug.Log("Client connected. You can now call ServerRpc methods.");
        // Call your ServerRpc method here or trigger an event to notify other scripts
        CallYourServerRpc();
    }
}

```

Make sure the class with the above inherits from NetworkBehaviour and that it has a NetworkObject component

---
Tags: unity, networking
---


# Question
Title: How to attribute authors of assets for my indie game
I am browsing sketchfab.com for assets and some of them are 'CC Attribution' which means you must attribute the author in your work. Where would I put this information in my game? Especially if I am using many assets. Do I have to attribute each author individually or can i just say 'some assets from sketchfab.com' for example?

# Answer
> 25 votes
The CC-BY license requires that you credit the author of the work, not the platform that conveyed it. So yes, when you take lots of assets from lots of different creators, you must credit each of them in the way their individual license conditions demand. Which in the case of the Creative Commons, means with the creators name, the name of the asset, link to the asset and a link to the license. Otherwise you are committing a copyright violation. Which means that the creators of those assets might cause you all kinds of problems. Like sending DMCA takedown notice to the platforms through which you sell your game or even sue you for damages.

General practice for giving credits is the credit screen of your game. Which should, according to the guidelines by the IGDA, be easily accessible from within your game without having to play the game itself. Yes, game development tradition is to show the credits roll after "beating" the game (whatever that means in the context of the game your are making). And I personally am actually a huge fan of this tradition. But due to the requirement to make credits easily accessible, you usually **also** make them accessible immediately through the start screen or options menu.

My personal approach when dealing with 3rd party assets is to create a text file for each asset I download that contains the credit message as demanded by the license conditions, name it like the asset and store it in the same directory. Not to include those in the final build, but for myself so that I remember what credit I need to give for each asset when I make the credits screen later (which you might even be able to automatize with a script). When you don't keep track of where your assets came from, then you might years later find yourself in the uncomfortable situation that you have to search every single asset site you can think of for hours to again find that !#$%& grass texture you used so you can credit it appropriately.

# Answer
> 4 votes
Exact terms will vary depending on the particular variant of CC license involved.

---

Generally speaking, you will need to include, for ***each*** individual asset:

* a copyright statement; and
* a link to the material; and
* the terms under which use of the asset is granted; and
    + this may entail either inlining the full license text or simply providing a hyperlink to it
* the author's name (may be included in above).

Some versions of the license may require inclusion of the asset's name in addition to or instead of a hyperlink.

Attribution should be reasonably visible (technically "reasonable to the means, medium, and context of use"). In the context of game-dev, this often means including credits accessible from the title screen, launcher, or alongside a readme.

---

You can learn the specifics for each particular CC license at the Creative Commons website.

The Creative Commons site also provides examples on how attribution should be given:

> “Furggelen afterglow” by Lukas Schlagenhauf is licensed under CC BY-ND 2.0.

> This is an ideal attribution because it includes the:
>
> Title: “Furggelen afterglow”
>
> Creator: “Lukas Schlagenhauf“—with a link to their profile page
>
> Source: “Furggelen afterglow“—with a link to the original photo on Flickr
>
> License: “CC BY-ND 2.0”—with a link to the license deed

---
Tags: assets, copyright, licensing
---


title: moving an object around a Circle

text:
# Question
Title: moving an object around a Circle
I am going to draw a shape like a gear, how can I move a tooth around a circle? Something like the image below :

For example, I need to draw 20 teeth at equal intervals around a circle with a diameter of 50 mm. I am doing this for a G-code generator program I draw a tooth first ,Then it is necessary to draw these teeth, which can be adjusted to the desired number by the user, according to the diameter of the gear wheel around a circle For example, this is a G-code for drawing one tooth :

```
G90
G21
G1 X0 Y0
G1 X5 Y10
G1 X10 Y10
G1 X15 Y0

```

You can view the output using this site : https://ncviewer.com/

What is the equation to do this? I am currently programming using Lua language

# Answer
> 2 votes
This is a pretty conventional application of a transformation matrix.

First, we need a matrix that translates the center of the gear to the origin:

$$\mathbb{T} = \begin{bmatrix} 1 & 0 & -C\_x\\ 0 & 1 & -C\_y\\ 0 & 0 & 1 \end{bmatrix}$$

Then we rotate by the desired angle \\$\theta\\$ around the origin:

$$\mathbb{R}\_\theta = \begin{bmatrix} \cos \theta & -\sin \theta & 0\\ \sin \theta & \cos \theta & 0\\ 0 & 0 & 1 \end{bmatrix}$$

Then we reverse our translation to put the whole gear back where we started.

Composing these matrices, we get...

$$\begin{align}\vec v^\prime &= \mathbb T^{-1}\mathbb R\_\theta \mathbb T \vec v\\ &= \begin{bmatrix}1 & 0 & C\_x\\0&1&C\_y\\0&0&1\end{bmatrix} \begin{bmatrix}\cos \theta & -\sin \theta & 0\\\sin \theta & \cos \theta & 0\\0&0&1\end{bmatrix} \begin{bmatrix}1 & 0 & -C\_x\\0&1&-C\_y\\0&0&1\end{bmatrix}\begin{bmatrix}v\_x\\v\_y\\1\end{bmatrix}\\ &= \begin{bmatrix}\cos \theta & -\sin \theta & C\_x\\\sin \theta & \cos \theta & C\_y\\0&0&1\end{bmatrix} \begin{bmatrix}1 & 0 & -C\_x\\0&1&-C\_y\\0&0&1\end{bmatrix}\begin{bmatrix}v\_x\\v\_y\\1\end{bmatrix}\\ &= \begin{bmatrix}\cos \theta & -\sin \theta & -C\_x\cos \theta + C\_y \sin \theta + C\_x \\\sin \theta & \cos \theta & -C\_x \sin \theta - C\_y \cos \theta + C\_y\\0&0&1\end{bmatrix} \begin{bmatrix}v\_x\\v\_y\\1\end{bmatrix}\\ &= \begin{bmatrix}v\_x \cos \theta - v\_y \sin \theta -C\_x\cos \theta + C\_y \sin \theta + C\_x\\v\_x \sin \theta + v\_y \cos \theta -C\_x \sin \theta - C\_y \cos \theta + C\_y \\1\end{bmatrix}\\ \end{align}$$

That gives you the formula for the x and y coordinates of a point \\$\vec v\\$ after this transformation. You can ignore the third row - it's just there to make the translation work.

Whether there's a nicer way to do this in G-code is a question for someone other than a game developer.

---
Tags: mathematics, graphics-programming, lua
---


# Question
Title: How to sequence Animators for a list of GameObjects in Unity?
I created a Prefab called White Letter and added an Animator to it to create the illusion of falling letters.

I use this Prefab to generate words; here's an animated gif of what it looks like in action:

The animation basically turns the Mesh Renderer On and Enables the Audio Source, and then dynamically alters the Font Size and Offset over 30 frames to make it look like it's falling:

I took each of the White Letters (and the dot) and put them into a List of GameObjects. Then "For Each" GameObject on the List, I triggered the animation.

The problem I'm running into is that at first, all of the animations ran at the same time. So to get around that, I added a "Wait for 1 second" to the end of my For Each loop.

This worked but is not elegant and doesn't offer fine-grained control over the animation timings.

Ideally I would like to have better control over the animation timing. For example, I'd like the X to fall... and then at a certain frame of its fall, I'd like to trigger the animation for the next letter (the dot). Etcetera.

Basically while the Animator of one GameObject is executing, I'd like to be able to trigger the Animator of the next GameObject (in my list).

Any advice on how to achieve this?

# Answer
> 1 votes
If you had a fixed sequence of falling glyphs, then I would do this with the optional Timeline package. But due to the fact that you want to support arbitraty strings of unknown length, this isn't going to work too well, because you would need to create a separate timeline for each string. Well, you *could* generate the timeline procedurally, but then you would miss out on the visual editor, which is the main reason to use this in the first place.

So in this case I would recommend to use animation events. Animation events allow you to place points in the Animation window which trigger C# methods when reached. So you can have the animation for an individual glyph and at (or near) the end of the animation place the animation event that calls the method which spawns the next glyph in the string.

---
Tags: unity, animator
---