title: Fade-in sprite in TextMeshPro

text:
# Question
Title: Fade-in sprite in TextMeshPro
```
public IEnumerator FadeTextmeshproIn(float t, TextMeshProUGUI text)
{
    text.color = new Color(text.color.r, text.color.g, text.color.b, 0);
    TMP_SpriteAsset spriteAsset = text.spriteAsset;
    spriteAsset.material.color = new Color(spriteAsset.material.color.r, spriteAsset.material.color.g, spriteAsset.material.color.b, 0);

    while (text.color.a < 1.0f)
    {
        text.color = new Color(text.color.r, text.color.g, text.color.b, text.color.a + (Time.deltaTime / t));
        spriteAsset.material.color = new Color(spriteAsset.material.color.r, spriteAsset.material.color.g, spriteAsset.material.color.b, spriteAsset.material.color.a + (Time.deltaTime / t));
        yield return null;
    }
}

```

This is a function I am using to fade-in a TextMeshPro component. The TextMeshPro is composed of a sprite and a text, as shown in the images below.

However, when the function is called, only the text fades in, and the sprite never appears, as shown in the gif below. I can't seem to find a way to make them both fade in together.

Also note that I would like to keep them in the same component, because splitting them up into two components would make it hard to keep the spacing between them the same as the score next to it gets higher.

# Answer
You can try to use Image color instead of changing material color (all elements using the same material will fade) maybe you set color alpha of the same material to zero in the else code thats why it never fade in. Just use

```
UnityEngine.UI.Image img;

```

and set  `img.color= new Color(r,g,b,a)` instead. It will set color of selected image only.
> 0 votes

---
Tags: c#, animation, sprites, text, unity-ui
---


# Question
Title: Random Grid Generation with Random Density
I have a 2D grid of cells in Unity, and each cell can be on or off. I want to randomly generate the on cells, and when I just assign a probability to each cell, the entire grid has the same density, looking something like this:

But I would like different densities for random areas, something more like:

Is there some kind of algorithm to make this random generation possible?

# Answer
Use `Mathf.PerlinNoise` todo it , example here:

```
float Perlin(float x, float y)
{
        for(x; x< ChunkSize; x++)
       {
                for(y; y < ChunkSize; y++)
                {
                        return Mathf.PerlinNoise(x,y);
                 }
         }
}

```

https://forum.unity.com/threads/mathf-perlinnoise-a-way-to-random-seed-it.336147/
> 2 votes

# Answer
You can just set the densities probability to each area so you will get result close to your second picture. Write the algorithm to separate the gird on areas. for example you have 8x8 grid and areas:

```
11122333
11122333
44422555
44466555
44466555
77888888
77888888
77888888

```

Generate probablity for each area: 1)p=80% 2)p=30% 3)p=45% etc. And you can customize it for your needs.
> 0 votes

---
Tags: unity, procedural-generation, random
---


# Question
Title: Does Steam notify the user that they need Java for a game when they buy/download/install it?
My mate and I are gonna make a game for Steam and I, as the programmer, want to use Java as that is my current favorite language. So I need to know, does Steam notify the user that they need Java for a game when they buy/download/install it?

# Answer
To answer your question directly, no Steam doesn't notify the purchaser that the game needs Oracle's Java Runtime Environment installed to play the game. That's because there shouldn't be any need to, any game that has a dependency on the JRE will download and install it as part of the normal Steam installation procedure. This is no different than games that have dependencies on Microsoft's Visual Studio, DirectX or .NET runtime. There is even a standard JRE depot that you can use.

That said, I personally refuse to buy or install any game that dependent on Oracle's JRE. I don't want to have to deal with that nonsense. An alternative route would follow Minecraft's lead an include a Java VM as part of the game itself. That is, instead of installing a VM for all Java applications on the machine to use, like with the Oracle JRE, you install a VM side-by-side your game that only your game uses. I don't think you can do this with the Oracle JRE, I believe Minecraft uses one based on OpenJDK.

On the other hand, if you're just starting out, you should probably take the easy route and use the standard Oracle JRE install, and just accept some people won't like that.
> 20 votes

# Answer
*This is by no means an answer, but some points to consider. It did not fit in the comments box.*

I would think that even if you were to use c++, you would need to ship your game with a bunch of Redistributable, at least on Windows. Unless you can manage to not use Visual Studio tools and such. I don't know what happens for Mac users.

And if you go with Java, I believe there would be a way to ship the JVM with your game. This would increase the download size, but it would ensure

1. that the client has a jvm, and
2. that the client has the *correct* jvm version for your game

Note that it is already necessary to ship the JVM with the game if you are distributing through the Mac App Store, so if you plan on distributing beyond Steam, this may be necessary anyway.
> 14 votes

# Answer
This related question recommends using launch4j.

Based on 3 Ring's code page, it looks like they use getdown for Spiral Knights.

You might consider reaching out to Puppy Games to see if they're willing to share any insights. Similarly, there are some devs on java-gaming.org that have some experience with this.
> 5 votes

# Answer
You just have to make your custom Java and put it inside the install EXE along with your JAR file to put it on steam.
> 0 votes

---
Tags: java, steam
---


title: Unity Application.Quit() doesn't work

text:
# Question
Title: Unity Application.Quit() doesn't work
In the update, I have set up a counter so that after 140 frames, Unity will quit the game. But this quit command doesn't quit and it just continues to play the game. What am I doing wrong? I am using and testing in Unity 2D. There are no errors and all the prints are visible.

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

public class Normal_Car : MonoBehaviour
{
    private int counter = 0;

    public Vector3 finalPos = new Vector3(0.00f,0.00f,0.00f);

    public Transform t;

    // Start is called before the first frame update
    void Start()
    {
        t.GetComponent<Transform>();
    }

    // Update is called once per frame
    void Update()
    {
        print("Frame: " + counter.ToString());
        counter += 1;
        t.position += finalPos;
        if(counter >= 140)
        {
            Application.Quit();
            print("Quit!");
        }
    }
}

```

# Answer
> 1 votes
If you check out the documentation for `Application.Quit` it starts by saying this:

> Quits the player application. Shut down the running application. The Application.Quit call is ignored in the Editor.

`Application.Quit` does nothing if you test inside the editor.

# Answer
> 2 votes
There were some comments here but no actual solution. The answers of course exist by searching but not in this post.

The ability to exit the game in BOTH standalone and editor mode is important for testing menus and other factors. Here is an example:

```
public void ExitGame()
{
    SaveGame();

    #if UNITY_STANDALONE
        Application.Quit();
    #endif

    #if UNITY_EDITOR
        UnityEditor.EditorApplication.isPlaying = false;
    #endif
}

private void SaveGame()
{
    Debug.Log("Saving Game...");
}

```

Hopefully this clarifies things a bit

# Answer
> 0 votes
I think it's this.Quit(); That might just be in WinForms though :)

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


# Question
Title: How does clearing full rows work in tetris?
I'm working on my tetris game, and I'm a bit confused on the aftermath of clearing a full row. In some implementations, clearing a row, shifts all the rows above it down one row. That's how I originally envisioned implementing it, but I don't think it's quite that simple.

e.g., let's take a look at this video starting at 33:34

You can see that the L piece (full of Fs) is dropping down and it forms a full row which gets cleared, and then all the rows above it are shifted downwards by 1. However, I don't think this is quite correct because you end up with "floating" pieces, e.g., take a look at the 4th row from the bottom "A GF G#". The first G is floating in space. Shouldn't it be translated all the way down to fill the gap? This makes the this functionality a bit more complicated to implement but feels more correct to me.

# Answer
Again, it works however the game designer defines it. Line clear gravity varies by implementation and sometimes the game mode. The video you linked appears to be using naive gravity as it leaves floating unconnected blocks after a line clear:

The alternative you describe sounds like cascade mode gravity:

as the system is recursive - it clears the line and then reapplies gravity to check for subsequent line clears.

The sticky mode variant modifies this further by using color coding to change both the gravity and clearing rules. Sticky includes some multi-colored pieces which break into smaller pieces of separate colors when they lock. Blocks of the same color glue themselves together; any contiguous group of the same color with 25 or more blocks disappears. Anything with nothing supporting it falls, just as in cascade mode.

Naive gravity is easer to code and limits player strategy with respect to field management. Other modes typically more complex and provide the player with more options. For instance the naive gravity example is a favorable option with cascade gravity as it will result in a subsequent line clear.

Variations allow us to tune the play experience by making design choices. For instance, allowing cascades provides a wider move set to the player and rewarding cascade chains incentives certain types of play.

There are many variants of Tetris. Which is 'correct' depends on your design priorities (type of play are you favoring) and constraints (resources required to build/test/maintain a more complex system).
> 2 votes

---
Tags: tetris
---


# Question
Title: Is Unity Built-in Render Pipeline the default option, which includes mobile/diffuse shader?
I have been using mobile/diffuse shader in my project for awhile. However, I am not yet familiar with the term "**Built-in Render Pipeline**".

Is it true that "**Built-in Render Pipeline**" is the default option in Unity, and it also includes **mobile/diffuse** shader along with other default shaders such as standard, sprite, etc... ?

I know that URP and HDRP do not include mobile shaders.

# Answer
Yes, the Built-In Render Pipeline is the one you get by default in Unity if you don't start with the URP or HDRP project templates, or deliberately instal the scriptable render pipeline package.

While URP does not have default shaders called "mobile", the whole pipeline together with its default shaders is designed to be "universal" — i.e. working well on a range of platforms, including mobile.
> 1 votes

---
Tags: unity, shaders
---


# Question
Title: What does this (Unity) NavMesh gizmo mean? (Reddish pixels in front of Agent)
Basically question. I've never seen this gizmo before. Though something I know is that my agent is failing at what's supposed to be doing. So, perhaps an error gizmo? But what kind of error?

# Answer
Part of me thinks this might be the gizmo for an Obstacle. Which is when you have an object that you want to move around that effects the shape of your Navmesh dynamically (So it updates the Navmesh as the obstacle moves through it) So you could have something like a moving door that opened and shut. I think there is an option in the Inspector to turn this on / off somewhere. But yes as DMGregory stated, would be really useful to have the steps leading up to this, to be able to advise properly.
> 0 votes

---
Tags: unity, navmesh
---


# Question
Title: How can I resize pixel art in Pyglet without making it blurry?
I have a tileset of 8x8 pixel images, and I want to resize them in my game so they'd be double that (16x16 pixels, e.g. turning each pixel into a 2x2 block.) What I'm trying to achieve is a Minecraft-like effect, where you have small pixel images scale to larger blockier pixels.

In Pyglet, the sprite's `scale` property blurs the pixels. Is there some other way?

**Working Code:**

Here's the solution that works (thanks to DMan's persistence and Jimmy's insight):

```
image = resource.image('tileset.png')
texture = image.get_texture()
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)
texture.width = 16 # resize from 8x8 to 16x16
texture.height = 16
texture.blit(100, 30) # draw

```

# Answer
At the request of commenters...

*Warning to Pyglet professionals: There may be a nice Pyglet way to do this, and this isn't it. It's a nice OpenGL way. You have been warned!*

You can do this in OpenGL by first binding the texture, then calling `glTexParameteri` or similar varients. You can do this in Pyglet by importing OpenGL:

`from pyglet.gl import *`

You can then enable `GL_TEXTURE_2D` to set the target. This is not always needed, but I'm keeping this complete for some other bindings.

`glEnable(GL_TEXTURE_2D)`

In Pyglet, it seems like you don't have to bind the texture either. Sometimes you have to load in your image, get the texture id, then use `glBindTexture(GL_TEXTURE_2D, texture.id)`. My assumption that these are already the state set for you in Pyglet.

The next step is to call `glTexParameteri`. Thanks to Jimmy on correcting me on this: the correct call is:

`gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)`

A quick break down: the first is just to set the target so OpenGL knows what you're talking about, then the second parameter is the type of filter you would like to set. `MAG_FILTER` is correct because it controls the magnifications of textures. The final parameter is `GL_NEAREST`, which controls how the texture is scaled. `GL_NEAREST` is basically a fast scale that gives pixel-styled textures. `GL_LINEAR` is normal and will instead smoothly blur your texture.

This version of OpenGL I'm talking about (about \< OpenGL 3.2 officially) uses immediate mode, which sets the state. Now that the state is set, you can scale your texture. I can see no better than to show the code that Renold himself posted as working code.

```
image = resource.image('tileset.png')
texture = image.get_texture()
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)
texture.width = 16 # resize from 8x8 to 16x16
texture.height = 16
texture.blit(100, 30) # draw

```
> 9 votes

# Answer
For those like me, who are simply making a retro-style game where they want EVERYTHING scaled to be pixelated, the simple quick answer is start your code with:

```
from pyglet.gl import *
glEnable(GL_TEXTURE_2D)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)

```

Then all your usage of sprites, etc. from there on out stay nice and pixelated.
> 4 votes

# Answer
Modern pyglet lets you set the default texture filtering by modifying a couple class attributes on `Texture`. Pyglet docs even explicitly mention "retro style pixel art games".

Here's an example. With the following project structure...

```
asteroids/
    game/
        __init__.py
        asteroid.py
        player.py
        resources.py
    resources/
        asteroid.png
        flame.png
        spaceship.png
    asteroids.py

```

...you can have the following code in `asteroids.py` (the main game logic, where you first import pyglet):

```
# Set default texture filtering for pixel art.
from pyglet.gl import GL_NEAREST
from pyglet.image import Texture

Texture.default_mag_filter = Texture.default_min_filter = GL_NEAREST

# Do your other imports.
import pyglet

from game import asteroid, player, resources

```

Now your pixel art scales nicely.
> 2 votes

---
Tags: python, image, pyglet
---


title: Why do a lot of games use DirectX9

text:
# Question
Title: Why do a lot of games use DirectX9
A lot of older games use DirectX9 which makes sense, however several modern games such as Sonic Mania, Terraria and Undertale all use DirectX9. Is there some benefit to using an older version of the api?

# Answer
The vast majority of game developers today don't deal with graphic APIs like DirectX, OpenGL, Mantle or Vulkan directly. They delegate that to a library or game engine, so they can focus on the fun part (the actual gameplay). This is the case for two of three examples in this question. Terraria is built in XNA. Undertale is built in GameMaker. Only Sonic Mania uses an inhouse engine (which Christian Whitehead developed specifically for Sonic fangames in 2007 and probably didn't make substantial changes to after it worked).

But game engines tend to be a bit behind the newest APIs. That's because modern game engines are extremely complex pieces of software. Transitioning to newer graphics APIs costs a ton of developer hours and can break a lot of things. So they tend to have a more conservative approach to this. This is especially the case with game engines that focus on 2d (like GameMaker Studio, which was used for Undertale). While newer APIs open up a lot of cool new possibilities for 3d graphics, their innovations for classic 2d graphics are pretty much negligible.

And in addition to that, game developers also tend to be a bit behind the latest versions of their game engines. One reason for that is a common mantra in game development: "Never update your engine during a project". The reason is that upgrading to a newer version of a game engine can break a lot of things. Things you wouldn't expect. So unless you have a very good reason to upgrade your game engine version (like a fix for a bug that affects your game or a new feature that would make development measurably easier), you usually try to stick with the version you started the game with.

Another reason is that many games are built upon already created technology for their respective game engines. They might use 3rd party plugins or inhouse systems that only run on older versions of the engine. Replacing or updating those technologies might cause more work than the benefits of upgrading to a newer version of the engine. So they remain stuck with their version of the engine.

Licensing might also be an issue. Some game engines only license a specific major version, and when they release a new major versions, they want people to pay again for switching. RPGMaker is known for this business model. Other game engines might occasionally change their license conditions for newer versions in ways some developers don't agree with, so developers get around those new conditions by not updating. For a recent example, there is speculation that the current Unity version 2023.3 will turn into such an "eternal release", because Unity announced a new "runtime fee" that will be charged per sale/download from the next version on.
> 3 votes

# Answer
I can't answer this definitively as I don't use DirectX, but two reasons I can think of:

* support for more (older) systems,
* if they don't need the new features of later versions, why put in the engineering effort (as long as DirectX9 is still supported by the OS).

There may be other benefits specific to DirectX - other answers will have to address those.

In what I'm guessing is an analogous situation, I'm developing with Vulkan 1.0 rather than the later versions, for those two reasons.
> 1 votes

---
Tags: directx, directx9
---


# Question
Title: Can we use Universal RP shaders for some objects and Mobile shaders for other objects in a Unity scene?
I am sorry if this question sounds silly. But, I am new to Universal RP shaders, and have to ask this question.

---

Previously, in my project, I had many beautiful objects that use Mobile shaders.

Today, I upgrade my project to use Universal RP shaders because I have just bought a Unity asset that requires URP shaders. So, I upgrade my project to use URP.

But, after that, all my old objects, which previously used Mobile shaders, now have the **PINK** color, which means that Mobile shaders do not work for them any more.

Therefore, I have to convert all of my old materials to URP. Now, the problem is that these old objects look much less beautiful than before because they use URP shaders (and NOT the Mobile shaders).

---

My "**silly**" question is this: Can we use Universal RP shaders for some objects and Mobile shaders for other objects in a Unity scene ?

If the answer is **NO**, are there other good alternatives instead ?

# Answer
No, you can't. Shaders are always developed for a specific render pipeline. And your project can only use one render pipeline at a time. So if you want to migrate your project to the URP, you have to replace **all** the shaders with URP shaders. Otherwise they are rendered as solid magenta.

When switching render pipelines, then the automatic material conversion is in many cases rather unreliable. And it is often difficult to find a replacement shader that looks *exactly* like the previous one. Unity recommends the Simple Lit Shader as a drop-in replacement for all the mobile shaders of the build-in pipeline. But not every material property of these shaders has an exact equivalent in this new shader. So it usually takes some experimentation and meticulous tweaking of material parameters to make everything in the game look the same (or at least as good) as before.
> 1 votes

---
Tags: unity, shaders, unity-urp
---


# Question
Title: Cannot convert bool to System.Func<bool>
When I run this script in Unity: (ignore the clones variable)

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

public class Throw : MonoBehaviour
{
    public Rigidbody rb;

    private float clones = 0;

    public KeyCode throwKey = KeyCode.Mouse0;
    private void Update()
    {
        if (transform.parent != null)
        {
            gameObject.name = "Wood";
            rb.isKinematic = true;
            if (Input.GetKeyDown(throwKey))
            {
                Vector3 position = new Vector3(transform.parent.position.x, transform.parent.position.y, transform.parent.position.z);
                Instantiate(gameObject, position, Quaternion.Euler(0, 0, 0));

                rb.AddForce(transform.forward * 500f, ForceMode.Impulse);
                transform.SetParent(null);
                StartCoroutine(Wait());
            }
        }
        else
        {
            gameObject.name = "thrownWood";
            rb.isKinematic = false;
        }
    }

    IEnumerator Wait()
    {
        yield return new WaitUntil(Input.GetKeyUp(throwKey));
    }
}

```

It comes up with the error message:

Any idea for why this happens?

# Answer
> 1 votes
When you follow a function with open and close parentheses, you are calling that function and taking its return value as the result of the expression.

So here, where you meant to pass a reference to the function, you instead called the function once, got a single bool value (true or false), and tried to pass that bool value as a waiting condition when a function (a rule for *choosing* a bool) was needed.

You can fix it like so:

```
bool WaitCondition() {
    return Input.GetKeyUp(throwKey);
}

IEnumerator Wait() {
    yield return new WaitUntil(WaitCondition);
}

```

Note that there's no `()` after `WaitCondition` when we pass it to `WaitUntil` — we're referring to the function, not calling/invoking it to get its return value.

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


# Question
Title: How to use handles for asset management?
The way I've learned to implement an asset manager is having unordered maps for each asset type (textures, shaders, meshes, etc.), each with a string key and object value and then having methods `Add()`, `Get()`, `Load()` for each asset type. For my skill level and the scale of projects I'll be doing this is probably good enough, however, I came across a blog that uses the concept of handles which I found quite interesting. It shows a handle as a wrapper around a `uint32_t` and then goes on about a manager class that follows a similar structure to what I said.

What I don't understand about this approach is how do you associate a handle with a object? With the method I've been using since it's just strings I can easily create an object and store the ID in it

```
AssetManager::AddTexture("Textures/player.png", "PlayerTexture");
AssetManager::AddMesh("Meshes/player.obj", "PlayerMesh");

// This could technically be written anywhere
Scene::AddObject(GameObject("Player", "PlayerTexture", "PlayerMesh"));

AssetManager::GetMesh(Object.MeshName);

static Mesh GetMesh(std::string ID) {
    return  meshes[ID];
}

```

But with handles wouldn't I need to make my object right after loading the asset? Or how else am I supposed to get the handle to the object unless I continue to use string IDs but for the handles, but I feel like that would defeat the purpose. Here's an example of trying to understand using handles.

```
TextureHandle playerTextureHandle = AssetManager::AddTexture("Textures/player.png");

// Needs to be here so I can access the variable
Scene::AddObject(GameObject("Player", playerTextureHandle));

AssetManager::GetTexture(Object.textureHandle);

struct TextureHandle {
    unsigned int handle;
}

static Texture GetTexture(TextureHandle handle) {
    return textures[handle.handle];
}

```

Writing this post another potential problem might be the fact I don't understand what a handle fully is so I have a feeling I might not be using it in the intended way.

# Answer
> 2 votes
My favorite fast food restaurant recently refactored their ordering process.

You used to go to the counter, order your food, and then stand there and wait while you wait for the food, and everyone else who is hungry waits in line behind you.

But now you go to the counter, say what you want, pay, and then you receive a receipt with a number on it. Then you wait with your number in hand, while the employee at the counter serves other customers and hands them receipts with numbers as well. You wait until your number gets called, go to a different counter, show them your number, and receive your food. Or when your number doesn't get called, you can go to that counter, show them your number and ask what takes so long. Or when you have a complaint, you can go to the manager, show them your number, and tell them you want your money back.

What does that have to do with your question, you ask?

The number of the receipt is a **handle** for a food order. It's a convention for communicating between the consumer and the restaurant regarding what food order they are talking about. Which is crucial, because without such a convention this asynchronous food serving process would end up in chaos.

So how would you adapt that process to asset handling in a game engine?

* The consumer goes to the AssetManager and asks them "I would like to have one `Resources/Textures/Environment/Walls/BrickWall.png`, please."
* The AssetManager looks into its array of loaded textures. There are three possible cases: Either the texture is already loaded, it is in the process of being loaded, or the consumer is the first one to ask for it. In the first two cases, it would return the index of the texture. In the last case, it would find a new index for that texture, initiate the loading process on a separate thread, and return the new number.
* When the consumer now *actually* needs that texture, they again ask the asset manager: "Here is my number, is the texture ready yet?". The manager then either responds with a reference to the loaded texture, tells the consumer that the texture is still being loaded, or throws an exception because they don't even know the number the consumer provided.

Now you might wonder "Why convert the name of the texture to an ID number? Why not always ask the AssetManager for `"Resources/Textures/Environment/Walls/BrickWall.png"` all the time? Isn't that a lot more convenient?" Well, the problem is that a `std::unordered_map` with a string key is relatively slow. Because in order to find the right value, it has to perform a lot of string comparisons. And a string comparison means to compare every character in string A with every character in string B until there is a difference. Which can take a while if you are using very long strings that often start identical. This is not a problem if you do it occasionally, but it is a problem when you do it every single frame for every single wall segment that's on the screen.

But do you know what's the fastest way to find a value? Jumping to a specific array index. So if your values are in an array, and you know the index, then that lookup is lightning-fast. Fast enough that it is usually not a problem to do it in your inner loop.

---
Tags: c++, architecture, asset-management
---


# Question
Title: Why doesn't multi-constraint work in this case?
The situation is as follows:

There are two objects and there are 3 constraints between the two objects.

> $$ \dot{C}=(\vec{V}\_{rel\_a} - \vec{V}\_{rel\_b}) \cdot normalize(\vec{p\_{a}} - \vec{p\_{b}}) $$ "Pa" and "Pb" is constraint point on object, "V\_rel" is relative velocity of constraint point

I used the formula in the picture below to calculate and the calculated result was incorrect. Why is this?

The result is that the constraint equation is not satisfied, and the relative velocities of the three constraint points are not equal.

---

this is test data:

```
    float fMass1 = 100;
    float fMass2 = 100;
    const VECTOR3<float> vCenter[] = { VECTOR3<float>(0, 9, 0), VECTOR3<float>(0, 0, 0) };
    const VECTOR3<float> ContactPoint[] = { VECTOR3<float>(-3, 4.5, -3), VECTOR3<float>(-3, 4.5, 3), VECTOR3<float>(3, 4.5, -3), VECTOR3<float>(3, 4.5, 3) };
    const VECTOR3<float> vSize = VECTOR3<float>(6, 9, 6);

    VECTOR3<float> vVelocity1           = VECTOR3<float>(0, 20, 0);
    VECTOR3<float> vAngularVelocity1    = VECTOR3<float>(0, 0, -3);

    VECTOR3<float> vVelocity2           = VECTOR3<float>(0, 80, 0);
    VECTOR3<float> vAngularVelocity2    = VECTOR3<float>(10, 0, 0);

```

this is core code:

```
template<typename T>
void VelocityMultipleConstraint(const VelocityConstraintParameter<T>* param)
{
    MATRIX<3, 12, double> Jacobian;
    MATRIX<12, 12, double> InverseMass;
    MATRIX<12, 1, double> Velocity;

    for (int i = 0; i < 3; i++) {
        Jacobian(i, 0) = param[i].vDirection.x;
        Jacobian(i, 1) = param[i].vDirection.y;
        Jacobian(i, 2) = param[i].vDirection.z;

        const VECTOR3<T> vRadiusObject1 = param[i].vObj1ContactPoint - param[i].vBarycenter1;
        const VECTOR3<T> vRadiusCrossNormal1 = cross(vRadiusObject1, param[i].vDirection);

        Jacobian(i, 3) = vRadiusCrossNormal1.x;
        Jacobian(i, 4) = vRadiusCrossNormal1.y;
        Jacobian(i, 5) = vRadiusCrossNormal1.z;

        Jacobian(i, 6) = -param[i].vDirection.x;
        Jacobian(i, 7) = -param[i].vDirection.y;
        Jacobian(i, 8) = -param[i].vDirection.z;

        const VECTOR3<T> vRadiusObject2 = param[i].vObj2ContactPoint - param[i].vBarycenter2;
        const VECTOR3<T> vRadiusCrossNormal2 = cross(-vRadiusObject2, param[i].vDirection);

        Jacobian(i, 9) = vRadiusCrossNormal2.x;
        Jacobian(i, 10) = vRadiusCrossNormal2.y;
        Jacobian(i, 11) = vRadiusCrossNormal2.z;
    }
    InverseMass(0, 0) = param[0].fInverseMass1;             InverseMass(1, 1) = param[0].fInverseMass1;                 InverseMass(2, 2) = param[0].fInverseMass1;
    InverseMass(3, 3) = param[0].mtInverseInertia1(0, 0);   InverseMass(3, 4) = param[0].mtInverseInertia1(0, 1);       InverseMass(3, 5) = param[0].mtInverseInertia1(0, 2);
    InverseMass(4, 3) = param[0].mtInverseInertia1(1, 0);   InverseMass(4, 4) = param[0].mtInverseInertia1(1, 1);       InverseMass(4, 5) = param[0].mtInverseInertia1(1, 2);
    InverseMass(5, 3) = param[0].mtInverseInertia1(2, 0);   InverseMass(5, 4) = param[0].mtInverseInertia1(2, 1);       InverseMass(5, 5) = param[0].mtInverseInertia1(2, 2);

    InverseMass(6, 6) = param[0].fInverseMass2;               InverseMass(7, 7) = param[0].fInverseMass2;               InverseMass(8, 8) = param[0].fInverseMass2;
    InverseMass(9, 9) = param[0].mtInverseInertia2(0, 0);     InverseMass(9, 10) = param[0].mtInverseInertia2(0, 1);     InverseMass(9, 11) = param[0].mtInverseInertia2(0, 2);
    InverseMass(10, 9) = param[0].mtInverseInertia2(1, 0);     InverseMass(10, 10) = param[0].mtInverseInertia2(1, 1);     InverseMass(10, 11) = param[0].mtInverseInertia2(1, 2);
    InverseMass(11, 9) = param[0].mtInverseInertia2(2, 0);     InverseMass(11, 10) = param[0].mtInverseInertia2(2, 1);     InverseMass(11, 11) = param[0].mtInverseInertia2(2, 2);

    Velocity(0, 0) = param[0].vVelocity1.x;         Velocity(1, 0) = param[0].vVelocity1.y;            Velocity(2, 0) = param[0].vVelocity1.z;
    Velocity(3, 0) = param[0].vAngularVelocity1.x;  Velocity(4, 0) = param[0].vAngularVelocity1.y;     Velocity(5, 0) = param[0].vAngularVelocity1.z;
    Velocity(6, 0) = param[0].vVelocity2.x;         Velocity(7, 0) = param[0].vVelocity2.y;            Velocity(8, 0) = param[0].vVelocity2.z;
    Velocity(9, 0) = param[0].vAngularVelocity2.x;  Velocity(10, 0) = param[0].vAngularVelocity2.y;     Velocity(11, 0) = param[0].vAngularVelocity2.z;

    MATRIX<3, 1, double> Lambda = inverse( Jacobian * InverseMass * Jacobian.transpose()) * (-Jacobian * Velocity);

    MATRIX<12, 1, double> DeltaV = InverseMass * Jacobian.transpose() * Lambda;

    *param[0].pOutVelocity1          = VECTOR3<float>(param[0].vVelocity1.x + DeltaV(0, 0), param[0].vVelocity1.y + DeltaV(1, 0), param[0].vVelocity1.z + DeltaV(2, 0));
    *param[0].pOutAngularVelocity1   = VECTOR3<float>(param[0].vAngularVelocity1.x + DeltaV(3, 0), param[0].vAngularVelocity1.y + DeltaV(4, 0), param[0].vAngularVelocity1.z + DeltaV(5, 0));
    *param[0].pOutVelocity2          = VECTOR3<float>(param[0].vVelocity2.x + DeltaV(6, 0), param[0].vVelocity2.y + DeltaV(7, 0), param[0].vVelocity2.z + DeltaV(8, 0));
    *param[0].pOutAngularVelocity2   = VECTOR3<float>(param[0].vAngularVelocity2.x + DeltaV(9, 0), param[0].vAngularVelocity2.y + DeltaV(10, 0), param[0].vAngularVelocity2.z + DeltaV(11, 0));

}

```

This is the relative velocity of the center of mass of the three constraint points:

```
constraint point : 0
before : 1 :{x=-13.5000000 y=29.0000000 z=0.00000000 ...} 2 : {x=0.00000000 y=110.000000 z=45.0000000 ...}
constraint point : 1
before : 1 :{x=-13.5000000 y=29.0000000 z=0.00000000 ...} 2 : {x=0.00000000 y=50.0000000 z=45.0000000 ...}
constraint point : 2
before : 1 :{x=-13.5000000 y=11.0000000 z=0.00000000 ...} 2 : {x=0.00000000 y=110.000000 z=45.0000000 ...}
after : 1 : {x=5.06883144 y=45.9733505 z=0.528086662 ...} , 2 : {x=-9.93715286 y=54.8153305 z=-10.8799744 ...}
after : 1 : {x=-3.84213710 y=38.4656563 z=0.528086662 ...} , 2 : {x=-1.02618432 y=61.1101532 z=-10.8799744 ...}
after : 1 : {x=5.06883144 y=42.5455589 z=9.43905544 ...} , 2 : {x=-9.93715286 y=57.8786316 z=-19.7909431 ...}

```

***According to the constraint equation, the velocities of the three constraint points should be equal.***

This is the full source code on GitHub

# Answer
I saw your message on Discord and responded, albeit kind of late. Apologies. Here's the copy of the response.

Given multiple contact constraint points between two rigid bodies, it is normal that they have different linear and angular velocity, unless there is an additional constraint to fix the relative rotation between the two bodies.
> 0 votes

---
Tags: c++, physics, physics-engine, rigid-body-dynamics
---


# Question
Title: Should I care about appropriate variable/integer literals in C++?
I'm developing a C++ game engine. A question has popped to my head. Let's imagine this constructor:

```
Vector2f::Vector2f(float x, float y)
: x(x), y(y) {}

```

We can call in those 2 ways:

```
Vector2f(2.0, 3.5); //option 1
Vector2f(2.0f, 3.5f); //option 2

```

When in Visual Studio I hold my mouse over *right values* passed to constructor it says *(double)(2.0)* or *(double)(3.5)* or *(float)(2.0f)* *(float)(3.5)*. So I guess it makes some conversions on fly. **Should I care about this?** Or maybe simply compiler will optimize this anyway. Beacuse this seems like premature optimization but I guess I could switch to use appropriate literals anywhere where I deal with *right values*. This question also expands to using 'u' suffix etc. when writing code like this:

```
for (size_t i = 0u; i < max; i++) //this?
for (size_t i = 0; i < max; i++) //or this?

```

# Answer
> 1 votes
This code will throw warning 4305: https://learn.microsoft.com/en-us/cpp/error-messages/compiler-warnings/compiler-warning-level-1-c4305?view=msvc-170

This is a Level 1 warning so it should be thrown by your compiler in all cases unless you have warnings (or this specific warning) disabled.

The main thing to worry about here is that there may be truncation of the value (or loss of precision) due to conversion from a higher-precision to a lower-precision data type, but that obviously does not apply to all cases.

If in doubt I would just use the appropriate suffixes.

---
Tags: c++
---


# Question
Title: What is the best way to handle removing elements from an array while iterating through it in Unreal Engine Blueprint?
I'm trying to remove "Park" Area Controls from a Scene Actions array in Unreal Engine Blueprint. My current attempt doesn't work, and I'd appreciate help troubleshooting it.

Details:

* I have a Game Scene Ref object with an array of Scene Actions.
* Each Scene Action has an array of Area Controls.
* Each Area Control has an Area object with a Content Type property.
* I want to remove any Area Control where the Content Type is "Park" from the Scene Actions array.

My current blueprint does the following:

* Loops through Scene Actions.
* Loops through each Action's Area Controls.
* Checks if the Area Control's Area has a Content Type of "Park".
* If it does, directly removes the Area Control from the current array.

# Answer
I don't think you can remove elements of an array while iterating through an array. But you can create a temporary list and instead add an element to it if the element should not be removed and do not add if you wish to remove it from the array. At the end you can convert the list into an array.
> 1 votes

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


# Question
Title: How to spawn a road at the end of a current road and delete the previous (Endless Road Spawner)
I'm creating a game in unity for my school project similar to a mobile game called Traffic Racer which is essentially an endless runner. Due to my current scripts, I need to spawn the road at the end of the current road whenever my car passes through the trigger I have made (Instead of just making it look like the road is moving my car is moving forward). The problem is I have no idea how to create a script to spawn it when the current road ends and then delete the previous road.

This is what the road looks like and its made up of multiple objects:

I placed the trigger just before the end of the road (just before the player can see the end because I have fog.)

Please help, sorry if I made the question hard to read its my first time so I dont know the etiquette of asking questions here.

# Answer
In your hierarchy snippet, the objects are blue, so it appears that you're already using prefabs. Do you know about instantiating prefabs at runtime using scripts? That's the typical way to create new game objects in a scene in Unity.

One thing to be aware of when doing an endless runner: due to floating-point precision issues, if your object's transform position gets too far from the Origin (0, 0, 0), they'll begin to be drawn in distorted ways. The typical way to handle this for an endless runner is to have your runner not move forward at all; instead the environment moves backwards to create the illusion that the runner (or car in this case) is moving forwards. So instantiate your road segment at a set point, start moving it backwards until it's off-screen, then Destroy it.
> 1 votes

# Answer
what i would do is move the road forwards the length between the middle of the lines and the player would not notice
> -1 votes

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


# Question
Title: How to achieve camera zoom-In effect and locking view during NPC Interaction in Unity
I am currently working on an interactive game in Unity 3D where, upon pressing the "E" key, the player character interacts with an NPC. During this interaction, I aim to implement a camera zoom-in effect, focusing on the NPC, and restrict the player's ability to move the view until the NPC finishes talking.

The primary issues are:

* Ensuring the camera consistently faces the NPC, irrespective of the player's initial orientation (The player can interact with the NPC while he is facing away from the NPC, side etc. He just has to be near the NPC).
* Preventing the player from moving the view during the NPC's dialogue.

# Answer
There are many ways to skin a cat. But my go-to solution for having a game that can be in different modes at the same time, like a "walk around" mode and a "talk to NPC" mode, is by creating a finite state machine that is simply implemented as a bunch of game objects, with each one representing a state and only one of them being active at the same time. Anything that is specific to only one state - input controller, game systems, UI elements etc. - are on that state's GameObject or its children. So a state transition can be done by simply deactivating the current game object and activating the new one. If you need any code to run when transitioning into or out of a state, put that code into the OnEnable and OnDisable event methods of scripts on those state objects.

---

Regarding the camera movement: I solved this problem in my last game using Cinemachine.

This optional package for Unity is a powerful camera controller that is particularly good at making fluent transitions from one camera perspective to another.

1. If your project isn't using Cinemachine already, convert it so it does. Depending on what you already do in your project camera-wise that might require some small or large changes, so instead of going into greater detail here I would like to refer you to the available documentation and 3rd party tutorials which are plenty on the Internet.
2. Create separate Cinemachine virtual camera objects. One "play mode camera" that shows the perspective your game is usually played from, and one "character closeup camera" for each NPC which you attach as a child to the NPC game object in a way that it always faces the face. Alternatively, you can also have only one single "character closeup camera" and control which NPC it shows using the "Position Control" and "Rotation Control" settings, and change which object it tracks via script at runtime (which fits particularly well into the "game states as GameObjects" pattern I mentioned earlier).
3. When the game switches from "play mode" to "npc mode", deactivate the "play mode camera" and activate the "character closeup camera" with gameObject.SetActive. Or alternatively keep both active and control which one is active by canging their relative CinemaVirtualCamera.Priority property. To get back to play mode, do the same thing in reverse.
4. You will now see that there is a nice, fluent transition between game view and NPC view, If you want to tweak this transition further, like make it faster or slower or change its easing, you can do so in the CinemachineBrain component.
> 2 votes

---
Tags: unity, 3d, camera
---


# Question
Title: In Unity, how do I make text/annotations appear when I mouse over GameObjects in playmode?
How do I make text appear when I mouse over GameObjects in-game? What is the Unity jargon for this? I'm assuming it's 'annotations'.

# Answer
> 1 votes
There's no Unity-specific jargon for this, because what you're describing is not the engine's job. That's part of your game, which means it's on you to implement this.

A rough outline of how this would work:

* You'd make a data container script representing a "Hoverable" object.

+ You'd place an instance of this component on each object that you want to be able to get an annotation tooltip for, and configure its properties with the message/images or other data that you want to display.
    + You'd also ensure each such object has a collider to represent the shape and extents of its hoverable zone.
* You'd make an annotation UI object that has the text fields or other visual interface you want for displaying the information about the hovered object.
* You'd make a Selection / Hover Manager script responsible for keeping track of what the player is doing with their mouse. It would have a member variable to store the currently-hovered Hoverable component.

+ Each frame in Update, this script would convert the mouse position to a ray to fire into the scene. For each hit, you'd check to see if the hit collider has a Hoverable component attached. Then you have a few possibilities:

    - You find a Hoverable component, and it's the same as the currently-hovered Hoverable component. Do nothing and keep showing the current message.
        - You find no Hoverable component, and you didn't have a currently-hovered Hoverable component. Do nothing and keep showing no message.
        - You find no Hoverable component, and you previously had a currently-hovered Hoverable component. Now it's time to un-hover that component, hiding your annotation UI message and any hover highlight state.

        You might want to give a small tolerance of time or distance before un-hovering, to make the selection a bit more forgiving and reduce flickering if the player holds their mouse right near the edge.
        - You find a Hoverable component different from your currently-hovered Hoverable component. Now it's time to show your annotation, populating it with the message/info from the Hoverable component you found and setting it as your currently-hovered Hoverable.

The selection / hover manager could manipulate the UI object(s) to display the message directly, or just publish events on hover state changes that other objects subscribe to, taking responsibility to update their own states when signaled.

# Answer
> 0 votes
At least in 2021 LTS, I now see this

---
Tags: unity, gui, mouse, ui-design
---


# Question
Title: Bounding Box/Rectangle collision glitches
I've been working on this golf game for a couple of weeks and have been trying to create a reliable collision system for whenever a golf ball (mini golf) hits a block. I'm using regular rectangular box collision to help me with, but I have constantly been running into glitching issues, eg, the golf ball can clip through blocks. I've tried many methods to solve this but none of them work well.

The way I handle moving the ball is quite simple, is that the player clicks on the ball, drags and releases, which provides an initial velocity and angle, I then get x & y components and decrease or increase the position of the golf ball, I also have variables which can make the components negative. Code for this is beneath.

```
    def shooting(self):

    self.x_vel = self.initial_vel * (math.cos(math.radians(self.angle)))
    self.y_vel = self.initial_vel * (math.sin(math.radians(self.angle)))
    if self.x_inverse:
        self.x_vel *= -1
    if self.y_inverse:
        self.y_vel *= -1
    self.rect.centerx -= self.x_vel*self.dt
    self.rect.centery -= self.y_vel*self.dt
    self.initial_vel -=  self.resistance * self.dt
    if self.initial_vel <= 10:
        self.shoot = False

```

My method for calculating collisions with a block is just regular bounding box/rectangular box collision, code is beneath.

```
def bounced(self, golf_ball):

    if golf_ball.rect.colliderect(self.rect):
        if abs(self.rect.left - golf_ball.rect.right) <= 5:

            if golf_ball.rect.right > self.rect.left:
                golf_ball.rect.right = self.rect.left
                golf_ball.rect.right -= 1
            if golf_ball.x_inverse:
                golf_ball.x_inverse = False
            else:
                golf_ball.x_inverse = True  # Left

        if abs(self.rect.right - golf_ball.rect.left) <= 5:

            if golf_ball.rect.left < self.rect.right:
                golf_ball.rect.left = self.rect.right
                golf_ball.rect.left += 1

            if golf_ball.x_inverse:
                golf_ball.x_inverse = False
            else:
                golf_ball.x_inverse = True

        if abs(self.rect.bottom - golf_ball.rect.top) <= 5:  # Bottom

            if golf_ball.rect.top < self.rect.bottom:
                golf_ball.rect.top = self.rect.bottom
                golf_ball.rect.top += 1
            if golf_ball.y_inverse:
                golf_ball.y_inverse = False
            else:
                golf_ball.y_inverse = True

        if abs(self.rect.top - golf_ball.rect.bottom) <= 5:
            if golf_ball.rect.bottom > self.rect.top:
                golf_ball.rect.bottom = self.rect.top
                golf_ball.rect.bottom -= 1

            if golf_ball.y_inverse:
                golf_ball.y_inverse = False
            else:
                golf_ball.y_inverse = True`

```

My issue arises when the ball is launched at high speeds near the block, the golf ball can glitch through the block, which is obviously undesirable.

Below is my code and image for golf ball and box/block, the specific parts of code worth looking at is the shooting method and bounce\_detection in the golf ball class, and the bounced method in the block class, the only reason I added all other code, is so that you can test out the code, and attempt to solve the issue.

```
import pygame
import math

pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
mouse_pos = pygame.mouse.get_pos()
dt = clock.tick(70) / 1000

class Golf_Ball:
 def __init__(self, x_pos, y_pos, mass, w, h, mouse_pos, screen, dt):
     self.screen = screen
     self.resisting = False

     # self.dt = dt
     self.mass = mass
     self.w = w
     self.h = h
     self.visible = True
     self.initial_vel = 0
     self.x_vel, self.y_vel = 0, 0
     self.resultant = 0
     self.mouse_pos = mouse_pos
     self.fired = True
     self.hit_time = 0
     self.held_down = False
     self.line = False
     self.fired_resultant = 0
     self.x_pos = x_pos
     self.y_pos = y_pos
     self.angle = 0
     self.shoot = False
     self.resistance = 100
     self.velocity_constant = 0.3
     self.spin_angel = 0
     self.image = pygame.image.load('Assets/golf.png').convert_alpha()
     self.image_copy = pygame.transform.rotate(self.image, 0)
     self.rect = self.image.get_rect(center=(self.x_pos, self.y_pos))
     self.x_inverse, self.y_inverse = False, False

 def mouse_click_manager(self):
     if pygame.mouse.get_pressed()[0] == True and self.shoot == False:

         if self.rect.collidepoint(self.mouse_pos):

             if self.line == False and self.held_down == False:
                 self.held_down = True
                 self.line = True
         if self.line and self.held_down == False:
             self.held_down = True
             self.line = False

             self.fired_resultant = self.resultant * self.velocity_constant
             self.initial_vel = int(round(((self.fired_resultant / self.mass) * 1), 0))
             print("Hit", self.initial_vel)
             self.shoot = True
             self.x_inverse, self.y_inverse = False, False

     elif not pygame.mouse.get_pressed()[0]:
         self.held_down = False

 def line_manager(self):
     if self.line:

         if abs(self.rect.centerx - self.mouse_pos[0]) != 0:
             self.angle = math.degrees(
                 math.atan(abs(self.rect.centery - self.mouse_pos[1]) / abs(self.rect.centerx - self.mouse_pos[0])))
             if self.mouse_pos[1] < self.rect.centery:
                 self.angle = self.angle * -1
             if self.mouse_pos[0] < self.rect.centerx:
                 self.angle = abs(self.angle - 90) + 90
         elif abs(self.rect.centerx - self.mouse_pos[0]) == 0:
             if self.mouse_pos[1] > self.rect.centery:
                 self.angle = 90
             else:
                 self.angle = -90

         self.resultant = math.sqrt(
             abs(self.rect.centerx - self.mouse_pos[0]) ** 2 + abs(self.rect.centery - self.mouse_pos[1]) ** 2)

         pygame.draw.line(self.screen, "Black", (self.rect.centerx, self.rect.centery), self.mouse_pos, 3)

 def shooting(self):

     self.x_vel = self.initial_vel * (math.cos(math.radians(self.angle)))
     self.y_vel = self.initial_vel * (math.sin(math.radians(self.angle)))
     if self.x_inverse:
         self.x_vel *= -1
     if self.y_inverse:
         self.y_vel *= -1
     self.rect.centerx -= self.x_vel * self.dt
     self.rect.centery -= self.y_vel * self.dt
     self.initial_vel -= self.resistance * self.dt
     if self.initial_vel <= 10:
         self.shoot = False

 def bounce_detection(self):
     if self.rect.left <= 0:  # Left
         if self.rect.left < 0:
             self.rect.left = 1

         if self.x_inverse:
             self.x_inverse = False
         else:
             self.x_inverse = True

     if self.rect.right >= 640:  # Right
         if self.rect.right > 640:
             self.rect.right = 639
         if self.x_inverse:
             self.x_inverse = False
         else:
             self.x_inverse = True

     if self.rect.top <= 0:  # Top
         if self.rect.top < 0:
             self.rect.top = 1
         if self.y_inverse:
             self.y_inverse = False
         else:
             self.y_inverse = True

     if self.rect.bottom >= 480:  # Bottom
         if self.rect.bottom > 480:
             self.rect.bottom = 479
         if self.y_inverse:
             self.y_inverse = False
         else:
             self.y_inverse = True

 def update(self, mouse_pos, dt):
     self.mouse_pos = mouse_pos
     self.dt = dt
     if self.visible:
         if self.shoot:
             self.shooting()
             self.bounce_detection()
             self.spin_angel += self.initial_vel * 10 * self.dt
             self.image_copy = pygame.transform.rotate(self.image, self.spin_angel)

         else:
             self.mouse_click_manager()
             self.line_manager()
         self.resistance = 300
         self.screen.blit(self.image_copy, (self.rect.centerx - int(self.image_copy.get_width() / 2),
                                            self.rect.centery - int(self.image_copy.get_height() / 2)))
         pygame.draw.rect(self.screen, 'White', self.rect, 1)

class Block:

 def __init__(self, x_pos, y_pos, width, height, screen, disabled, dt):
     self.x_pos = x_pos
     self.y_pos = y_pos
     self.screen = screen
     self.disabled = disabled
     self.width = width
     self.height = height
     self.image = pygame.transform.smoothscale(pygame.image.load('Assets\Wooden_Block.png'),
                                               (self.width, self.height))
     self.rect = self.image.get_rect(topleft=(self.x_pos, self.y_pos))
     self.mask = pygame.mask.from_surface(self.image)
     self.dt = dt

     self.clock = 0
     self.counter = 0
     self.dummy_rect = pygame.Rect((self.x_pos - 5, self.y_pos - 5), (self.rect.width + 10, self.rect.height + 10))
     self.direction = True
     self.in_block = False

 def bounced(self, golf_ball):

     if golf_ball.rect.colliderect(self.rect):
         if abs(self.rect.left - golf_ball.rect.right) <= 5:

             if golf_ball.rect.right > self.rect.left:
                 golf_ball.rect.right = self.rect.left
                 golf_ball.rect.right -= 1
             if golf_ball.x_inverse:
                 golf_ball.x_inverse = False
             else:
                 golf_ball.x_inverse = True  # Left

         if abs(self.rect.right - golf_ball.rect.left) <= 5:

             if golf_ball.rect.left < self.rect.right:
                 golf_ball.rect.left = self.rect.right
                 golf_ball.rect.left += 1

             if golf_ball.x_inverse:
                 golf_ball.x_inverse = False
             else:
                 golf_ball.x_inverse = True

         if abs(self.rect.bottom - golf_ball.rect.top) <= 5:  # Bottom

             if golf_ball.rect.top < self.rect.bottom:
                 golf_ball.rect.top = self.rect.bottom
                 golf_ball.rect.top += 1
             if golf_ball.y_inverse:
                 golf_ball.y_inverse = False
             else:
                 golf_ball.y_inverse = True

         if abs(self.rect.top - golf_ball.rect.bottom) <= 5:
             if golf_ball.rect.bottom > self.rect.top:
                 golf_ball.rect.bottom = self.rect.top
                 golf_ball.rect.bottom -= 1

             if golf_ball.y_inverse:
                 golf_ball.y_inverse = False
             else:
                 golf_ball.y_inverse = True

 def update(self, golf_ball):
     self.bounced(golf_ball)

     self.screen.blit(self.image, self.rect)
     pygame.draw.rect(self.screen, 'Black', self.rect, 1)

golf_ball = Golf_Ball(200, 200, 0.04593, 20, 20, mouse_pos, screen, dt)
block_1 = Block(100, 300, 50, 20, screen, False, dt)

block = pygame.transform.rotate(
 pygame.transform.smoothscale(pygame.image.load('Assets\Wooden_Block.png').convert_alpha(), (100, 50)), 45)
block_rect = block.get_rect(topleft=(300, 200))

running = True
while running:
 for event in pygame.event.get():
     if event.type == pygame.QUIT:
         running = False
     elif event.type == pygame.KEYDOWN:

         key = event.key
         if event.key == pygame.K_ESCAPE:
             running = False

 mouse_pos = pygame.mouse.get_pos()
 screen.fill('Green')
 golf_ball.update(mouse_pos, dt)
 block_1.update(golf_ball)

 # screen.blit(block, block_rect)
 clock.tick(70)
 dt = clock.tick(70) / 1000
 pygame.display.flip()

pygame.quit()

```

# Answer
swept sphere(or circle) collision. Simply put, instead of checking for two overlapping shapes you check for intersections between a line and the object. The ball starts at A and after movement vector is applied it should be at B. AB is your line segment to check against the boxes. Let's say your box is defined as DEFG, representing the 4 points cockwise. (box can be rotated as well, it does not matter) Check for the intersection of AB with DE, EF, FG, and GD. There's a ton of info out there on line-line intersection tests, I don't recall the equations off the top of my head exactly.

From there you can determine the exact point of intersection and move the golfball accordingly. For instance, if the ball moves 10 units but hits a wall after 7, then the intersection point can be calculated with linear interpolation:

I = A + (B-A) * 0.7

The 0.7 will come from the intersections tests. As the line tests work on infinite lines, the resulting values should fall between 0 and 1 to ensure its within the length of the segments. So that's a boundary check to consider.

From the intersection point you want to subtract the ball's radius for the final position otherwise it'll appear to be half inside the box. Similarly, the movement vector AB should include the ball's radius as well. So technically the line is A to B + r. Otherwise, the golfball could land right next to the square without intersecting it but appear to be partially inside.
> 0 votes

---
Tags: collision-detection, pygame, collision-resolution, aabb, bounding-boxes
---


# Question
Title: I can't find what I'm doing wrong when rendering a point light that is clipped by the floor
I have a top down camera on my game, and I'm rendering a point light on my opengl fragment shader.

When the point light is far away from the floor it looks like I would expect it should look, like a perfect sphere of light.

But when the light is close to the floor is getting sliced not equally from the bottom but diagonally.

Is there something wrong with my implementation of the pointlight?

vertex

```
layout(location = 0) in vec2 v_position;
layout(location = 1) in vec3 v_light_position;

layout(location = 0) out vec2 position;
layout(location = 1) out vec2 light_position;

layout(binding = 0) uniform ubo {
    mat4 camera_view;
    vec3 light_color;
    float light_fade;
    float light_scatter;
    float light_intensity;
}

void main() {
    position = v_position;
    light_position = v_light_position;

    gl_Position = camera_view * vec4(position, 0., 1.);
}

```

fragment

```
layout(location = 0) out vec4 color;

void main() {
    float light_distance = distance(position, light_position.xy);

    float attenuation = 1 / (1. + light_fade * light_distance + light_scatter * (light_distance * light_distance));

    vec3 normal = texture(texture_1, uv).rgb;

    vec3 light_direction = normalize(
        vec3(light_position.x - position.x, position.y - light_position.y, light_position.z)
    );

    float ndotl = clamp(dot(normal, light_direction), 0., 1.);

    vec3 diffuse = vec3(light_intensity) * ndotl;

    color.rgb = light_color.rgb * diffuse * attenuation;
    color.a = 1.;
}

```

Getting the light clipped with the floor has sense, but the plane is perfectly flat with no slope, so it's awkward this is happening.

# Answer
Okay, the problem was not in the code but in how I was creating my normals in Blender.

I was using a `vec3(.5, .5, 1.)` for a flat plane when it should have been `vec3(0., 0., 1.)`
> 2 votes

---
Tags: opengl, glsl, lighting
---


# Question
Title: 2D rotating on z axis according to Time.deltaTime not working properly
This is in 2D by the way.

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

public class Whirl : MonoBehaviour
{
    float turnSpeed = -0.5f;

    void Update()
    {
        transform.rotation = Quaternion.Euler(0f, 0f, turnSpeed * Time.fixedDeltaTime);
    }
}

```

The object where this script is attached to is not working properly. I never experienced this bug, but the z rotation is staying in a 0.002 range, like it's trying to rotate, but it can't. Any idea to fix this bug?

And yes, fixedDeltaTime is not the problem, because I already tried regular deltaTime.

# Answer
> 0 votes
Ok, so for some reason you can't use any variation of `Time.deltaTime`, and instead have to use `Time.time`.

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


# Question
Title: biome blending using multiple biome (altitude, humidity) points
I have a noise function for altitude: float getAltitude(x, z) and noise function for humidity: float getHumidity(x, z) and at each cell of my terrain I calculate a (altitude, humidity) point, and then find which on of my predefined biome (altitude, humidity) points it's closest to - that gives me the biome the point is in. So then I use my particular biome's elevation noise function to set the elevation of the terrain at that point. That works great. I am having problems blending biomes. I tried setting up a BIOME\_BLEND\_RADIUS value and if the difference in distances to 2 (or more) biome points is within that BIOME\_BLEND\_RADIUS I interpolate them. My issue is that interpolation - I can't get it to work. I would appreciate some help with this, thanks.

edit: I tried interpolating two biomes at a time. I found distance1 = distance from input point to closest biome point in (altitude, humidity) space and distance2 which is the equivalent fro second closest biome. Then if (distance2 - distance1 \< BLEND\_RADIUS) I did influence1 = (distance2 - distance1) / BLEND\_RADIUS / 2 + 0.5f; and influence2 = 1.0f - influence1; and otherwise influence1 = 1.0f and influecne2 = 0.0f; This approach worked for blending two biomes but I didn't know how to expand it to more than that. Then I switched over to using my BLEND\_RADIUS to just finding n closest biome points and then finding distances to each, normalizing them and using those normalized distances as influences of each biome. That approach blends nicely but causes bleed-over.

# Answer
With any biome blending, your general goal is to produce a set of `{biome, weight}` pairs where all the weights sum to one. You can then compute any blended value as a weighted sum of the individual biome values.

Your parameter space is essentially a Voronoi diagram, and you want to compute a border blending within the diagram.

One solution which produces smooth results is as follows:

* Find the distance `D` to the closest Voronoi point.
* Consider all Voronoi points within the range of `4R + D`, where `R` is your blending radius.
    + This is the maximum distance of any point that can affect the weights in the step to follow.
    + You can omit this at first, but as you add more biomes the runtime complexity of the following steps will be O(N²).
* Initialize each point's weight at 1. Iteratively refine their weights as follows:
    + Loop over every *distinct pair* of points `(A, B)` from the above query step.
    + Find the dividing line between them, and calculate a signed distance `F` of the input point `I` from the dividing line, such that it's positive towards `B` and negative towards `A`. `F = dot(I - (A.position + B.position) / 2, B.position - A.position) / length(B.position - A.position)`.
    + Divide by `R` so the radius covers the range `[-1, 1]` within the blending radius, clamp the result so it can't go past those values, rescale it to `[0, 1]`, and run it through a fade curve. `H = fade(min(max(F/R, -1), 1) * 0.5 + 0.5)` where `fade(t) = t*t*(3-2*t)`.
    + Multiply B's weight by `H`, and A's weight by `1-H`.
* Divide each weight by the total.

In essence, the algorithm is performing individual clamped-smoothstep blending between each pair of points, then multiplying all of a given point's weights together. Between points A and B in the following illustration, the input (evaluation) coordinate is on A's side, so A would get a weight closer to one and B would get a weight closer to zero, as decided by how far the input point is from the dividing line. If the dividing line were completely out of the blending range, then A's weight in this calculation would be one and B's would be zero.

Then, since you're sampling the biome space with noise, which tends to have different slopes in different value ranges, you will likely want a way to control the blending size depending on which biomes are meeting. To do this, you can assign each biome its own radius value. To put that value to use, you might choose to compute the average every time you consider a pair of biomes in the above steps. If you're feeling adventurous, you can also try to devise a formula to automatically assign each biome a radius based on its position in the blending space.

Explanation for the `4R + D` consideration range: For a point B to be close enough to A that it could have a nonzero weight when pitted against it, the dividing line has to be within the blending radius of the input coordinate. For this to be the case, B must be less than `2R + D` distance away. Specifically, that's `+R` for how far away the dividing line needs to be, then another `+R` to move B far enough to place it there. Finally, for a point C to be able to modify the weight of the furthest possible considered B, add another `2R` to get `4R + D`. Note that once a point receives a zero weight as part of any pair calculation, its final weight will necessarily be zero.
> 0 votes

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


title: Calculate path segments size

text:
# Question
Title: Calculate path segments size
I have a problem more closely described on a picture below. The idea is that I have my agent in point A and I want to get to the point B. The problem is, that agents rotation towards point B is *alpha* degrees. I want to get to the point B in *n* steps (path segments) such that at each step, I rotate towards point B by uniform degrees. That should be (if I am not mistaken) \\$2\times\frac{alpha}{n}\\$ degrees at each step.

Update: as correctly pointed out, it should be \\$2\times\frac{alpha}{n - 1}\\$ degrees at each step.

I want to know how big of a steps (path segments) I need to make so they all have same size and will get me to the point B.

# Answer
> 0 votes
A simple way to solve this is just to assume all segments have length 1 for a first pass, so they contribute a distance parallel to AB equal to the cosine of their angle (using our friend the unit circle). We can then add up this contribution across the `n` segments to get the total distance along AB when the arc curls back to cross the line. It might overshoot or undershoot B, but that's OK. We can take the distance AB and divide it by the total distance we tabulated to get a scaling factor that will make it match exactly. That quotient is then the segment size to use.

```
float GetSegmentSize(Vector2 A, Vector2 B, float startAngle, int segmentCount) {

    // Fencepost: an arc with n segments has n-1 turning joints.
    float angleIncrement = 2 * startAngle / (segmentCount - 1);

    float totalLength = 0;
    for (int i = 0; i < segmentCount; i++) {
        float segmentAngle = startAngle - i * angleIncrement;
        totalLength += Mathf.Cos(segmentAngle);
    }

    return Vector2.Distance(A, B) / totalLength;
}

```

Since we're adding up several small values into a larger total, this is subject to some loss of precision in floating point math, but you can upgrade to double precision if needed for the intermediate steps, and that should be enough precision for most game purposes.

You can also use symmetry to halve the calculation, since the segments before and after the halfway point add the same distance contribution - we don't need to calculate their cosines twice:

```
// For odd n, there's a segment perfectly parallel to AB in the middle.
float totalLength = (n & 1) == 0 ? 0 : 1;
int halfway = n >> 1;
for (int i = 0; i < halfway; i++) {
    float segmentAngle = startAngle - i * angleIncrement;
    totalLength += 2 * Mathf.Cos(segmentAngle);
}

```

# Answer
> 0 votes
If you consider a circle that runs through both **A** and **B**, constructed so that the circle tangent at **A** is equal to the initial path-segment (or the direction of the **A** agent):

Then you can solve for the radius **r** as you have a triangle where you know one angle, *90 - alpha*, and one side *(distance a to b) / 2*.

When **r** is calculated, you can calculate where point **c** is located. With **c** and **a** and **b** you know how many degrees there is between the vectors *c to a* and *c to b*, divide that angle with **n** and you get the angle step you need to move every step to get from **a** to **b**.

Take the vector from **c** to **a**, rotate it by the angle step, the distance between that endpoint and **a** is the segment length you are looking for.

In the above example I am changing **n**, and the coordinate of **b** and the direction of the first segment.

I think there is some special case where **c** is on the *other size* of vector between **a** and **b** but that should be trivial to cater for.

I got pointed in the right direction by the people over at math.stackexchange (https://math.stackexchange.com/questions/4840292/given-two-points-and-a-an-angle-find-the-radius-of-the-circle-that-intersects-b)

**Update:**

As correctly pointed out by @DMGregory, the above method plots *secants* evenly distributed along the *arc* of the circle that runs through points **a** and **b** such that the direction vector (of angle **alpha**) is the *tangent* to the circle, this means that the angle of the first segment is not **alpha**, but some smaller angle.

The first segment of the path needs to lie **on** the direction vector to correctly answer the question. I think this can be achieved by instead of just evenly distribute the *arc* **n** times extend the line of the first **pie-slice** (in red) of the until it intersects the direction vector ad point **p**, and then construct the subsequent segments by simply rotating that segment by **2 * alpha / (n - 1)**.

This way the path will always start with a segment that lies on the direction vector from **a**, which is what I call the line at angle **alpha** from the line **a** to **b**.

---
Tags: mathematics, rotation, vector, geometry, linear-algebra
---


# Question
Title: How to make a coroutine private in Unity?
I am trying to make a coroutine private in Unity. I have tried declaring it as a private method, but it still seems to be accessible from other classes.

Here is an example of the code I am using:

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

public class EnemyPatrol : MonoBehaviour
{
    public float speed = 1f;
    public float minX;
    public float maxX;
    public float waitingTime = 2f;
    private static IEnumerator PatrolToTarget;
    private GameObject _target;
    // Start is called before the first frame update
    void Start()
    {
       UpdateTarget();
       StartCoroutine(PatrolToTarget());
    }

    // Update is called once per frame
    void Update()
    {

    }

    private void UpdateTarget()
    {
        if (_target == null)  {
            _target = new GameObject("Target");
            _target.transform.position = new Vector2(minX, transform.position.y);
            transform.localScale = new Vector3(-1, 1, 1);
            return;
        }

        if (_target.transform.position.x == minX) {
            _target.transform.position = new Vector2(maxX, transform.position.y);
            transform.localScale = new Vector3(1, 1, 1);

        }

        else if (_target.transform.position.x == maxX) {
            _target.transform.position = new Vector2(minX, transform.position.y);
            transform.localScale = new Vector3(-1, 1, 1);
            }

        private void IEnumerator PatrolToTarget() {

            while(Vector2.Distance(transform.position, @this._target.transform.position) > 0.05f)
            {
                    Vector2 direction = _target.transform.position - transform.position;
                    float xDirection = direction.x;

                    transform.Translate(direction.normalized * speed * Time.deltaTime);
                    //importante
                    yield return null;
            }

                Debug.Log("Target reached");
                transform.position = new Vector2(_target.transform.position.x, transform.position.y);

                Debug.Log("Waiting for " + waitingTime + "seconds");
                yield return new WaitForSeconds(@this.waitingTime);

                Debug.Log("Wait enough, let´s update the target and move again");
                UpdateTarget();
                StartCoroutine(PatrolToTarget());

        }
    }
}

```

# Answer
Where you put your code matters.

When you write code like this:

```
private void UpdateTarget() {
    // Update code here...
}

```

*All* the code between the opening `{` and closing `}` belongs to the `UpdateTarget` method.

So when you wedge another function inside it, like this:

```
private void UpdateTarget() {
    // Update code here...

    IEnumerator PatrolToTarget() {
        // Patrol code here...
    }
}

```

...then what you've done is define what's called a Local Function that belongs to `UpdateTarget`. Instead of adding a new member function to the class, the `PatrolToTarget` function is now visible *only* to code inside the `UpdateTarget` method. Code elsewhere in the class cannot see it.

This is obviously not what you want, because you're trying to call `PatrolToTarget()` from `Start`.

Your method signature is also invalid here:

```
private void IEnumerator PatrolToTarget()

```
* `void` and `IEnumerator` are both return types, but you're only allowed to have one.
* `private` is not a valid modifier for a local function, since *all* local functions are super-private to just the containing code block.

This last error is the one your compiler is complaining about. Because you've given it invalid code that cannot compile, it gives up, and doesn't mention the fact that `PatrolToTarget` is not visible from `Start`. Unity and your IDE will keep using the last successfully compiled version, which was probably one where this function was still public, and that's what's causing the illusion that it was somehow not possible to make it private.

So, remember, always fix all your compiler errors before trying to solve a bigger problem - they usually point you in the right direction, and one unsolved error can mask more pressing ones hiding behind it.

With that out of the way, here's how to make a coroutine private:

```
private void UpdateTarget() {
    // Update code here...
}
// Note that we've closed the } so we're outside UpdateTarget now.

private IEnumerator PatrolToTarget() {
    // Patrol code here.
}

```

There's no trick to it at all. We just write `private` in front of it like any other method. You just have to pay attention to where you're writing your code, and ensure that if you want to define a member function, you're writing it in the body of the containing class, not wedged inside another function.

Be sure to also delete `private static PatrolToTarget;` from the top of your class. This declares a variable with the same name as the function, so you'll have a collision if you leave it there. You never assign this variable anywhere, so it's just junk code that's not doing anything useful.
> 3 votes

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


# Question
Title: How do I convert a voxel model to a low-poly mesh with texture mapping that accurately mimics the coloured voxels?
I've created a model in MagicaVoxel (**A**) and I want to use it in Godot. I imported the model into Blender, but then realized that it's using a very high polygon count for such a simple model. I found that using MagicaVoxel's OBJ export yields interesting results in that voxels of the same colour share polygons (**B**), but when many different coloured voxels are next to each other, it still creates a high polygon count.

Ideally, I'd like to have a model that is the lowest polygon count possible (**C**) with an accurate texture map to mimic the voxel colours. Is there an existing tool to achieve this? I really like how MagicaVoxel works and I'm not interested in using Blender to model or manually texture the mesh, but maybe there's a plugin for Blender? I'm open to suggestions.

As a side note, it's possible that I could just use the OBJ file as is, but I wonder about performance. Mesh **B** has 216 polygons, while mesh **C** uses 140. This is just one asset in a medieval adventure game and I'd like to have a very cluttered world. ;-)

***Edit For clarification:** MagicaVoxel exports an OBJ file with accurate texture mapping, but isolates different colours of voxels to their own polygons, creating more polygons than are required. Mesh **B** is the result (I imagine this removes the need for any anisotropic filtering). Mesh **C** was also exported from MagicaVoxel, but with the colour information removed. Thus, without the desired material information. I just wanted to avoid any confusion with what MagicaVoxel can do on it's own. Maybe there's a solution within MagicaVoxel that I'm not aware of?*

---

**Update:** I believe Blender can do what I need, but it's going to require a lot more research to get it right. I was able to get a texture map to bake by diffusing colour with some success (some faces got the wrong colour, see the yellow near the bottom of the blade), but I couldn't quite figure out how to do it with vertex colour emissions to see if the result would be better. Then (as you can see in the sword handle) I need to setup up a pixel perfect UV and texture map, prior to baking. I'm kind of leaning away from doing it manually in Blender, to be honest. I may have to do this for a thousand or more models, and every time a model is edited.

I'm going to let this question sit for now in the hope that there's an easier solution. Maybe a script exists to do this? Maybe I should learn how to write my own? In the meantime, I can still proceed with the higher polygon counts in the OBJ exports from MagicaVoxel. The neat thing about the native MagicaVoxel OBJ exports is that the texture map is a simple 1px tall by 256px wide palette PNG file (every colour is a single square pixel) that all meshes can share. Everything can use the same texture file. Maybe that offsets the higher polygon count performance hit? Anyway, I'm taking a break from Blender. ;-)

# Answer
Although this is quite an old post - I went ahead and solved this issue.

My program Ultimate Voxel Optimizer takes in magicavoxel files, and exports them in numerous formats to fit your workflow, including textures, materials, or even vertex colours. You'll find that if you use the optimized method, you can get even more polygon reduction than you would find in object C in your post.

Hope this helps!
> 2 votes

# Answer
There exists an addon on the asset store that can import .vox files directly, no exporting needed: https://godotengine.org/asset-library/asset/162

Regarding the high poly count, I'd say that you can always optimize later if it becomes an issue.
> 1 votes

# Answer
I found out this post pretty late but I've struggled with the very same problem, and I managed to make a Blender plugin in the end to solve the same.

Here's the Free script, Hope you like it: Vox-Cleaner-V2
> 1 votes

---
Tags: textures, blender, godot, voxels, magicavoxel
---


# Question
Title: Why do the camera and the character not move when I use my own mapping context?
I replaced the defult mannequin with my character and created a new input action and an input mapping context.

But when I change the default mapping context to mine, the camera and the character never move, and I can’t move the character using the buttons, nor can the camera move like before when I move my mouse.

Why do the camera and the character not move when I use my own mapping context?

# Answer
> 0 votes
From the way the question is asked, it occurs to me that you are assuming that defining the action will automatically make your Character pick them up. You still need to listen to the action somewhere, e.g. in the Player Controller and translate it into a movement, e.g. like so (my Action name is obviously different from yours):

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


# Question
Title: Is there a way to stop a part of the code from working?
I'm currently trying to do the death animation of my player in Unity, but since my player will be touching the ground, the death animation won't run. Is there a way to solve this?

Here is my movement code:

```
void Update()
{
    transform.position += Vector3.right * SpeedValues[(int)CurrentSpeed] * Time.deltaTime;

    if(Input.GetMouseButton(0))
    {
        if (OnGround())
        {
            rb.velocity = Vector2.zero;
            rb.AddForce(Vector2.up * 26.6581f, ForceMode2D.Impulse);
        }
    }
}
bool OnGround()
{
    return Physics2D.OverlapCircle(GroundCheckTransform.position, GroundCheckRadius, GroundMask);
}

```

Here is the death animation code:

```
private void OnCollisionEnter2D(Collision2D collision)
{
    if(collision.gameObject.CompareTag("Enemy"))

    Destroy(gameObject);
    LevelManager.instance.Respawn();
}

```

# Answer
Yes there is simple way to stop a part of code from working just put `return` before the line you want to stop working. And probably u need to change the function like this:

```
if(collision.gameObject.CompareTag("Enemy"))
{
    LevelManager.instance.Respawn();
    Destroy(gameObject);
}
//If you need also respawn on any collision hit add this line too
LevelManager.instance.Respawn();

```
> 0 votes

---
Tags: unity
---


title: Correct way to handle pickup counter?

text:
# Question
Title: Correct way to handle pickup counter?
In my game, the player picks up items. When every pickup is picked up, you can exit the level. This is how I coded it now, I don't like it and I am writing here to learn if there are better ways to do it. I am only gonna show the pickup manager code, as the pickup objects only add themselves on enable, and remove themselves on disable.

```
[DefaultExecutionOrder(-1)]
public class PickupManager : MonoBehaviour
{
    public static PickupManager Instance;

    private List<PickupableObject> objectsInstances = new List<PickupableObject>();

    private int objectsInLevel = 0;
    private int objectsRemoved = 0;

    private void OnEnable()
    {
        Instance = this;
    }

    private void OnDisable()
    {
        Instance = null;
    }

    public void Add(PickupableObject d)
    {
        if (!objectsInstances.Contains(d))
        {
            objectsInstances.Add(d);
            objectsInLevel++;
        }
    }

    public void Remove(PickupableObject d)
    {
        if (objectsInstances.Contains(d))
            objectsInstances.Remove(d);
    }

    public void ObjectPickedUp(PickupableObject d)
    {
        objectsRemoved++;
    }

    public float GetPercentage()
    {
        if (objectsInLevel > 0)
        {
            return (float)objectsRemoved / (float)objectsInLevel;
        }
        return 1;
    }
}

```

**Cons:**

1. It is a Singleton, but at the same time not, as each of the scenes has a different one. I don't like it
2. At the initialization of this script, it doesn't know how many pickups are there, until the end of the current frame

**Pros:**

1. It works, but only if I do additional checks (in the first frame the number of picked up objects is the same as the number of pickups, 0)

I thought about another way to handle it, that is: **making the manager spawn the pickups itself.**

**Cons:**

1. You can't see the pickups in the editor, unless you are running the game. Big no no as I need to place them perfectly, as each pickup has a different model.

**Pros:**

1. The script doesn't need a public static instance
2. The script knows the number of pickups at the very start and doesn't need workaround to work correctly

Is there a way to handle this better?

# Answer
You should do a bit of reading on code architecture, clean code and design patterns if you want to know how to make your code better on your own.

But to address your question, for a start, there are several things wrong with your Singleton. First of all, your Instance reference is publicly available, which means it can be changed from any other place in your program. Thankfully, property getters and setters don't have to have the same access modifiers, meaning that you can have a public getter, and a private setter.

```
private static PickupManager s_instance;
public static Pickup Manager Instance { get => s_instance; private set { s_instance = value; } }

```

Now the Instance is managed internally by your class, good. The next problem is there is nothing stopping the game from having multiple instances because when every PickupManager is enabled the Instance is set to that object. What I would do is move that functionality to the Awake method and check if an instance already exists, if it does then disable the component.

```
private void Awake()
{
    if (Instance != null)
    {
        this.enabled = false;
        return;
    }
    Instance = this;
}

```

And... now that that's out of the way, you don't need to make your manager a Signleton. Now it all comes down to this: will there be a fixed amount of pickups, or will more pickups be spawning during the level, will some be removed, etc. You should first consider what you actually want for your game.

Easiest solution is to have a fixed amount of pickups. You need an IPickup interface from which all pickups will inherit, and the interface should have a OnPickup event. The PickupManager will at it's Awake method find all GameObjects which have a component that inherits the IPickup interface, and place them in a Dictionary. For each pickup object as a key, there is a boolean pair which specifies if the pickup is picked up. The Manager should also listen to the OnPickup event for each item so that it can mark it as pickedup. One important thing about this is to not destroy the objects when they are picked up, but just not render their meshes and collision, and change the state of the script controlling the pickup.

```
using System.Collections.Generic;

public class PickupManager : MonoBehaviour
{
    private Dictionary<IPickup, bool> _pickups;

    private void Awake()
    {
         _pickups = new();
         foreach (IPickup pickup in Object.FindObjectsOfType<IPickup>())
         {
             _pickups.Add(pickup, false);
             pickup.OnPickup += (item) => { _pickups[item] = true; };
         }
    }

    public int PickedUpItems()
    {
        int ctr = 0;
        foreach (bool pickedup in _pickups.Values)
        {
            if (pickedup)
                ctr++;
        }
        return ctr;
    }
}

public interface IPickup
{
    public delegate void PickupEventHandler(IPickup item);
    public event PickupEventHandler OnPickup;
}

public class ExamplePickup : MonoBehaviour, IPickup
{
    public float SomeValue = 5f;
    public event IPickup.PickupEventHandler OnPickup;

    private void OnTriggerEnter(Collider col)
    {
        if (!col.transform.CompareTag("Player"))
            return;
        GetComponent<MeshRenderer>().enabled = false;
        GetComponent<BoxCollider>().enabled = false;
        OnPickup?.(this);
    }
}

```

Now if you want items to spawn during the game is to have a separate Spawner (factory) class which notifies the Manager of this changes. A step further would be to make all your pickups the same prefab, and have an Identifier component which specifies the look, functionality, properties, etc. of the item, and you would specify these using a custom EditorWindow. Then the items would be initialized by the Spawner class when the level is loaded, and registered to the PickupManager.
> 1 votes

---
Tags: unity
---


# Question
Title: Identifying the wall of impact during BSP traversal
I'm building a 2D BSP based physics game and am having trouble implementing what might seem like an easy feature. I'm using Gamemaker as the basis for this project.

## Basic Info and Point of Impact Finding

Identifying the point of impact using a BSP traversal algorithm is relatively simple. What I'm trying to identify is *which wall* the segment collided with. This is not only to gather the correct surface information used in collision resolution, but also to invoke that surface's method for being impacted *(play the right sound, enter a door, etc)*.

Each node stores its wall in a struct variable called `split`, which contains its two points, its normal, and any other relevant information about the wall. During construction, these walls are used to *split* the other walls and distribute them to either the front or back subtree, hence the name. Colinear walls are handled as such: If it faces our split, send it to our front. Otherwise, send it to the back.

Leaf nodes have a split of `int` -1 for empty and -2 for solid. This is checked as the base case for the traversal algorithm *(GML is dynamically typed)*.

All nodes are stored in an array with their index being used as their address in memory. A node's children are stored using the integer variables `frontChild` and `backChild`.

I will not be covering the details on how BSP traversal is typically performed. This can easily be found online and I haven't done anything out of the ordinary to my knowledge so far. Finding the point of impact works well, and I've accounted for floating point errors using an epsilon value.

```
function bspTestSegment(p1, p2, w, ind=0)
{
//Returns where (if at all) a given segment intersects with the bsp walls, along with the
//wall itself.

    var n = cWorld.bsp[? room][ind]

    //If we've hit a leaf node, return the result.
    if n.split == -1
    {
        //Empty node.
        return 0
    }
    if n.split == -2
    {
        //Solid node. Return point of impact.
        return p1
    }

    //Get our dot products.
    var d1 = p1.sub(n.split.p1).dot(n.split.normal)
    var d2 = p2.sub(n.split.p1).dot(n.split.normal)

    //If we're only on one side of the splitting line, just send us to that subtree.
    if d1 >= -EPSILON and d2 >= -EPSILON
    {
        return bspTestSegment(p1, p2, w, n.frontChild)
    }
    if d1 < -EPSILON and d2 < -EPSILON
    {
        return bspTestSegment(p1, p2, w, n.backChild)
    }

    //We know we're straddling the line, so split our wall.
    var seg = bspSplitWallsTest(p1, p2, n.split.p1, n.split.p2)

    //Find which direction relative to the wall we're headed. If we're headed toward the
    //wall, send us to its front child first.
    if d1 >= -EPSILON
    {
        //Claim the wall of impact.
        w[P] = n.split

        //Test the front child.
        var hit = bspTestSegment(seg[0], seg[1], w, n.frontChild)

        //If we hit something, return where.
        if hit != 0
        {
            return hit
        }

        //Otherwise, test the backchild.
        return bspTestSegment(seg[1], seg[2], w, n.backChild)
    }
    //Otherwise send us to its backchild first.
    else
    {
        var hit = bspTestSegment(seg[0], seg[1], w, n.backChild)

        //If we hit something, return where.
        if hit != 0
        {
            return hit
        }

        //Otherwise, test the frontchild.
        return bspTestSegment(seg[1], seg[2], w, n.frontChild)
    }
}

```

Collision resolution also works well, granted we have the correct wall of impact.

## Wall of Impact Finding

The issue is in identifying which wall was the first along the segment to be impacted. The simplest possible approach is to pass a pointer `w` *(GML doesn't have proper pointers so I use an array)* to the traversal function, and whenever a split is straddled while the segment is heading toward it, that node overrides the pointer with its split *(wall)*. Therefore, the lowest node on the tree that the segment ran head-first into will *claim* the impact as its own, and assign its split *(wall)* to the pointer. This works for most cases.

The issue is when a node claims the wall of impact as its own, and is then *overridden* by a node in its rear sub-tree. The segment will be split by the correct node, but a node behind it will end up satisfying both conditions *(segment is heading towards and straddling)* and override the pointer incorrectly.

## Attempted Solutions

If a segment intersects the BSP, the point of impact is guaranteed to be the starting point of the segment that reaches a solid node. A solid node is only reached when a segment is straddling a wall. When a segment is straddling a wall, the segment is split, and the sub-segment between its midpoint and endpoint is the one sent to the solid leaf *(granted it's headed toward the node that split it)*. Therefore, we can guarantee that the point of impact is the midpoint of some node's split segment. Logically, this midpoint is going to belong to the correct wall of impact.

If a node splits the segment (again, while the segment is headed toward it), we consider it a potential candidate for the wall of impact. Once we've reached a solid leaf, we can then walk back up the tree and compare this point of impact with every candidate's midpoint. Only the one that matches (or is within epsilon distance of) the point of impact will claim the wall of impact.

This would be inside the "heading toward the wall" block:

```
//Otherwise, test the backchild.
hit = bspTestSegment(seg[1], seg[2], w, n.backChild)

//Override the wall of impact if we're the one that split the colliding segment.
if hit != 0 and hit.sub(seg[1]).lenSqr() < 1
{
    w[P] = n.split
}

return hit

```

*(note: I have my own vector constructor. hit, seg\[0-2\], p1, and p2 are all 2D vectors. the method lenSqr() returns the vector's squared magnitude for distance comparisons.)*

This works, but then creates a new issue. If a rear descendant is colinear with a node, the descendant's rightful claim to the wall will be overridden by its ancestor node on the walk back up.

Another attempt had me building the tree such that any colinear wall was passed down to the front sub-tree. Then, during traversal, in the case where our segment lies entirely in front of the split, I allowed it to claim the wall if the endpoint of the segment was colinear with it. This fails as not only is it possible for a front descendant to be colinear and entirely elsewhere, it's also claimed while walking *down* the tree, meaning the previously implemented walk *back up* overrides it.

I can't find research as to how this specific part of the traversal is handled and yet I know it is because many BSP based engines handle this just fine. If anyone can help or point me to a good resource I'd be more than a little grateful. Thank you so much for reading...

# Answer
> 1 votes
I figured it out. It was similar to my first attempted solution, but slightly more robust.

```
//Otherwise, test the backchild.
hit = bspTestSegment(seg[1], seg[2], n.backChild)

//Override the wall of impact if the point of impact is colinear and within the
//bounds of our wall.
if hit != 0
{
    if hit[0].sub(n.split.p1).dot(n.split.vunit) >= 0 and
    hit[0].sub(n.split.p2).dot(n.split.vunit) <= 0 and
    hit[0].sub(n.split.p1).dot(n.split.normal) >= 0
    {
        hit[1] = n.split
    }
}

return hit

```

The above section of code is in the same place as the first failed solution. While going back up the tree, instead of overriding the wall when our midpoint of the split segment matches the point of impact *(which failed because that wasn't necessarily touching the wall)*, we simply ensure that the point of impact runs along the wall itself, and is between our wall's start `split.p1` and end `split.p2` points.

To do this, we simply take the line of the wall itself *(here it's called vunit)* and get its dot product with the point of impact relative to the start and endpoints of the wall *(conditions 1 and 2)*. Then all that's left is to make sure it's colinear and we're done! *(condition 3)*.

The reason this works is that we're basically ensuring that the point of impact lies along the line *segment* rather than just the line. In fact, the first wall to claim the impact will never be overridden, so it's possible to make this even more efficient by not running these tests after one does.

Since we're only overriding the wall while walking back up the tree, we don't even need to pass a pointer for the wall to each recursive call. Here I simply returned the point of impact in `hit[0]` and the wall of impact in `hit[1]`. Just be sure that, at the solid base case, you return `[p1, <empty_wall_struct>]` instead of just `p1` to ensure that the game doesn't crash when you have a point of impact but no wall (when the object is outside of the map, for example).

: y

---
Tags: collision-detection, game-maker, physics-engine, tree, binary-space-partitioning
---