# Question
Title: Using Game Engine (or parts of it) In Commercial Application?
This is a difficult question, as it is not related to game development directly: we are currently evaluating, if an existing game implementation (game engine or part of it) may fulfill the needs for a new concept we like to integrate in our existing commercial application.

The idea: Implementation of a comprehensive resource management system.

A resource should have the following attributes (current draft state):

1. State
    * Functional state (technical)
    * Organisational state
2. Location/Assignment
    * Location of resource
    * Parent resource to which this resource is attached to
3. Ability to move on its own
4. Type
5. Property List \[0-n\]
    * Compatibility constraints
    * Capacity constraints
    * important: each property in this list is organised in a hierarchical tree of its category and may only be assigned to resource while obeying the compatibility constraints of other existing properties, and the type, of course
6. Dependencies \[0-n\]
    * to other resources
    * to other contexts ??
7. Services/Skills \[1-n\]
    * List of requests this resource is able to fulfill (to a specific degree)
8. Charge State \[0-n\]
    * depending on type, optional charge/load state

My researches brought up three different types of things:

1. Receipts of how to build a resource management system/inventory
2. Descriptions of existing game implementations (from user perspective)
3. Game engines

These three things aren't exactly what we are trying to find. The closest match are game engines. But I doubt, that the integration of a whole game engine may be the best approach as (1) we have an existing application and (2) we don't need many of the game specific functionality. Using an external library that brings resource management would be a more precise approach.

On the other hand, what we do have is a 2d map view on which the resources (that can move on their own) are being displayed. On this map, the resources are being assigned to an event that opens one to many requests that need to be fulfilled. An important aspect is the time, resources need to move to the location of the event. So there indeed are some common mechanics to a (e. g. strategy) game.

Any ideas for a starting point from where we can proceed doing further research?

# Answer
The resource (or "unit") properties and behaviours you describe are **not things usually provided by game engines**.

A game engine provides the core foundation to build a game on top of, things like...

* importing texture, 3D model, sound assets and converting them to suitable real-time formats
* providing an editor interface where creators can configure and arrange game content
* gathering keyboard/mouse/controller input
* tracking time and ticking update loops or event functions in user scripts to move the game state forward
* providing a render loop with an API that makes it easy to draw 3D meshes or 2D sprites with a variety of shader materials

...and more, often all in a cross-platform.way.

You'll notice **no game mechanics** appear in that list, just the raw parts that a game developer would craft game mechanics out of (ways to react to input, ways to play a sound or spawn particles, etc...)

The game state and game mechanics like unit/resource management that you describe would be written in user code that then interfaces with the engine for things like spatial queries in the scene, path-finding, drawing, etc.

If you have a 2D map in your application, then it sounds like you already have modules providing most of that functionality, and you don't need a game engine to provide it.

The other thing you might be leading you toward game engines is that many come with libraries of sample user code, asset stores with pre-made scripts for download/purchase, or tutorials showing how to achieve common game features using that engine. But you don't need to integrate the engine itself into your app to benefit from these. It's unlikely you'll find a pre-made RTS unit or resource management game system that's configurable enough to do exactly what you need anyway, so you were always going to have to write some custom code. What you can do is study some of these pre-made assets and learn the kinds of techniques game developers use to implement these features, and what kind of engine APIs they're built on. Then you can use that knowledge to provide game-like facilities in your app's internal API, and build your custom resource mechanics against that.

To get you started in that direction, Game Programming Patterns is a great guide to common software development patterns through a game lens, which can help you get into the headspace of a game developer, and it's free to read online. You may also want to search this StackExchange for past answers talking about "composition over inheritance", component-based approaches, and entity-component-system architecture, which form a related family of ideas that's proven very powerful and flexible for building game content. These are better explained elsewhere, so I won't try to rehash it all here.
> 1 votes

---
Tags: game-mechanics, resource-management, inventory
---


# Question
Title: How to flip the scale of just a parent GameObject and not its children
I'm creating a 2D platformer game and I have a Player gameObject in the hierarchy that has its sprite. When the player is facing one way and they press the opposite arrow, I'd like to flip the sprite but *not* the camera and groundCheck children gameObjects underneath.

The code below doesn't work and it gives me a `NullReferenceException: Object reference not set to an instance of an object` error.

```
        if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f) {
            isFacingRight = !isFacingRight;
            Vector3 localScale = transform.localScale;
            localScale.x *= -1f;
            transform.parent.localScale = localScale;
        }
    }

```

When I replace `transform.parent.localScale = localScale` to `transform.localScale = localScale` it works except it flips all of the gameObjects, including the camera.

# Answer
> 2 votes
Because of the nature of my 2D platformer, I was able to just use the flipX boolean on the Sprite Renderer. I didn't notice it was there! This code works great:

```
private void Flip() {
    if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f) {
        isFacingRight = !isFacingRight;
        GetComponent<SpriteRenderer>().flipX = !isFacingRight;
    }
}

```

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


# Question
Title: Why does my XR ray refuses to cast on my UI?
I have about ten UIs with buttons in my scene. I can cast my XR Ray on all of these UIs and the buttons work fine except two. The buttons on these two UIs are clickable but the rays are not showing on them. I don't know why

# Answer
> 0 votes
I managed to solve this by adding an XR Simple Interactable component and a box collider to these two canvases. One thing is that if the collider protrudes out too much, the xr-ray will not be able to interact with the items on the canvas, the end point of the ray will be front of the collider. So, I made the canvas as tight as possible and it worked as expected.

---
Tags: unity, raycasting
---


# Question
Title: How to publish WebXR game on Quest or Steam stores?
I would like to develop a simple and small game for WebXR so that Quest, Index, etc. can play it. I would eventually like to be able to put it on the Quest store and Steam.

Is there a way to publish a WebXR game in those stores? Or would I have to compile it for Android/Windows as a native application?

I am a web developer and familiar with JavaScript, so I was planning to use three.js

# Answer
> 1 votes
Meta has an official process for WebXR content & is covered on their documentation on WebXR Workflow:

> ## Publishing Your Experience
>
> A WebXR experience is just a normal web page, so it can be served online like any other site.
>
> Meta Quest Browser also features WebXR experiences on the New Tab Page. If you have created a WebXR experience that you’d want to get featured, see the submissions guidelines page.
>
> ### WebXR Submission Form
>
> After following the guidelines and confirming you meet the technical requirements, submit your experience with the WebXR Submission form to be considered for the New Tab Page.

Their submissions guidelines (linked above) list both content guidelines, technical requirements and technical recommendations. I suggest familiarizing yourself with them *before* investing resources in development so as to maximize effort on things that meet their criteria. You should also note that the openly state meeting their criteria does not guarantee your experience will be featured.

They also have additional WebXR developer info here: Get Started with Oculus Browser & WebXR.

# Answer
> 0 votes
you can publish your game on heyvr.io. https://heyvr.io/publish There you can also get a lot more information on how to do it and what tools you can use.

Also there are a lot of WebXR games you can try to get some impressions for your game.

They also have a Discord https://discord.gg/xdzBpmqj. The founders and other developers are very responsive and happy to help.

---
Tags: javascript, webgl, three.js, steam
---


# Question
Title: How to capture consecutive key strokes for different input modes
I'm making an Ultima spinoff which requires a lot of key strokes for actions. For example the arrow keys are for movement BUT once the player presses down the 'T' (talk) key the arrow keys are used for determining which NPC to talk to.

In summary, 'T' + arrow keys is the combination to initiate conversion with NPCs, and arrow keys alone are for movement. Right now I'm using a flag `isInConversation` whenever 'T' has been pressed, but this looks silly and can quickly increases the number of flags once other functionalities go online.

What do you think? Is a state machine a better option?

Here is the code:

```
        while (SDL_PollEvent(&e) != 0)
        {
            //User requests quit
            if (e.type == SDL_QUIT)
            {
                quit = true;
            }
            else if (e.type == SDL_KEYDOWN)
            {
                //Select surfaces based on key press
                switch (e.key.keysym.sym)
                {
                case SDLK_UP:
                    if (isInConversation) { // check NPCs in north direction }
                    else if (ai.canMoveDirection(&playerEntity, NORTH, currentMap)) {
                        updatePlayer(NORTH);
                        scroll(NORTH);
                    }
                    break;
                case SDLK_DOWN:
                    if (isInConversation) { // check NPCs in south direction }
                    else if (ai.canMoveDirection(&playerEntity, SOUTH, currentMap)) {
                        updatePlayer(SOUTH);
                        scroll(SOUTH);
                    }
                    break;
                case SDLK_LEFT:
                    if (isInConversation) { // check NPCs in west direction }
                    else if (ai.canMoveDirection(&playerEntity, WEST, currentMap)) {
                        updatePlayer(WEST);
                        scroll(WEST);
                    }
                    break;
                case SDLK_RIGHT:
                    if (isInConversation) { // check NPCs in east direction }
                    else if (ai.canMoveDirection(&playerEntity, EAST, currentMap)) {
                        updatePlayer(EAST);
                        scroll(EAST);
                    }
                    break;
                case SDLK_ESCAPE:
                    quit = true;
                    break;
                case SDLK_e:
                    // trigger map change
                    changeMap();
                    break;
                case SDLK_t:
                    // talk, should set keystate to ENTER_TALK
                    // So expecting an arrow key afterwards
                    inConversationState = true;
                default:
                    break;
                }
                // Each key down triggers npc movement
                for (auto n : currentMap->getNPC()) {
                    ai.moveRandomly(n, currentMap);
                }
            }
        }

```

# Answer
> 1 votes
This way is works, but in case you need more key strokes(like 3 or more keys pressed) this code are going to be more complicated. I suggest you to redesign your code to first detect events and then after that, update your game. You are doing both at the same time.

Simple example:

```
bool tPressed = false;
bool upPressed = false;

while(SDL_PollEvent(&event)) { //NOTE THIS CAN be runned more than one time at a game loop
//HANDLE t and up variables here
}

//NOTE Now all of your events are been handled, you can update your.
if(tPressed && upPressed) {
//Do the doings case both key are pressed
}

```

This design is pretty common to handle multiple keys pressed and also presented by official SDL documentation in this link: https://www.libsdl.org/release/SDL-1.2.15/docs/html/guideinputkeyboard.html

---
Tags: c++, input, sdl2
---


title: Can't see instantiated UI element

text:
# Question
Title: Can't see instantiated UI element
I'm trying to create a level editor for a 2D game and I wanted to instantiate radio buttons, the backgrounds and numbers of which are determined by the tilesheet I load.

I'm sure I'm doing something simple wrong but I can't figure it out. When I instantiate these radio buttons and set their locations and backgrounds to the values I want, they appear in the object hierarchy and each have the correct location but are not displayed. The "Toggle" resource I'm using is the basic Unity toggle object saved in my resources folder. In the screenshot you can see in the scene view that they appear to be in the correct location (the large box at the bottom) since the bounds for the rect transforms show up in the right spot.

In the script I'm using, my tileset is sliced into 32x32 squares using unity's slicing tool and has been placed into the script's public tilesheets\[\] array. It is then used to load all the component sprites, each of which should be used to make a unique radio button. These radio buttons are all parented to the transform of the script, which is the toggleGroup "group\_sprites". The script is as follows:

```
using UnityEngine;
using UnityEngine.UI;
using UnityEditor;
using System.Collections;
using System.Linq;

public class SpriteSelector : MonoBehaviour {

    ToggleGroup group_sprites;
    Toggle[][] toggles;
    public Texture2D[] tilesheets;
    public Texture2D checkmark;
    int sliceSize = 32;
    int level;

    public void Setup()
    {
        group_sprites = GameObject.Find ("group_sprites").GetComponent<ToggleGroup> ();
        //Slice the current thingy
        LoadTileset (0);

        //Make a toggle group
    }

    public void LoadTileset(int _level)
    {
        level = _level;
        //Slice em up
        string spriteSheet = AssetDatabase.GetAssetPath(tilesheets[level]);
        Sprite[] sprites = AssetDatabase.LoadAllAssetsAtPath (spriteSheet)
            .OfType<Sprite> ().ToArray ();

        RectTransform parentRect = gameObject.GetComponent<RectTransform> ();
        int buffer = 1;
        float toggleWidth = parentRect.rect.width/8 - buffer;
        float xPos = -76.45f;
        float yPos = 42.3f;
        foreach(Sprite sprite in sprites)
        {
            GameObject terrainToggle = (GameObject)GameObject.Instantiate(Resources.Load ("Toggle"));
            terrainToggle.transform.SetParent(transform);
            GameObject Background = terrainToggle.transform.FindChild("Background").gameObject;
            GameObject CheckMark = Background.transform.FindChild("Checkmark").gameObject;

            //location
            RectTransform trans = terrainToggle.GetComponent<RectTransform>();
            trans.sizeDelta = new Vector2(toggleWidth, toggleWidth);
            trans.anchoredPosition = new Vector2(xPos ,yPos);//+ trans.sizeDelta.x/2, yPos - trans.sizeDelta.y/2);

            //background
            //Background.GetComponent<Image>().overrideSprite = sprite;
            Image backImage  = Background.GetComponent<Image>();
            backImage.sprite = sprite;
            //checkmark
            CheckMark.GetComponent<Image>().sprite = Sprite.Create (checkmark, new Rect(0,0,checkmark.width, checkmark.height), new Vector2(0.5f,0.5f));

            xPos += parentRect.rect.width/8;
            if(xPos > parentRect.rect.width/2)
            {
                xPos = -76.45f;
                yPos -= parentRect.rect.width/8;
            }
        }

        //foreach slice, make a toggle
    }

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

        //if click on a tile,
    }
}

```

Thanks!!

# Answer
For anyone interested, my problem was that the prefabs were instantiated as part of an Awake() call, which evidently makes your prefabs invisible. Moving the instantiation to a Start() call fixed my problem.
> 1 votes

# Answer
I had a similar problem that was due to "Image" from an Instantiate call was not working but a "RawImage" working fine.
> 0 votes

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


# Question
Title: How to fix the warning "Only textures with width / height being multiple of 4 can be compressed to ETC2 format"?
This question is about Unity texture compression.

I have an image that has the dimensions as follows: width = 724, and height = 1044. The original size is 348 Kbytes. This means that both the width and height are multiple of 4.

If I open this image in Unity, change the type to **sprite (2D and UI)**, and set the max size to **2048**, then Unity rendered this image with the size of 0.7 M, which is bigger than the original size of 348 Kbytes.

If I open this image in Unity, change the type to **sprite (2D and UI)**, and set the max size to **1024**, then Unity displays a strange warning as follows "**Only textures with width / height being multiple of 4 can be compressed to ETC2 format**", and it does not compress this image even though I believe that both the width and height of this image are already multiple of 4 because as I wrote earlier, the dimensions of the image are as follows: width = 724, and height = 1044.

Would you please show me how to fix that warning message above ?

# Answer
> 3 votes
It's not unusual for the "compressed" sizes of game textures to be larger than the source asset files, because the compression formats we use at runtime in games need to be GPU-readable.

I go into more detail about this in other answers, but to be brief:

* Typical compression formats we use for source assets or images on the web (PNG, JPG) can use variable bit rates: taking predictable areas of the image and compressing them more, while complex parts of the image use more raw data. They're also decompressing the whole image at once, so they can use information from one part of the image to make predictions to better compress other parts of the image.
* When rendering an image with a GPU, you need random access. A shader core needs to be able to ask "What's the colour at pixel (154, 1011)?" and the texture unit needs to know the exact position in memory to find that and be able to answer the question *fast*, without taking the time to read distant parts of the image to work out the correct decompression table.

That unfortunately means compression for game assets isn't as good by many metrics as PNG/JPG. We generally have to deal with larger memory footprints, and as we try to crunch down the file size we see visible quality loss much faster, because the more aggressive compression algorithm hits all parts of the image, not just the smooth compressible parts.

For that reason, images that are very sensitive to being displayed just-so, like 2D sprites and UI images, will be saved in an uncompressed format, so you don't get the visual degradation that comes with GPU texture compression. That's why changing the image type to "Sprite (2D and UI)" makes the file size double in your case.

0.7 MB is still not that bad in an era when GPU have gigabytes of fast video RAM, and even most phones have access to multiple gigabytes of shared RAM, but it can add up over a large game, or if you're trying to really crunch your download size. See advice for reducing Unity build size, including use of asset bundles and addressables for some ideas there.

---

The next bit is just math. If you try to save a 724x1044 image at "Max size 1024", then that height has to change, since 1044 is greater than 1024.

So, following your instructions, Unity scales down the image proportionately, so the height is 1024 (the max allowed), and the width keeps the original 181:261 ratio of the original as best it can. 1024 * 724/1044 = 710.130... which rounds to 710, so you get an image that's 710x1024.

1024 divides evenly by 4, but 710 does not (it's 2 * 355 - no more prime factors of 2 left). So the error message is accurately telling you that it cannot compress the image using ETC2 at the size you've specified.

To fix this, try manually scaling your image (or cropping if necessary) to a desired size that fits the multiple-of-4 criterion. Adding two single-pixel-wide columns of padding or slightly stretching the aspect ratio to 712x1024 would be enough.

If this image is used as a sprite or UI image, then you may also be able to store it in a larger 2048x2048 image and use the extra space to store other sprites - something called a Sprite Atlas. Then each image inside that meta-image is free to have whatever strange dimensions it wants, as long as it doesn't overlap with its neighbours. Unity has features to automatically pack your assets together into atlases, which can also speed up drawing by reducing state switching between content that's drawn back-to-back.

---
Tags: unity, textures, compression
---


# Question
Title: Equivalent of RigidBody2D's body_exited on StaticBody2D?
I'm building a type of Pinball game using Godot 4.0. I've got two types of components relevant to this question:

* **balls**, represented as a `RigidBody2D` scene with `Sprite` and circular `CollisionShape2D` children
* **circular bumpers**, represented as a `StaticBody2D` scene with `Sprite` and circular `CollisionShape2D` children

When a ball hits *any* object, that *other* object should be "in charge" (code-wise) of what happens; at least, to get some clean code. However, the `body_exited` signal is only available on the balls' node type, but not available on `StaticBody2D`.

**I'd *want* to write (pseudo-code):**

```
# In StaticBody2D BumperCircular.gd:
func _on_body_exited(body):
    if is_ball(body):
        # add bonus velocity because of the bump

```

I feel like I'm missing something, because it seems wrong to add `body_exited` on the Ball and then dispatch/delegate back to the other body for logic on what happens next.

**So I feel like I *have* to write:**

```
# In RigidBody2D Ball.gd:
func _on_body_exited(body):
    if is_bumper(body):
        # logic for bumper coded inside this script
    else if is_some_component(body):
        # logic for component type 2 coded inside this script
    else if is_some_component(body):
        # logic for component type 3 coded inside this script
    # etc.
        # etc.

```

Or at best:

```
# In RigidBody2D Ball.gd:
func _on_body_exited(body):
    if has_ball_collision_logic(body):
        body.on_ball_collision_logic(this) # dispatch to the other object for logic

```

But both seem to me the wrong way around.

What am I missing here? **Why is there no `body_exited` on `StaticBody2D`?**

PS. I've searched this Stack Exchange site and online in general, plus I've peered through the (inheritance tree of the) StaticBody2D documentation but found no relevant info yet.

# Answer
> 5 votes
**Note**: even thought this answer is written for 2D, equivalent approaches would work for 3D.

---

**Solution 1: Use a `RigidBody2D`.**

You can set the `freeze` property of your `RigidBody2D` to `true`, and its `freeze_mode` to `FREEZE_MODE_STATIC` which will make it not move just like an `StaticBody2D`.

However, apparently the signals won't be enabled unless you set it to `FREEZE_MODE_KINEMATIC`.

---

**Solution 2: Duck type it.**

This idea would almost work:

> ```
> # In RigidBody2D Ball.gd:
> func _on_body_exited(body):
>     if has_ball_collision_logic(body):
>         body.on_ball_collision_logic(this)
>
> ```

To make it work, you can check for the particular method you are going to call:

```
func _on_body_exited(body):
    if body.has_method(&"on_ball_collision_logic"):
        body.on_ball_collision_logic(this)

```

---

**Solution 3: Give an `Area2D` to your `StaticBody2D` (or `CharacterBody2D`)**

Your `StaticBody2D` (or `CharacterBody2D`) can't detect collisions, but an `Area2D` can. So you can add `Area2D` as a child of it, in such way that it has identical position and colliders, it can detect the collisions for the `StaticBody2D` (or `CharacterBody2D`).

---

**Solution 4: Make the `StaticBody2D` (or `CharacterBody2D`) detect collisions.**

We are going to add an `_integrate_forces` callback to the `StaticBody2D` (or `CharacterBody2D`) using `body_set_force_integration_callback`:

```
func _ready() -> void:
    PhysicsServer2D.body_set_force_integration_callback(
        get_rid(),
        _integrate_forces
    )

func _integrate_forces(PhysicsDirectBodyState2D state, userdata) -> void:
    pass

```

Next we will ask `PhysicsDirectBodyState2D` for contacts, but for that to work we need to set how many contacts we want to get:

```
func _ready() -> void:
    var body_rid := get_rid()
    PhysicsServer2D.body_set_force_integration_callback(
        body_rid,
        _integrate_forces
    )
    body_set_max_contacts_reported(body_rid, 32)

func _integrate_forces(PhysicsDirectBodyState2D state, userdata) -> void:
    for index in state.get_contact_count():
        var body := state.get_contact_collider_object(index) as PhysicsBody2D

```

And then we will keep track of them, so we can emit signals:

```
signal body_entered(body:Node)
signal body_exited(body:Node)

var colliding_bodies := {}

func _ready() -> void:
    var body_rid := get_rid()
    PhysicsServer2D.body_set_force_integration_callback(
        body_rid,
        _integrate_forces
    )
    body_set_max_contacts_reported(body_rid, 32)

func _integrate_forces(PhysicsDirectBodyState2D state, userdata) -> void:
    var new_colliding_bodies := {}
    for index in state.get_contact_count():
        var body := state.get_contact_collider_object(index) as PhysicsBody2D
        if not is_instance_valid(body):
            continue

        new_colliding_bodies[body] = body
        if not colliding_bodies.has(body):
            body_entered.emit(body)

    for body in colliding_bodies.keys():
        if not new_colliding_bodies.has(body):
            body_exited.emit(body)

    colliding_bodies = new_colliding_bodies

```

And there you have `body_entered` and `body_exited` added to your `StaticBody2D` (or `CharacterBody2D`).

---

> Why is there no `body_exited` on `StaticBody2D`?

The engine does not need to put the work for the `StaticBody2D` body to detect collisions because the `StaticBody2D` won't react to collisions. So these are not offered out of the box.

---
Tags: collision-detection, godot, gdscript
---


# Question
Title: How to lock aspect ratio when resizing game window in unity?
I want a scalable game window that when resized stays at 16:9 aspect ratio. The goal is for the user to be able grab the window on the right or bottom and resize it. The game should adjust the corresponding side of the view-port to lock the aspect ratio. I've tried forcing certain values in the update line of a script on the camera, but it did not work. the game is 2d and most of the elements are scripted using the gui functions. I'm having a very hard time finding exactly what I'm looking for as it is, most of what I've found is in an attempt to create black bars and keep the game from stretching, but that doesn't help ongui using matrices.

here are the resources I've tried so far

http://goo.gl/8FuyRC \- this one is a script someone wrote that I attached to the main scene camera, I then built it, however that didn't work.

http://goo.gl/qZ5DAl \- this is something from the unity website regarding camera aspect ratio. I put a line of code in the update function of my camera object

```
#pragma strict

function Start () {

}

function Update () {
Camera.main.orthographicSize = 3.596306;
}

```

as well as

```
#pragma strict

function Start () {

}

function Update () {
Camera.aspect = 1;
}

```

none of the above worked.

http ://goo.gl/MbTDcz - was the last thing I tried, and it just made some more black bars...

so far nothing has worked. not sure why. to reiterate, the goal I'm trying to accomplish is that, when the user grabs the edge of a windowed player, and drags it, the corresponding x or y axis will follow in suit to keep the aspect ratio the same.

# Answer
> 1 votes
From the script you're posting, it looks like you're changing variables on the camera, which won't affect the screen size. This is pseudocode (and untested), but this should be the right concept:

```
private var lastWidth : int = 0;
private var lastHeight : int = 0;

function Start () {

}

function Update ()
{
    var width = Screen.width;
    var height = Screen.height;

    if(lastWidth != width) // if the user is changing the width
    {
        // update the height
        var heightAccordingToWidth = width / 16.0 * 9.0;
        Screen.SetResolution(width, Mathf.Round(heightAccordingToWidth), false, 0);
    }
    else if(lastHeight != height) // if the user is changing the height
    {
        // update the width
        var widthAccordingToHeight = height / 9.0 * 16.0;
        Screen.SetResolution(Mathf.Round(widthAccordingToHeight), height, false, 0);
    }

    lastWidth = width;
    lastHeight = height;
}

```

Again, changing the camera height and width isn't the same as changing the window width/height.

# Answer
> 1 votes
After reading the answer above, I created a script which rescales the window every a fixed amount of frames, because changing every frame causes a lot of problems.

Just put it on the MainCamera:

```
using UnityEngine;

public class CameraAspectRatioManager : MonoBehaviour
{
    [SerializeField] private int widthAspect = 16;
    [SerializeField] private int heightAspect = 9;
    [Tooltip("After every how many frames to rescale the windows size.")]
    [SerializeField] private int updateAspectDelay = 100;

    private int frame = 0;

    private int lastWidth = 0;
    private int lastHeight = 0;

    private void Update()
    {
        frame++;

        if (frame % updateAspectDelay != 0) { return; }

        var width = Screen.width;
        var height = Screen.height;

        if (lastWidth != width) // if the user is changing the width
        {
            // update the height
            float heightAccordingToWidth = (float) width / widthAspect * heightAspect;
            Screen.SetResolution(width, (int)Mathf.Round(heightAccordingToWidth), false);
        }
        else if (lastHeight != height) // if the user is changing the height
        {
            // update the width
            float widthAccordingToHeight = (float) height / heightAspect * widthAspect;
            Screen.SetResolution((int)Mathf.Round(widthAccordingToHeight), height, false);
        }

        lastWidth = width;
        lastHeight = height;
    }
}

```

---
Tags: unity, javascript, window-management
---


# Question
Title: UI Toolkit not firing button clicked event
I'm using the new UI Toolkit and new Input System together, and I've setup everything correctly the Input Actions has separate input for UI, the Input System UI Input Module is setup correctly, the Visual Tree works in the scene, and my custom script has no errors, but for some reason my Button doesn't fire the clicked event. Everything works when debugged, I also made the button change color when active, which it does, but it doesn't fire an event...

# Answer
I haven't mentioned how my UI Controller works, turns out that disabling a UI Document removes all events. Just reassign the events in the OnEnable() method.
> 0 votes

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


# Question
Title: Why is reinforcement learning not widely adopted as an AI tool for agents in well-known games?
Reinforcement learning has shown remarkable success in game-playing agents, as seen in the achievements of AlphaGo and OpenAI's Dota 2 AI. There are a few tools, such as Unity ML Agents, to integrate state-of-the-art algorithms into game engines, and we have recently seen that Grand Turismo 7 added an AI racer trained with reinforcement learning into their game. However, this approach to creating intelligent agents seems not widely adopted in many other complex games where AI agents such as NPCs and other opponents could benefit from its capabilities. Examples of successful integrations are still minimal.

I'm curious to know the reasons behind this trend. Why is reinforcement learning not being widely adopted as an AI tool for agents in games? Is it still too early to have this technology or are there technical limitations or practical challenges that make it difficult to implement? Or are other factors, such as ethical concerns or legal issues, hindering its adoption?

I would appreciate any insights or references to relevant literature or failed attempts to integrate reinforcement learning algorithms into games on this topic.

# Answer
At a very high level: reinforcement learning solves a different problem than the one game AI programmers are typically trying to solve.

It's great if you want to make an opponent that's good at *winning*, *efficiently* in problem spaces that are *incompletely known*, possibly by exhibiting *surprising* strategies that a human wouldn't have intuited, thought to code into it, or know how to counter effectively.

In digital games, we often want our AI characters to play to *lose*, *entertainingly*, in problem spaces that are *completely known* (like a fixed map we can annotate with waypoints / behaviour hints in advance), and we want them to do it in ways that *aren't overly surprising* or counter-intuitive, else it looks like a bug or cheating.

This playing-for-fun-not-to-win is harder to quantify into a reward function, and it's difficult to anticipate and fence off every exploit or weird-looking emergent behaviour the RL process might wander into.

Sometimes we prefer AI who are downright predictable, because then our players have fun manipulating them, and our designers can more easily tune them to get the frequencies of different behaviours they want / that our playtests show tend to yield the most fun. (And as a bonus, our AI bugs are reproducible and easier to reason about and fix!)

Players who want to be challenged by an intelligent and adaptive opponent trying its best to beat them usually prefer to play against other human players. Letting them get their challenge fix that way builds social stickiness into the game by fostering play relationships with friends, guild mates, rivals, tournaments, streaming audiences... relationships players don't tend to form with AI opponents.

There could absolutely be benefit to having reinforcement learning opponents as a training mode to help someone get up to speed with competitive play, without the social shame of losing to fellow humans over and over. But the development cost of doing that well is probably quite high for many games, compared to using a ranking/matchmaking system to pair up beginner players with other beginners, as long as the game is able to maintain a critical mass of active players (and if it's not, the developers have bigger problems).
> 54 votes

# Answer
## "Artificial intelligence" in games

In general, enemy agents in video games do not use machine learning. Instead they are expert systems, behavior tree, cellular automata, finite state machines, path-finding, and similar solutions. All of which were at some point considered artificial/computational intelligence.

These terms refer to always changing sets of technologies. For example, at some point path-finding was considered "Artificial intelligence". Currently when people say "Artificial intelligence" they are thinking of machine learning.

The rest of this answer is about machine learning and video games. *Taking for granted that we can use machine learning models to assist in asset creation.*

---

## Making enemy agents with machine learning is not a great idea

A lot of the applications of machine learning to video games are because video games pose a complex controllable challenge for the artificial agents. So, it is the video game industry being useful for machine learning research, and not the other way around.

As DMGregory explains making opponent artificial agents fit into the desing of the game is a remarkable challenge, because we want them to "lose, entertainingly", and it would not be straight forward to train a model for that as opposed to training it to win. Also predictible enemies are often better as the players can steadily figure out how to defeat them.

Furthermore, machine learning solutions create friction to change (changes will often require to retrain the machine learning models) and are hard to debug (Explainable Machine Learning is an active area of research).

---

## Examples of machine learning in video games

*Again, taking for granted that we can use machine learning models to assist in asset creation.*

A notable example of using machine learning in video games is augmented reality, which builds on top of computer vision. For example facial tracking and skeletal tracking implemented with pre-trained models.

We can find an examples of pre-trained models in more traditional games. For example, Supreme Commander 2 uses an artificial neural network pre-trained model to allow units to take decisions.

A more recent application is Deep Learning Super Sampling (DLSS). *Yet, I'm betting that is not what you had in mind.*

Furthermore, there are already experiments of using large language models and other generative models - running on a remote server - in games. *But - at the time of writing - these are indie games that use it as gimmick.*

---

## Feasibility of training machine learning models during game play

So far we have talked about pre-trained models. That is because:

* **Time**: it is unlikely that your game session is not going to last long enough to train a model. Much less if you want to do learning at the character level, since your would be interacting with another character for just a small fraction of the game session (unless it is a character companion). *And if it is an enemy character, chances are you kill it before you could tell if it was smart or not.*
* **Performance**: You would be taking a fraction of the CPU time budget to train the AI. *Remember that in video games the game already has a lot of things to do each frame to keep the game running smoothly.*

**Are there games that train a neural network during game play?** Yes. In indie games where that is the point (games about creature evolution), or games created as part of research projects.

**Addendum**: There is a note worthy example: Black & White by Lionhead studios. It trained a neural network during game play, which was used as part of the pet creature behavior logic. The player could reward or punish the creature at any moment which would be applied to recent behaviors. Also, while leashed to the player the creature had a chance to mimic player actions. So positive training was the player would leash the creature, do the actions them wanted it to do, and then reward the creature for it. Negative was the player catching the creature doing something they didn't want to do and punishing it. I also want to point out that it was a very small model, which allowed for training it this way.

In fact, the situation might improve: The paper "**The Forward-Forward Algorithm: Some Preliminary Investigations**" released in December of last year introduces an alternative to back-propagation which is less computationally intensive and has faster training rounds (although it will require more training round to archive the same results) which might allow to train models during game play.

This does not change the fact that making opponent artificial agents work within the game design is a remarkable challenge. Yet, it makes other solutions more feasible, such as artificial agent companions that assist the player, and machine learning solutions for dynamic difficulty.
> 12 votes

---
Tags: ai, reinforcement-learning
---


# Question
Title: Add delay between taking repeated damage from a hazard
I have a 2D platformer and when the player collides with a tile that is on the Hazard layer, the player takes 1 damage. However, I would like for there to be a 2 second delay until the next time the player takes damage again even if they're still colliding with the hazard. As of right now, the player loses all of their health immediately and there is (seemingly) no pause. This is what I have:

```
using System.Collections;
using UnityEngine;

public class Player : MonoBehaviour {

    public int maxHealth = 10;
    public int currentHealth;
    public HealthBar healthBar;

    [SerializeField] private Transform groundCheck;
    [SerializeField] private LayerMask hazardLayer;

    void Start() {
        currentHealth = maxHealth;
        healthBar.SetMaxHealth(maxHealth);
    }

    void Update() {
        if (Physics2D.OverlapCircle(groundCheck.position, 0.5f, hazardLayer)) {
            TakeDamage(1);
            StartCoroutine(DamagePause());
        }
    }

    void TakeDamage(int damage) {
        currentHealth -= damage;
        healthBar.SetHealth(currentHealth);
    }

    IEnumerator DamagePause() {
        yield return new WaitForSeconds(2);
    }
}

```

The Coroutine is not working. How could I go about doing this?

# Answer
> 1 votes
I ended up figuring out I could just create a counter instead of using the Coroutine. Still not sure why the Coroutine didn't work but this works:

```
using UnityEngine;

public class Player : MonoBehaviour {

    public int maxHealth = 10;
    public int currentHealth;
    public HealthBar healthBar;

    //a constant that we return to for the total damage delay period length
    const float DAMAGE_DELAY = 2; //in seconds
    //the current damage delay point we are on in the delay timer
    private float damageDelay;

    [SerializeField] private Transform groundCheck;
    [SerializeField] private LayerMask hazardLayer;

    void Start() {
        currentHealth = maxHealth;
        healthBar.SetMaxHealth(maxHealth);
    }

    void Update() {
        //subtract 1 every real life second
        damageDelay -= Time.deltaTime;
        if (Physics2D.OverlapCircle(groundCheck.position, 0.5f, hazardLayer)) {
            TakeDamage(1);
        }
    }

    void TakeDamage(int damage) {
        //if the current number in the damageDelay is <= 0 or in other words if
        //2 seconds delay has passed, subtract 1 from the healthbar
        if (damageDelay <= 0) {
            currentHealth -= damage;
            healthBar.SetHealth(currentHealth);
            //set damageDelay to start a new cooldown/delay period (2 seconds)
            damageDelay = DAMAGE_DELAY;
        }
    }
}

```

# Answer
> 5 votes
That's not how coroutines work. Coroutine is non-blocking, It cannot prevent the execution of the next Update.

You can set a flag in the coroutine and read it in `Update()`:

```
public class Player : MonoBehaviour {

    private bool isInDamageCD;

    void Update() {
        if (!isInDamageCD) {
            if (Physics2D.OverlapCircle(groundCheck.position, 0.5f, hazardLayer)) {
                TakeDamage(1);
                StartCoroutine(DamagePause());
            }
        }
    }

    IEnumerator DamagePause() {
        isInDamageCD = true;
        yield return new WaitForSeconds(2);
        isInDamageCD = false;
    }
}

```

Or you can start a coroutine in `Start()` and perform all checks inside it:

```
public class Player : MonoBehaviour {

    void Start() {
        StartCoroutine(HazardDamage());
    }

    IEnumerator HazardDamage() {
        while(true) {
            while(true) {
                if (Physics2D.OverlapCircle(groundCheck.position, 0.5f, hazardLayer)) {
                    TakeDamage(1);
                    break;
                }
                yield return null;
            }
            yield return new WaitForSeconds(2);
        }
    }
}

```

The Coroutines are not some kind of unity magic, They just register some iterator with yeild to unity, and executes the iterator at a specific place in each frame. I think anyone starting out with coroutines should read what iterators are.

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


title: OnTriggerExit Coroutine won't stop?

text:
# Question
Title: OnTriggerExit Coroutine won't stop?
i use StopCoroutine to stop "AttackPlayer", but their keep exculte the TakeDamage() function, even i stop it.

how to totally stop the IEnumerator , use bool to turn the whileloop on and off?

```
   void OnTriggerEnter(Collider other)
    {
        if (other.TryGetComponent(out Player player))
        {
            // Attack the player
            StartCoroutine(AttackPlayer(other));
        }
    }

   void OnTriggerExit(Collider other)
    {
        if (other.TryGetComponent(out Player player))
        {
            // Stop attacking the player
            StopCoroutine("AttackPlayer");
        }
    }

    IEnumerator AttackPlayer(Collider playerCollider)
    {
        Player player = playerCollider.GetComponent<Player>();
        while (player != null)
        {
              TakeDamage();
              yield return new WaitForSeconds(AttackSpeed);
        }
    }

```

# Answer
> 1 votes
S. Tank Çetin's answer correctly shows why your code doesn't work. What you can do instead is capture a reference to the coroutine in progress when you start it, then stop *that*:

```
Coroutine _attackInProgress;

void OnTriggerEnter(Collider other)
{
    if (_attackInProgress == null && other.TryGetComponent(out Player player))
    {
        // Attack the player
        _attackInProgress = StartCoroutine(AttackPlayer(player));
    }
}

void OnTriggerExit(Collider other)
{
    if (_attqckInProgress != null && other.TryGetComponent(out Player player))
    {
        // Stop attacking the player
        StopCoroutine(_attackInProgress);
        _attackInProgess = null;
    }
}

IEnumerator AttackPlayer(Player player)
{
    while (player != null)
    {
          TakeDamage();
          yield return new WaitForSeconds(AttackSpeed);
    }

    _attackInProgress = null;
}

```

You'll notice I (again) changed your `AttackPlayer` function to accept a `Player`, not a `Collider`. It's unnecessarily wasteful to search for the `Player` component twice, once in `OnTriggerEnter` and again in `AttackPlayer`, when the calling function could have just given it an instance of the type it needs directly.

# Answer
> 1 votes
You can't start with the function call syntax and end with the string syntax.

> Note: Do not mix the three arguments. If a string is used as the argument in StartCoroutine, use the string in StopCoroutine. Similarly, use the IEnumerator in both StartCoroutine and StopCoroutine. Finally, use StopCoroutine with the Coroutine used for creation.

See here: https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html

---
Tags: unity
---


# Question
Title: Trying to have damage flashing for a short time every time player takes damage
The code below has the player flashing when touching a hazard but continues flashing indefinitely. If I stand on the spike for a few seconds, the flashing speeds up faster than I want.

```
public class Player : MonoBehaviour {

    public int maxHealth = 10;
    public int currentHealth;
    public HealthBar healthBar;

    private float currentDamageInterval;
   [SerializeField] private float damageInterval = 2f; //in seconds

   [SerializeField] private Transform groundCheck;
   [SerializeField] private LayerMask hazardLayer;

    private SpriteRenderer sr;
    private Color[] colors = { Color.red, Color.white };

    void Start() {
        sr = gameObject.GetComponent<SpriteRenderer>();
        currentHealth = maxHealth;
        healthBar.SetMaxHealth(maxHealth);
    }

    void Update() {
        //subtract 1 every real life second
        if (currentDamageInterval > 0) {
            //sr.color = Color.white;
            currentDamageInterval -= Time.deltaTime;
        }
        if(currentDamageInterval <= 0 ) {
            if (Physics2D.OverlapCircle(groundCheck.position, 0.5f, hazardLayer)) {
                TakeDamage(1);
            }
        }
    }

    public bool CanTakeDamage() {
        return !(currentDamageInterval > 0f);
    }

    public void TakeDamage(int damage) {
        //if the current number in the currentDamageInterval is <= 0 or in other words if
        //2 seconds delay has passed, subtract 1 from the healthbar
        if (currentDamageInterval <= 0) {
            currentHealth -= damage;
            healthBar.SetHealth(currentHealth);
            StartCoroutine(DamageFlashing(1f, .3f));
            //set currentDamageInterval to start a new cooldown/delay period (2 seconds)
            currentDamageInterval = damageInterval;
        }
        sr.color = Color.white;
    }

    IEnumerator DamageFlashing(float time, float intervalTime) {
        float elapsedTime = 0f;
        int index = 0;

        while (elapsedTime < time) {
            sr.color = colors[index % 2];

            elapsedTime += Time.deltaTime;
            index++;
            yield return new WaitForSeconds(intervalTime);
        }
    }
}

```

How can I have the flashing speed/intervals stay stable and stop flashing after 1 second (parameter I set in the DamageFlashing Coroutine)?

# Answer
You're starting multiple coroutines that are overlapping each other. Every 2 seconds you start a new copy of the coroutine while the other is still running, resulting in the increasing frequency of flashing.

"Shouldn't the old coroutine have finished by the time the new one starts?"

Not when you're advancing the timer like this:

```
elapsedTime += Time.deltaTime;
yield return new WaitForSeconds(intervalTime);

```

Here every `intervalTime = 0.3f` seconds, you advance your internal timer by only the time since the last frame — not the total time since the last coroutine iteration. If your game is running at 60 fps, then you're counting 16 ms for every 33 ms that pass. If your framerate is higher, your time dilation is even worse.

You can fix this like so, using the same interval to advance your timer that you use to pause the coroutine, and ensuring there's only one flashing coroutine running at a time.

```
    Coroutine _damageFlash;

    public void TakeDamage(int damage) {
        // You have a function for this,
        // and you already check this in Update!
        //if (currentDamageInterval <= 0) {

        currentHealth -= damage;
        healthBar.SetHealth(currentHealth);

        // Guarantee at most one coroutine runs at a time.
        if (_damageFlash != null)
            StopCoroutine (_damageFlash);

        _ damageFlash = StartCoroutine(DamageFlashing(1f, .3f));

        currentDamageInterval = damageInterval;
    }

    IEnumerator DamageFlashing(float duration, float interval) {

        int index = 0;
        var wait = new WaitForSeconds(interval);

        for (float elapsed = 0f; elapsed < duration; elapsed += interval) {
            sr.color = colors[index % 2];
            index++;
            yield return wait;
        }

        _damageFlash = null;
    }

```
> 1 votes

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


# Question
Title: Online Leaderboards: reducing cheaters without authoritative server verifying every move
My plan is to make a small game with **online leaderboards**.

Having everything calculated on the **server side is an unaffordable task**, so I need some other way.

My guess is that the best approach is to

* 1. **minimize** cheaters with some obvious protection
* 2. then run an **algorithm** on the rest, **flagging the suspicious** ones,
* 3. and then **manually** check them and remove the obvious ones.

Is this the best I can do in this case?

# Answer
> 2 votes
This solution is quite a lot of work, but still not as much as an authoritative server, and it also provides other benefits: **Add a record-and-replay feature to your game**.

1. Record all inputs and any non-deterministic events while the player is playing
2. Invent a file format to serialize that recorded data as a replay
3. Add a mode to the game which plays back a previously serialized replay
4. When someone submits a highscore, have them also submit the replay

Now when someone gets an outrageous high score, you can check how exactly they achieved that. This does not just allows you to catch cheaters, it also gives you great data to find out how the players are playing the game, which you can use to improve it. And if you also allow your players to view the replays of the top scorers, then they can learn from that.

It's still not 100% bullet-proof though, because someone could still use a program to generate a fake replay showing a perfect playthrough. But that requires a lot more effort than just sending an `INT_MAX` value to your API endpoint, because the cheater first needs to figure out how a perfect playthrough actually *looks like*.

# Answer
> 0 votes
If you're doing the score calculation on the client, there is not much you can do to prevent cheating.

You can and should validate the input sent to the server, for example:

```
collected_coins <= total_coins_in_game

```

However, this wont stop them from simply lying that they have the maxiumum amount possible. Running the game logic on the server would protect against this, but you stated this was not an option.

Even installing anti-cheat software on the client won't prevent them from sending false data over the internet. For more details on the topic, you can look at a similar question on the Information Security Stack Exchange.

In the end, if you're going to have a scoreboard for a single-player or fully client-side game, you'll have to accept the fact there is no way to stop a client from cheating if they really want to.

# Answer
> 0 votes
I believe Galaxy SDK has a free anti-cheat solution for this if you're open to using an external service.

From their docs, it looks like you can report scores as such:

```
GalaxyClientAPI.ReportScore(new GalaxySDK.ClientModels.ReportScoreRequest {
    Score = 500.0,
    LeaderboardId = "leaderboard_id",
}, result => { }, error => { });

```

And show the leaderboard with:

```
FindObjectOfType<GalaxyController>().ShowLeaderboard("leaderboard_id");

```

The dashboard/signup link is here.

---
Tags: security, leaderboards, anti-cheat
---


# Question
Title: How to predict where the soccer ball should be intercepted by an AI player after being kicked?
This question has been asked many times before, but most of the answers give solution to the problem where ball (target) is assumed to be moving at a constant velocity.

In my scenario, I'm making a football game. When I kick the ball into a direction by applying some force to the ball's rigidbody, I want a second AI player to find the point in the ball's path where he can intercept the ball. Now this ball can keep slowing down per frame, it does not keep moving with a constant speed.

I have attached an image for visualisation.

I know the ball's position, ball's current velocity, AI player's position, AI player's constant speed. How do I find such a point, where AI player can intercept the ball?

I am able to calculate such a point with the current velocity of the ball, but that point is not accurate, and changes as ball's current velocity changes per frame, as the ball can keep slowing down after every frame. This makes the AI player act kind of like a homing missile. Instead, I want the AI player to predict a point and just run to it.

Here's the C# (Unity) Code I have till now:

```
public Vector3 CalculateIntercept()
{
     Vector3 pos = Ball.GetInstance().transform.position;
     Vector3 dir = Ball.GetInstance().GetVelocity();
     dir.y = transform.position.y;

     float dist = (pos - transform.position).magnitude;
     return pos + (dist / 6.17f) * dir; //6.17 is the AI player's constant speed.
}

```

There's no drag on the ball, but there is a physics material with friction. I suppose to solve this, I might need to account for acceleration maybe.

Please help me figure this out. Thanks!

# Answer
> 1 votes
I'm sure there is probably a really complicated proper solution to this problem but I think we can probably cheat and get a quick answer using cached data and some functions.

Assuming the friction is constant on your field, you could probably calculate the amount of distance the ball travels over time by using something like:

```
// Attach me to the ball
public class BallLogger : MonoBehaviour
{
    public bool run = false;
    private float kickStartTime = 0.0f;
    private Vector3 kickStartPosition = Vector3.zero;
    private Vector3 lastPosition = Vector3.zero;

    private void Update()
    {
        if (run)
        {
            float kickTime = Time.time - kickStartTime;
            float kickDistance = (kickStartPos - transform.position).magnitude;
            float ballSpeed = Mathf.Abs(lastPosition - transform.position) / Time.deltaTime;
            Debug.Log("X (Time): " + kickTime + ", Y (Dist): " + kickDistance + ", Z (Speed): " + ballSpeed);

            run = ballSpeed > 0.001f;
        }
    }

    private void StartKick()
    {
        kickStartTime = Time.time;
        kickStartPosition = transform.position;
        lastPosition = transform.position;
    }
}

```

Once those values are known you can generate a function for determining the distance by feeding some of your values into a curve fitting tool (I use https://mycurvefit.com/, don't worry it's not an exercise website for ladies). Once you pick the equation that looks best for your data you should know how far away your ball is at any point in reasonable time (not accounting for crazy bounces and ricochets).

At this point we know where the ball is and will be at any given time, and now need to find where the player should intercept it. I'm sure there is a really smart way to do this, but I don't know it, so brace yourself. From here I would use a binary search like algorithm to see at which point on the balls path the player can reach without being either too early or too late. Some pseudo code for this would be like:

```
// true means I could probably get the ball, false means I can't
bool CheckMidPoint(float startTime, float endTime, int checksRemaining, out Vector3 bestMatch)
{
    if (checksRemaining > 0) // true if should we keep looking for a better place to get the ball.
    {
        float checkTime = 0.5f * (endTime - startTime);
        Vector3 futureBallPosition = WhereWillMyBallBe(checkTime);
        float myTime = PlayerTimeToPoint(futureBallPosition);

        if (myTime == checkTime) // this will probably never happen
        {
            return true;
        }
        else if (myTime < checkTime) // I got here too early
        {
            bestMatch = futureBallPosition;
            return true || CheckMidPoint(startTime, checkTime, checksRemaining-1, out bestMatch);
        }
        else // I got here too late
        {
            return CheckMidPoint(checkTime, startTime, checksRemaining-1, out bestMatch);
        }
    }
    else
    {
        return false; // lets hope one of the earlier checks passed otherwise let's give up, this guy is too chonky to get the ball.
    }
}

```

I apologize for not testing that and giving you better code but I am a bit short on time. Anyway that should return the best point to intercept the ball if it continues on the expected path. Be sure to keep your check count low (probably 10 is fine if only the closest player for each team is trying to get the ball) otherwise your frame rate might start to crawl.

# Answer
> 0 votes
Your only option is to dry run the simulation as the ball is kicked, then have the Ai begin moving to that location.

# Answer
> 0 votes
What I would do is calculate it as if it was constant speed, but re-calculate it as it is in the air, possibly every frame. As the ball gets closer to target, your constant speed calculations should approach the correct solution.

As a side-effect, you will get a realistic AI, as it will adjust itself as the ball approaches.

---
Tags: unity, physics, mathematics, projectile-physics, movement-prediction
---


# Question
Title: How can I fully or partially colorize a SpriteRenderer and make its "color" value match the end result at 100% opacity?
I have a GameObject that looks like this:

When I change the "color" value in the GameObject's SpriteRenderer to be (255, 0, 0, 255), the GameObject ends up looking like this:

But I want it to look this like instead:

What methods can I use to accomplish this?

My goal is to have it be dynamic so that it can range anywhere from "0% red" (the original colors) to "100% red" (entirely red, except for the transparent pixels).

For example, I want 50% red to look roughly like this:

# Answer
> 3 votes
After much trial and error, I was able to achieve what I wanted by modifing Unity's default "GUI/Text Shader" shader, which I downloaded from here under "Downloads (Win)" \> "Built in shaders".

I have very little idea how shaders work, but here's my crude explanation of what I think is happening in the shader code below:

1. It stores the original pixel art in a variable named `fixed4 sprite_texture`
2. It stores a solid colored copy of the pixel art, painted with the SpriteRenderer's current color, in a variable named `fixed4 solid_color`
3. It merges the two variables together using `lerp`, with the SpriteRenderer's current color's alpha value being used to determine how much the original pixel art should be colorized.

Once that shader has been applied to a GameObject's SpriteRenderer's material, I can easily change the GameObject's color through its MonoBehavior code.

**Usage example (C#):**

"0% red":

```
this.sprite_renderer.color = new Color(1f, 0f, 0f, 0f);

```

"50% red":

```
this.sprite_renderer.color = new Color(1f, 0f, 0f, .5f);

```

"100% red":

```
this.sprite_renderer.color = new Color(1f, 0f, 0f, 1f);

```

I'm not sure if there any drawbacks to this approach, but from what I can tell, it's easy to use, supports all colors (including pure white and black), and supports pixel art with a transparent background, which is exactly what I wanted.

**Usage example (GUI):**

**Full shader code:**

```
Shader "DynamicColorShader"
{
    Properties
    {
        _MainTex ("Font Texture", 2D) = "white" {}
    }

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

        Lighting Off Cull Off ZTest Always ZWrite Off
        Blend SrcAlpha OneMinusSrcAlpha

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile _ UNITY_SINGLE_PASS_STEREO STEREO_INSTANCING_ON STEREO_MULTIVIEW_ON
            #include "UnityCG.cginc"

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

            struct v2f
            {
                float4 vertex : SV_POSITION;
                fixed4 color : COLOR;
                float2 texcoord : TEXCOORD0;
                UNITY_VERTEX_OUTPUT_STEREO
            };

            sampler2D _MainTex;
            uniform float4 _MainTex_ST;
            uniform fixed4 _Color;

            v2f vert (appdata_t v)
            {
                v2f o;
                UNITY_SETUP_INSTANCE_ID(v);
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.color = v.color;
                o.texcoord = TRANSFORM_TEX(v.texcoord,_MainTex);
                return o;
            }

            fixed4 frag (v2f IN) : SV_Target
            {
                fixed4 sprite_texture = tex2D (_MainTex, IN.texcoord);

                fixed4 solid_color = IN.color;
                solid_color.a *= tex2D(_MainTex, IN.texcoord).a;

                fixed4 final = lerp(sprite_texture, solid_color, solid_color.a);

                return final;
            }
            ENDCG
        }
    }
}

```

# Answer
> 0 votes
The "color" parameter on a sprite renderer is applied as a tint, multiplied by the original texture colour. So it can only ever make colours darker in each of the red/green/blue channels — it can't "add red" where there was no red before.

If you don't want to write a custom shader, you can also just make a version of this sprite texture that has the same opacity (the same pattern of transparent and non-transparent pixels), but where all the pixel colours are white (255, 255, 255), which is `(1f, 1f, 1f)` when normalized. One multiplied by any other number is just that other number itself, so this lets you get your tint colour to output directly as the display colour.

If you sometimes want the multicolour version and sometimes the plain red version, you can swap the sprite renderer's sprite property at the same time that you change the tint colour.

# Answer
> -1 votes
You don't want to change the SpriteRenderer's `color`, but its shader (find it in `SpriteRenderer.material.shader`), so that it reduces any underlying image colour to one predefined colour.

You may check this: https://answers.unity.com/questions/1546026/shader-to-set-sprite-to-solid-color.html

And this: https://answers.unity.com/questions/582145/is-there-a-way-to-set-a-sprites-color-solid-white.html

---
Tags: unity, 2d, color, pixel, pixel-art
---


# Question
Title: What's the difference between VBoxContainer and VFlowContainer?
I'm trying to build some UI for my game made in Godot 4.0. I want to make a "Toolbox" scene and need to decide what containers to use. I come from web development, where I'd use a `flex` `column` and each tool would be a single row in that column of items.

In Godot 4 I have many options, the two relevant ones are nearly indistinguishable:

* `VBoxContainer`
    + UI Description is "*Vertical box container.*"
    + Official docs only say "*Vertical box container*" and tell me it has a `separation` property.
* `VFlowContainer`
    + UI Description is "*Vertical flow container.*"
    + Official docs say "*Vertical flow container.*" and tell me it has both a `h_separation` and `v_separation` property

The control tree in the Godot UI has some hints. The icon for `VBoxContainer` suggests it's what I want, but then again it lists a `ColorPicker` as a child of that type of node so that throws me off again.

What's the difference between these two controls, and when would I use one over the other?

# Answer
> 5 votes
First of all, these are `Container`s. So they will resize and arrange their children `Control`s. Adjusting to both the space available and the size of the children (which I reiterate that the `Container` can resize, so pay attention to container sizing properties of its children, which used to be called size flags in Godot 3.x).

In particular:

* `VBoxContainer`: Will arrange the children `Control`s in rows. One per row. Might grow vertically.
* `HBoxContainer`: Will arrange the children `Control`s in columns. One per column. Might grow horizontally.
* `VFlowContainer`: Will arrange the children `Control`s in columns. As many as it can fit per column, i.e. one per row until it runs out of vertical space and then start a new column. It does not force vertical alignment or sizes (elements of different columns might not align). Might grow horizontally.
* `HFlowContainer`: Will arrange the children `Control`s in rows. As many as it can fit per row, i.e. one per column until it runs out of horizontal space and then starts a new row. It does not force horizontal alignment or sizes (elements of different rows might not align). Might grow vertically.
* `GridContainer`: Will arrange the children `Control`s in rows and columns. As many as configured per row. It controls spacing and position to make a grid. Might grow vertically.

You can put any of the mentioned `Container`s inside of a `ScrollContainer` to get scroll bars.

---

I also want to mention a couple specialized classes:

* `MenuBar`: It will make menu bars by adding children `PopupMenu`s. Good for non-game application. It does not flow. You could make menu bars or tool bars with `HFlowContainer` and children `MenuButton`.
* `Tree`: It will make a tree like the ones you see in FileSystem or Scene in the Godot editor. It cal also make tables with multiple columns, where each row is an item. You must populate it from code. Also, it handles it own scrolling.

---

I don't know what you mean by "Toolbox". However, given that you mention `flex column`, I would suggest `VFlowContainer`, which I remind you might result in more than one column… If you don't want that use `VBoxContainer` instead.

---

If you have a look at the `ColorPicker`, you will see that it is made by rows:

The `ColorPicker` *is a* `VBoxContainer` so it gets to reuse all its logic.

For the curious, the first three rows are `HBoxContainer`, which is how they get multiple `Control`s in the same row. Then we have a `GridContainer` to make the color bars (made out of `Label`, `HSlider`, and `SpinBox`). The hex input is inside another `HBoxContainer`. And the "accordion"s on the bottom are `Button`s controlling the visibility of `GridContainer` for the color presets (which are also `Button`s).

---
Tags: gui, ui-design, godot-4
---


# Question
Title: Drag and drop differences between Godot 3 and 4?
I'd been following Godot tutorials to add Drag & Drop functionality to `Control` nodes. They've presumably been created for Godot 3.x, but my project is 4.0. And I can't seem to get it to work, thinking something has changed.

To make sure it's due to the difference in Godot versions, I did the exact same steps to reproduce the situation in both Godot 4.0 and 3.5.1:

1. Create new project, all default settings
2. Add `Node2D` root scene
3. Add a `PanelContainer` child to that
4. Add a `TextureRect` child to that, and drag the Godot icon resource on it for testing
5. Attach a new script to `PanelContainer` with this code:

```
 extends PanelContainer

 func get_drag_data(_position):
     var preview = TextureRect.new()
     preview.texture = $TextureRect.texture
     set_drag_preview(preview)
     return { id = "foobar" }

```
6. Run the game

The results:

* In 3.5.1, as expected, you can drag around the Godot icon;
* In 4.0, nothing happens, dragging the icon around won't work;

**What am I missing? How to get dragging of nodes working in version 4.x?**

I've tried a few extra things to answer my own question:

* Search the web, but at the time of writing it seems to give results that are 3.x-specific;
* Go through the node's "Inspector" properties, especially `Mouse` properties

# Answer
Nearly discarded my question because I found the answer myself, but perhaps just posting it will help others running into the same gotcha...

If you look at the official documentation for both versions, there's a *tiny* but all-important difference:

* v3.5 docs: `Variant get_drag_data ( Vector2 position ) virtual`
* v4.0 docs: `Variant _get_drag_data ( Vector2 at_position ) virtual const`

So **in v4.x there is an `_` (underscore) prefix to the method** that wasn't there in 3.x.

The godot engine source code even have a rename map entry for this change, presumably to help with converting projects? For reference: see the commit that introduced this change.
> 7 votes

---
Tags: gui, ui-design, godot-4, godot-3
---


# Question
Title: RPG formulas for dodge/evasion and lockpicking rolls
Im trying to figure out some way to implement a formula to calculate dodge and evasion in my game in some reliable way. The factor involved are dodge/evasion skill levels, of course, the target's dexterity and the attacker's dexterity and whatever offensive skill rules the specific attack. The idea is no matter how high the level difference, the attacker always have at least a 15-20% chance to hit and viceversa. Although the game doesnt limit levels, Im considering that average player wont be reaching more than 20-30 points in each skill or character stats, with some crazy people with no life or extreme builds reaching maybe 50 points. The second formula deals with lockpick,and Im trying to do something like Fallout 2: no matter how hard the lock was, if you try several times you had a very remote chance to open it (and also break it). Lockpick depends on Suberfuge skill and dexterity, with same estimated values (1-3x points). What can you suggest me for this?

# Answer
> 3 votes
Here's a Google Sheets document where you can play with these formulas \- see the "Diminishing Returns" tab:

You can adjust the min and max output values, as well as provide a sample input-output pair that the curve should pass through. The sheet then calculates three possible curves meeting those criteria, and plots them so you can compare their behaviour.

---

Expanding on the answer here: Sliding scale for secondary stats, we can use any of a family of functions that give diminishing returns, and just rescale them into our desired range.

Let's say we have some function `DiminishingReturn(float x)` on the interval `[0, infinity)` that has these properties:

* `DiminishingReturn(0) == 0`
* As `x` approaches infinity, `DiminishingReturn(x)` approaches 1
* `DiminishingReturn(x)` is an increasing function (`x2 > x1 ==> DiminishingReturn(x2) > DiminishingReturn(x1)`

Here are a few ways we could implement that function, corresponding to the three curves shown in the Google Sheets example above - pick whichever of the return statements looks best to you:

```
float DiminishingReturn(float x) {
    // hyperbolic
    return 1 - 1/(x + 1);

    // arc tangent
    return atan(x) * 2/PI;

    // exponential
    return 1 - exp(-x);
}

```

Then we can turn that into a stat output with a desired minimum and maximum like so:

```
float MinMaxStat(float min, float max, float input) {
    // Don't let the input drop below 0.
    input = max(0, input);

    return min + (max - min) * DiminishingReturn(input);
}

```

Now we can implement the chance to hit / pick lock like so:

```
float netAttackStat = attacker.level + attacker.dex + getAttackBonus(attacker);
netAttackStat -= defender.level + defender.dex;
float hitChance = MinMaxStat(0.15f, 1.0f, netAttackStat * 1.0f);

float netPickingStat = lockPicker.level + lockPicker.dex + lockPicker.subterfuge;
netPickingStat -= lock.difficulty;
float success = MinMaxStat(0.01f, 1.0f, netPickingStat * 1.0f);

```

So here higher levels stats by the attacking/picking player drive you rightward up the curve, while higher stats of the defender/lock drive you leftward down the curve, and the output success is always clamped between the given min and max. You can change the `* 1.0` multipliers to change the slope: how large a success chance increase you get from a small change in the input stat. The "Rate Coefficient" line in the Google Sheets doc shows the formula to calculate the appropriate multiplier to pass through a given input-output pair.

---
Tags: mathematics, game-design, game-mechanics, rpg
---


# Question
Title: Getting exceptions in Unity3d with EasyRoads3D, when attempting to create roads
After importing EasyRoads3D version 3.2.2f2 into Unity 2021.3.20f1, and trying to create a simple road, I get a lot of exceptions:

```
NullReferenceException: Object reference not set to an instance of an object
EasyRoads3Dv3Editor.ODOOCODCQO.OCCOCQDOOD (EasyRoads3Dv3.ERModularBase scr) (at :0)
EasyRoads3Dv3Editor.ODDQDODCCC.OnEnable () (at :0)
UnityEditor.PrefabUtility:CreateEmptyPrefab(String)
EasyRoads3Dv3Editor.OODCCDOQQQ:OODDDDODOC()
EasyRoads3Dv3Editor.ODDQDODCCC:OnEnable()

MissingMethodException: Method not found: UnityEngine.Vector3 UnityEditor.Handles.FreeMoveHandle(UnityEngine.Vector3,single,UnityEngine.Vector3,UnityEditor.Handles/CapFunction)
System.Reflection.RuntimeMethodInfo.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at :0)
Rethrow as TargetInvocationException: Exception has been thrown by the target of an invocation.
System.Reflection.RuntimeMethodInfo.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at :0)
System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) (at :0)
UnityEditor.SceneView.CallOnSceneGUI () (at /home/bokken/build/output/unity/unity/Editor/Mono/SceneView/SceneView.cs:3641)
UnityEditor.SceneView.HandleSelectionAndOnSceneGUI () (at /home/bokken/build/output/unity/unity/Editor/Mono/SceneView/SceneView.cs:2740)
UnityEditor.SceneView.DoOnGUI () (at /home/bokken/build/output/unity/unity/Editor/Mono/SceneView/SceneView.cs:2411)
UnityEditor.SceneView.OnSceneGUI () (at /home/bokken/build/output/unity/unity/Editor/Mono/SceneView/SceneView.cs:2255)
UnityEngine.UIElements.IMGUIContainer.DoOnGUI (UnityEngine.Event evt, UnityEngine.Matrix4x4 parentTransform, UnityEngine.Rect clippingRect, System.Boolean isComputingLayout, UnityEngine.Rect layoutSize, System.Action onGUIHandler, System.Boolean canAffectFocus) (at /home/bokken/build/output/unity/unity/ModuleOverrides/com.unity.ui/Core/IMGUIContainer.cs:351)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&) (at /home/bokken/build/output/unity/unity/Modules/IMGUI/GUIUtility.cs:189)

GUI Error: You are pushing more GUIClips than you are popping. Make sure they are balanced.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&) (at /home/bokken/build/output/unity/unity/Modules/IMGUI/GUIUtility.cs:189)

MissingMethodException: Method not found: UnityEngine.Vector3 UnityEditor.Handles.FreeMoveHandle(UnityEngine.Vector3,single,UnityEngine.Vector3,UnityEditor.Handles/CapFunction)
System.Reflection.RuntimeMethodInfo.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at :0)
Rethrow as TargetInvocationException: Exception has been thrown by the target of an invocation.
System.Reflection.RuntimeMethodInfo.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at :0)
System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) (at :0)
UnityEditor.SceneView.CallOnSceneGUI () (at /home/bokken/build/output/unity/unity/Editor/Mono/SceneView/SceneView.cs:3641)
UnityEditor.SceneView.HandleSelectionAndOnSceneGUI () (at /home/bokken/build/output/unity/unity/Editor/Mono/SceneView/SceneView.cs:2740)
UnityEditor.SceneView.DoOnGUI () (at /home/bokken/build/output/unity/unity/Editor/Mono/SceneView/SceneView.cs:2411)
UnityEditor.SceneView.OnSceneGUI () (at /home/bokken/build/output/unity/unity/Editor/Mono/SceneView/SceneView.cs:2255)
UnityEngine.UIElements.IMGUIContainer.DoOnGUI (UnityEngine.Event evt, UnityEngine.Matrix4x4 parentTransform, UnityEngine.Rect clippingRect, System.Boolean isComputingLayout, UnityEngine.Rect layoutSize, System.Action onGUIHandler, System.Boolean canAffectFocus) (at /home/bokken/build/output/unity/unity/ModuleOverrides/com.unity.ui/Core/IMGUIContainer.cs:372)
UnityEngine.UIElements.IMGUIContainer.HandleIMGUIEvent (UnityEngine.Event e, UnityEngine.Matrix4x4 worldTransform, UnityEngine.Rect clippingRect, System.Action onGUIHandler, System.Boolean canAffectFocus) (at /home/bokken/build/output/unity/unity/ModuleOverrides/com.unity.ui/Core/IMGUIContainer.cs:693)
UnityEngine.UIElements.IMGUIContainer.DoIMGUIRepaint () (at /home/bokken/build/output/unity/unity/ModuleOverrides/com.unity.ui/Core/IMGUIContainer.cs:553)
UnityEngine.UIElements.UIR.RenderChainCommand.ExecuteNonDrawMesh (UnityEngine.UIElements.UIR.DrawParams drawParams, System.Single pixelsPerPoint, System.Exception& immediateException) (at /home/bokken/build/output/unity/unity/ModuleOverrides/com.unity.ui/Core/Renderer/UIRenderer/UIRenderers.cs:129)
Rethrow as ImmediateModeException
UnityEngine.UIElements.UIR.RenderChain.Render () (at /home/bokken/build/output/unity/unity/ModuleOverrides/com.unity.ui/Core/Renderer/UIRRenderChain.cs:513)
UnityEngine.UIElements.UIRRepaintUpdater.Update () (at /home/bokken/build/output/unity/unity/ModuleOverrides/com.unity.ui/Core/Renderer/UIRRepaintUpdater.cs:79)
UnityEngine.UIElements.VisualTreeUpdater.UpdateVisualTreePhase (UnityEngine.UIElements.VisualTreeUpdatePhase phase) (at /home/bokken/build/output/unity/unity/ModuleOverrides/com.unity.ui/Core/VisualTreeUpdater.cs:155)
UnityEngine.UIElements.Panel.UpdateForRepaint () (at /home/bokken/build/output/unity/unity/ModuleOverrides/com.unity.ui/Core/Panel.cs:994)
UnityEngine.UIElements.Panel.Repaint (UnityEngine.Event e) (at /home/bokken/build/output/unity/unity/ModuleOverrides/com.unity.ui/Core/Panel.cs:1046)
UnityEngine.UIElements.UIElementsUtility.DoDispatch (UnityEngine.UIElements.BaseVisualElementPanel panel) (at /home/bokken/build/output/unity/unity/ModuleOverrides/com.unity.ui/Core/UIElementsUtility.cs:448)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr, System.Boolean& eventHandled) (at /home/bokken/build/output/unity/unity/ModuleOverrides/com.unity.ui/Core/UIElementsUtility.cs:211)
UnityEngine.UIElements.UIEventRegistration.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr) (at /home/bokken/build/output/unity/unity/ModuleOverrides/com.unity.ui/Core/UIElementsUtility.cs:74)
UnityEngine.UIElements.UIEventRegistration+<>c.b__1_2 (System.Int32 i, System.IntPtr ptr) (at /home/bokken/build/output/unity/unity/ModuleOverrides/com.unity.ui/Core/UIElementsUtility.cs:28)
UnityEngine.GUIUtility.ProcessEvent (System.Int32 instanceID, System.IntPtr nativeEventPtr, System.Boolean& result) (at /home/bokken/build/output/unity/unity/Modules/IMGUI/GUIUtility.cs:189)

```

The last couple of exceptions tend to come over and over again, as long as I have the `Road Network` object selected in the hierarchy.

Is this a bug in Unity? In EasyRoads3D? Or in my setup or because I'm using Linux on an unsupported system (Ubuntu 22.10)?

# Answer
> 1 votes
The problem is that I downloaded EasyRoads3D with a different version of Unity (IIRC 2022.2.something), and this somehow created a mismatch when importing it into a different version.

The solution was to remove the cached downloaded EasyRoads3D assets (Linux command shown):

```
$ rm -rf ~/.local/share/unity3d/Asset Store-5.x/AndaSoft

```

And then re-download it using the Unity version I want to use them in.

The cache location is found in this documentation.

For form information about removing downloaded and cached asset files, there's documentation for that as well.

---
Tags: unity, exceptions
---


# Question
Title: Calculating normals for a simplified terrain mesh
I am trying to simplify a mesh I am generating from a heightmap by creating larger triangles for areas of equal elevation, like this:

This however gives me issues with my normals:

I am calculating my normals by summing up the cross product of each face. I know this is incorrect since all my vertices no longer has "neighbours", but I cannot figure out the correct way to do this...

What am I missing? Unitys Mesh.RecalculateNormals() doesn't give correct result either.

Is there a better way of simplifying my terrain mesh? Does Unity provide a built-in alternative?

# Answer
Because the larger triangles have no vertices in the middle of their longer edges, the normals you get along those edges are just linear interpolations of the normals at each corner.

In order to match, any vertex that forms a T-junction somewhere along that long edge needs to have its normal set to the corresponding linear interpolation of the vertices at the ends of the long edge. For example:

```
|   |       |   |   |   |
A---B---C---D---E---F---G
|   |   |   |           |

```

Here, vertex C forms a T-junction with the long edge bordered by B and D, so C's normal should be a 50% blend of B and D's normals (and don't normalize it before interpolation — wait until after, in the fragment shader, to be sure it interpolates the same on both sides).

E and F both form T-junctions with the long edge between D and G, ⅓ and ⅔ of the way along, respectively. So E's normal should be `Lerp(D.normal, G.normal, 1f/3f)`, and F's normal should be `Lerp(D.normal, G.normal, 2f/3f)`

You can run into a challenge when one of the endpoints of a long edge itself forms a T-junction with another long edge:

```
|       |   |   |
H---I---J---K---L
|   |           |

```

For simplicity, in these cases I'd recommend taking every vertex participating in either long edge and setting their normals to straight up (0, 1, 0). Since your large triangles represent areas of equal elevation (ie. plateaus), an upward-facing normal is a reasonable approximation here, and guarantees that all the normals meeting at the long edges agree, without getting into complicated constraint solving (which might end up converging to the straight-up solution in pathological cases anyway, but with much higher code complexity and computational expense).
> 0 votes

---
Tags: unity, procedural-generation, terrain, 3d-meshes
---


# Question
Title: OptionButton dropdown appears behind other control nodes
I'm getting used to Godot 4.0, and I ran into an issue where the dropdown menu from OptionButton draws behind all the other control nodes (or, at the very least, those further down the scene tree).

I changed its z-index in the inspector to be higher than the other control nodes, but this didn't help. I've also rearranged the scene tree twice: first, I rearranged it so that everything was in HBox and VBox containers instead of the GridContainer, and that didn't help; and second, to place the HBoxContainer that the OptionButton node is in inside of a CanvasLayer, and this didn't change anything either.

I have suspicions about what's going on (and a really sloppy way of fixing it in mind, involving importing this scene from Godot 3.5 which does work normally). But, I'm wondering if anyone has suggestions. Thanks!

# Answer
This seems to be caused by the `Window` having set `always_on_top` to `true`, making it appear on top of every other window, including the `PopupMenu` from the `OptionButton`.

Thus your first solution is to not use `always_on_top`.

---

If you need `always_on_top`, we could hack it from script by getting the hidden `PopupMenu` and setting its `always_on_top` to match the `Window`:

```
extends OptionButton

func _ready() -> void:
    get_popup().always_on_top = get_window().always_on_top

```

---

Looking further into it took me to this issue: always\_on\_top breaks non-embedded popups, it seems to be related, although I'm getting the unexpected behavior even with `embed_subwindows` enabled in project settings.
> 2 votes

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


# Question
Title: How to detect enemies at a larger radius without expanding range where enemies can detect the player?
I had tried to enlarge the player's collider's radius so that it can detect enemies in a wider range and attack them by shooting. However, it seems like the large collider is also affecting the enemies' ability to detect the player.

How can I make a large radius for the player's remote attack, while keeping the enemies only able to detect an object the size of the player's visible model?

If I add a child object with a trigger collider to detect the attack range, is this a good solution?

# Answer
> 1 votes
Create an array of Colliders called hitColliders.

Use the Physics.OverlapSphere() method to find all the colliders within a given range from the current object's position.

Then in use foreach (Collider hitCollider in hitColliders) to detect your enemy

# Answer
> 0 votes
I am not sure if Unity already has this but you may **create mask**.

You need 2 integers:

1. int ownType ... 1 bit in integer (mask works for 32 objects = 2ˇ32).
2. int mask ... with whom object collide

On collision 1st. check if collision is valid to proceed.

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


# Question
Title: Player transform has not been assigned when player enters trigger collider?
I wrote some code so when the player falls off a platform and collides with a trigger collider called Respawn Trigger, the player's transform position is set to an empty gameObject called Respawn Point. Everything seems to work well except I get the following error each time I collide with the trigger and respawn:

UnassignedReferenceException: The variable player of PlayerRespawn has not been assigned.You probably need to assign the player variable of the PlayerRespawn script in the inspector. PlayerRespawn.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/PlayerRespawn.cs:9)

This is my script I put on my Respawn Trigger gameObject:

```
using UnityEngine;

public class PlayerRespawn : MonoBehaviour {

    [SerializeField] private Transform player;
    [SerializeField] private Transform respawnPoint;

    void OnTriggerEnter2D(Collider2D other) {
        player.transform.position = respawnPoint.localPosition;
    }
}

```

# Answer
> 1 votes
I was able to fix the issue by assigning it in code instead of in the inspector with this code:

```
public class PlayerRespawn : MonoBehaviour {

    private Transform player;
    private Transform respawnPoint;

    private void Start() {
        GameObject p = GameObject.Find("Player");
        player = p.transform;

        GameObject rp = GameObject.FindWithTag("Respawn Point");
        respawnPoint = rp.transform;
    }

    void OnTriggerEnter2D(Collider2D other) {
        player.position = respawnPoint.position;
    }
}

```

I am embarrassed to say I found the script also attached to the Player by mistake!

# Answer
> 0 votes
The error message suggests that the "player" variable has not been assigned in the inspector of the `PlayerRespawn` script.

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


# Question
Title: Consistently moving a GameObject from Point A to Point B using Unity Visual Scripting
I built a subGraph in Unity Visual Scripting to move a GameObject ("returnThisGameObject") from its current location (Point A) to its originalPosition (Point B).

The code run dozen of times a minute and usually does its job. But sometimes the GameObject doesn't move the full distance, and just stops part of the way there. The While loop in the subgraph doesn't finish in those cases, as subsequent graphs after this one do not run.

I could hack it so that the While loop only runs a certain number of frames before moving on. But I'm trying to figure out the root cause of why the While loop doesn't always work. I am not very familiar with Smooth Damp (or LERP) though, so I could use some guidance.

Any ideas why this While Loop isn't always completing?

EDIT: As suggested, I added a variable for objectVelocity and plugged it into the Smooth Damp node on both sides. Still encountering the issue where the GameObject doesn't always make it all the way to Point B...

# Answer
Just wanted to confirm once and for all that there was nothing wrong with the code above! It does successfully and consistently move a GameObject from Point A to Point B.

But when I tried to move 2 GameObjects in rapid succession.... sometimes the first GameObject would not make it all the way to its target.

Here's how I had the code structured:

* I had the movement code running in a single GameObject called "Move Manager".
* Move Manager had a Queue that stacked up the GameObjects to be moved,
* Move Manager had code would move the top GameObject from Point A to Point B... then once that was done, it would move the the next GameObject from Point A to Point B... etc.

The code worked perfectly if it only had to move one GameObject. But for some reason that I still don't understand, if two GameObjects were moved in rapid succession... sometimes the first GameObject would stop moving before it reached its target.

To solve this, I took the movement code inside of Move Manager and moved it into a Prefab for the GameObjects. As a result:

* The Move Manager could manage the queue of GameObjects (to be moved)
* And the GameObjects themselves would handle their own movement.

This solved the problem completely. I am still not sure why the movement code didn't work when it was inside Move Manager, but am just glad it's all working now.

Thanks to everyone who helped me confirm that there wasn't a problem in the movement code! This helped me isolate the problem, and ultimate figure out a workaround.
> 0 votes

---
Tags: unity, lerp
---