title: Interface object never equals null

text:
# Question
Title: Interface object never equals null
I've created an interface class for some mechanic I'm using to interact with things in my game. Now, I noticed that checking if that value is null never returns true.
Here's a screenshot of where this happens:

The error I get is the following:

```
MissingReferenceException: The object of type 'InteractiveItem' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
InteractiveItem.CurrentGameObject () (at Assets/Scripts/Interactive/InteractiveItem.cs:10)
Interactive.ManualStopInteract () (at Assets/Scripts/Interactive/Interactive.cs:30)

```

The line where this fails is:

```
if (IsInteracting() && this.interacting.CurrentGameObject().GetComponent<InteractiveUtilityChest>() == null && !MainReferences.UIReferences.IsAnyMenuWindowOpen()) {
        // do something
}

```

The `IsInteracting()` check is for some reason returning true here because the last line (InteractiveItem.cs:10) is in the method `interacting.CurrentGameObject()`

I don't get how this can happen or how I should solve it. As far as I know, an interface is a nullable type.

# Answer
I have a hypothesis for what might be causing this...

First, I need to explain something about `null` in Unity: when an instance descended from `UnityEngine.Object` (including `GameObject` or `MonoBehaviour`) gets `Destroy()`ed, it does not actually become `null`.

(In C#, a variable will only hold a value of `null` if it's uninitialized, or if it's been assigned `myVariable = null` explicitly - nothing can delete the object out from under you as long as any active script holds a reference to it)

Once the `Destroy()` takes effect at the end of the current frame's updates (before rendering), references to the instance will *compare as equal to* `null`, because Unity overloads the `==` operator for `UnityEngine.Object`. But the reference is still non-null. Try this example:

```
IEnumerator NullTest()
{
    var myObject = new GameObject();
    Destroy(myObject);

    Debug.Log("Is it null immediately?"
             + (myObject == null));                             // false

    yield return null; // Wait one frame for Destroy() to take effect

    Debug.Log("NOW is it null? "
              + (myObject == null));                            // true

    Debug.Log("But is it *really* null? "
              + System.Object.ReferenceEquals(myObject, null)); // false
}

```

This "pseudo-null" stub is what lets Unity understand what you were trying to do and give you a tailored error message:

> MissingReferenceException: The object of type 'InteractiveItem' has been destroyed but you are still trying to access it.

All real `null` values look alike, so if it was a real `null` Unity wouldn't be able to tell it came from a destroyed object.

Okay, so with that background, why is your code giving this confusing result?

Without seeing more of your code it's hard to say for sure, but I have a suspicion that you're implementing this interface on a `MonoBehaviour`, and **your `null` check doesn't know it's working with a class descended from `UnityEngine.Object`** \- all it knows is that it implements the `InteractiveItem` interface.

So this line:

```
return interacting != null;

```

is using the standard comparison, like `System.Object.ReferenceEquals()`. That replies "Well, no, it's been `Destroy`()ed, but it's not *literally* null" so `IsInteracting()` returns true.

Then your code proceeds and tries to call

```
this.interacting.CurrentGameObject()

```

and Unity steps in to say "Why are you trying to access a member of a `Destroy()`ed `MonoBehaviour`?" and throws an error.

So, some possible fixes...

* Make `InteractiveItem` descend from `MonoBehaviour` if everything
implementing it is going to be a `MonoBehaviour` anyway, so the
correct comparison is used automatically.
* Try casting `interacting` to (something descended from...)
`UnityEngine.Object` before checking for `null` to catch when it's
been `Destroy()`ed.
* Make your interactive objects aware that someone is trying to
interact with them, and use an `OnDestroy` method to notify the
interactor when the interaction is no longer available.
> 9 votes

# Answer
I ran into this same problem while working with a list of interfaces and ended up figuring out a different solution.

Instead of

```
if( InterfaceToGameObject == null )

```

I used

```
if( InterfaceToGameObject.Equals(null) )

```

Worked like a charm.
> 1 votes

# Answer
To add to what DMGregory wrote, you can use this to check interfaces for unity's "null" objects (taken from Unity.VisualScripting):

```
    public static bool IsUnityNull(this object obj)
    {
        // Checks whether an object is null or Unity pseudo-null
        // without having to cast to UnityEngine.Object manually

        return obj == null || ((obj is UnityObject) && ((UnityObject)obj) == null);
    }

```
> 1 votes

# Answer
Without seeing the rest of the code, my guess is that your variable interacting was never instantiated after it was declared.

if it was a member variable (not sure of your coding experience). It would be the same as doing something like this.

```
private MyClass obj;

```

if(obj != null) { //this code would never run because object wasn't initialized }

This would be fixed by changing your code to create an object, rather than just declaring the type for the variable.

```
private MyClass obj = new MyClass();

```

Now there is an object created and can be manipulated.

If that is not the case, are you writing specific logic in your interface, or a concrete class that extends/implements the interface?
> -2 votes

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


# Question
Title: Avoid certain parts being modulated by CanvasModulate in Godot 4.1
I'd followed a tutorial on how to make a day and night cycle in Godot 4.1. Basically it consists on a `CanvasModulate` node that changes color based on a gradient that imitates the different kinds of light color during the day and a `sin()` function. So far so good.

The problem is that my generic `Enemy` class has a `Label` hidden on top of it that shows the damage received when they are hit. **This label is also getting modulated by the night and day cycle, and it shouldn't.**

I've tried playing with the `Z_index` of both, `Label` and `CanvasModulate`, but it doesn't seem to work as I expected: **everything gets modulated no matter the index.**

I've also tried to put in this label as a child of a `CanvasLayer`, and this as a child of the `Enemy` class, which works fine for the modulation aspect, but **the label gets rendered in a corner**, or in the middle if I enable `follow_viewport_enabled`. Also I get a bunch of errors about "*... was modified from inside an instance, but it has vanished*" when I instance `Enemy` subclasses.

Maybe my design is flawed and those labels belong to the GUI (which works fine because it's in its own `CanvasLayer` and doesn't "move"), although I find it more intuitive to be children of the enemy, so I don't need to pass positions from the game to the GUI and create new labels when enemies get hit.

Any words of wisdom would be appreciated.

# Answer
> 0 votes
As the author of the tutorial told me, one way to avoid the modulation is adding a `CanvasItemMaterial` in the `Label`. In this `Material`, set the `Light Mode` to `Unshaded`. This works nice in my project.

# Answer
> 3 votes
If the `Label` is temporary, then passing the position - as you have been trying to avoid - is the best solution.

If it must stay with the `Enemy`, and it is a `Node2D`... You could make the `Label` a child of another `Node2D` (somewhere it is unaffected) and use a `RemoteTransform2D`.

Another option - which I find simpler - is to make a `Control` with a script that lets me specify the `Node` it must follow, and then it can read its position in `_process` and position itself accordingly. Then the `Label` or whatever you need to display (e.g. a `ProgressBar`) can be a child of said `Control`.

*For this you might have to convert the position from the game world to the window, which I believe is `get_global_transform_with_canvas`.*

---
Tags: rendering, godot-4
---


# Question
Title: What is the recommended way of storing large sets of organized, immutable data in Unity?
Since I'm making an RPG in Unity, I need a place to store all the possible moves/attacks in the game. These have the following properties:

* there will be a very large number of them, in the hundreds perhaps;
* apart from the natural tweaking process during development, they will remain unchanged forever: they're read-only data;
* they must be easily accessible and sortable whenever and wherever I want.

Initially I thought I would solve this problem very easily by creating a simple `Move` class with the relevant attributes (damage dealt, range, etc.), and then I would create a second file, possibly a `ScriptableObject`, which declares a global empty list of `Move` elements. I would then move onto the Inspector, which has a very nice UI, to quickly fill in the list by repeatedly clicking on ‘+’ and filling in the various attribute fields by hand.

However, I soon ran into an unexpected problem: the Inspector usually updates the list whenever the `Move` class is changed (e.g. if I add an attribute, it will be automatically added to all elements with a default value); but there are some circumstances, like if the script is temporarily unable to be compiled due to a mistype or another similar error, where the changes aren't backward compatible anymore, and so, after fixing the issue, **the list in the Inspector will become empty.** Since the elements were created from there and are nowhere to be found in the code, they are effectively lost forever; and there will be hundreds of these moves, so I can't afford losing them so easily.

So I thought that I should initialize the list directly in the code, but naturally C# won't allow me to: the script should only define the class and not initialize an instance of it, so if I try to give the list some elements, I get an error; and if I put the initializing part within `Start()` or `Awake()`, that part of the code just won't run and the list in the Inspector will still be empty unless I fill it in from the Inspector itself.

At this point I'm thinking of rather extreme solutions like writing a JSON file to hold all the information and have a script somehow read them from there when needed, but ***surely*** there is a better way to deal with this type of data in Unity, right?

# Answer
> 6 votes
My preferred workflow here is to author the move data in a spreadsheet, then write an importer script in Unity that reads the spreadsheet and creates or updates a `ScriptableObject` instance for each move in the list.

That way I can make bulk edits and analyses of the balance of the set of moves as a whole in the spreadsheet tool, and then update the in-game versions with one click.

This does lead to a lot of asset files, but if you just dump them into their own subfolder then they don't clutter your workflows. Most common edits can be made through the spreadsheet, so you usually only have to touch the individual files for data that's less convenient to author in spreadsheet form (like references to image/effect assets in your project).

To organize them into lists/categories, I'll have another `ScriptableObject` that contains a list of references to the individual assets, also automatically updated by the import script. Then my game code can reference those index objects to always have an up-to-date collection of all the current moves/etc.

Having each entry as a separate asset makes it easier for version control and working in parallel as a large team, as well as avoiding/isolating data loss in cases like you describe. It also lets you make multiple versions of a move that all exist simultaneously in your data, and switch between them as you try out which variant you like, without having to re-create the data each time you want to try another variant.

I do this as an exercise with my students, having them design battling monsters and their moves, or ingredients and recipes for a crafting system, and working through the steps of writing the importer.

It's a bit involved to fit in a StackExchange answer in its entirety, but I usually use the EPPlus library (an older, more permissibly licensed free version) which can read and even write to Excel .xlsx files. This and the source spreadsheet can go in an Editor folder so it doesn't bloat your game build. You could do something equivalent with CSV, though you lose the convenience of things like named ranges, conditional formatting, formulas, and charts. I'd bet you could make it work with a Google Sheets or LibreOffice Calc document if you prefer free/non-Microsoft alternatives.

# Answer
> 4 votes
You might be able to solve this by turning `Move` into a scriptable object as well. Those are much more stable in case of changes than POCOs in a serialized array of a MonoBehaviour or ScriptableObject. They certainly won't just get deleted by the engine on a whim, because each move is an asset file in the filesystem.

One possible way how you could lose data about your existing moves is if you would rename fields in the Move class. If you find yourself in a situation where you have to do that, then take a look at the `[FormerlySerializedAs]` attribute. It can help with migrating existing SOs to a new format. Retaining the data through more complex refactorings might require a bit of editor scripting to transform and copy the values from old fields to new ones, but that's usually a solvable problem.

If the purpose of the referencing behavior or SO is just to keep the references to the moves somewhere so they end up in the game build in a way that the game code can find them, then you might want to consider using the optional Addressables package instead. Those allow you to give each Move a unique string identifier that can be used to load it at runtime. So you no longer need a "data-holder" object for them. You can also load your complete catalog of moves at once by giving each move asset the same Label and then load them all with `Addressables.LoadAssetsAsync`.

---
Tags: unity, architecture, rpg, data-structure
---


# Question
Title: Why doesn't the fire appear when moving code to a function?
This is my code:

```
import pygame
import os
import time
pygame.font.init()
import random

clock = pygame.time.Clock()
timez = 0
time_count = 1000
WIDTH, HEIGHT = 1300, 800
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("mortal kombat")
YELLOW = (255,255,0)
vel = 5
BG = pygame.transform.scale(pygame.image.load("mortal kombat/mk 11 dragon grotto.jpg"),(WIDTH,HEIGHT))
fireball_image = pygame.transform.scale(pygame.image.load("mortal kombat/Explosion-Fireball-PNG.png"),(100,100))
Fire_vel = 5
Fire_list = []
Max_fire = 6
HIT = pygame.USEREVENT + 1
def draw(Fire_list):
    WIN.blit(BG,(0,0))
    WIN.blit(Liu_Kang_Character,(LK_rect.x,LK_rect.y))

    for fire in Fire_list:
           pygame.draw.rect(WIN,(255,255,0),fire)

           fire__y = fire.y
           WIN.blit(fireball_image,(fire.x-15,fire__y-45))

    pygame.display.update()

def pressing_keys(keys_pressed,LK):
    if keys_pressed[pygame.K_a] and LK.x >0:
           LK.x -= 8
    if keys_pressed[pygame.K_d] and LK.x < WIDTH - 250:
           LK.x += 8
    if keys_pressed[pygame.K_w] and LK.y > 0 :
           LK.y -= 8
    if keys_pressed[pygame.K_s] and LK.y < HEIGHT - 375:
           LK.y += 8

def handle_fire(Fire_list):
     for fire in Fire_list:
            fire.x -= Fire_vel

            ############
            timez += clock.tick(60)

            if timez >= time_count:
                 fire_y = random.randint(0,800)
                 fire = pygame.Rect(1200,fire_y,15,15)

                 Fire_list.append(fire)
                 timez = 0

            if fire.x < 0:
                   Fire_list.remove(fire)

            ##############

            if LK_rect.colliderect(fire):
                pygame.event.post(pygame.event.Event(HIT))
                Fire_list.remove(fire)

#liu kang
Liu_Kang_size = (50,50)

Liu_Kang_image= pygame.image.load(os.path.join('mortal kombat','Liu Kang-PNG-File.png'))
Liu_Kang_Character = pygame.transform.scale(Liu_Kang_image,(250,375))
LK_rect = pygame.Rect(100,300,250,375)

run = True

while run:

    draw(Fire_list)

    keys_pressed = pygame.key.get_pressed()
    pressing_keys(keys_pressed,LK_rect)

    for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                break

    print(Fire_list)

    handle_fire(Fire_list)

pygame.quit()

```

Somehow fire rects don't appear. But when the code is like this:

```
import pygame
import os
import time
pygame.font.init()
import random

clock = pygame.time.Clock()
timez = 0
time_count = 1000
WIDTH, HEIGHT = 1300, 800
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("mortal kombat")
YELLOW = (255,255,0)
vel = 5
BG = pygame.transform.scale(pygame.image.load("mortal kombat/mk 11 dragon grotto.jpg"),(WIDTH,HEIGHT))
fireball_image = pygame.transform.scale(pygame.image.load("mortal kombat/Explosion-Fireball-PNG.png"),(100,100))
Fire_vel = 5
Fire_list = []
Max_fire = 6
HIT = pygame.USEREVENT + 1
def draw(Fire_list):
    WIN.blit(BG,(0,0))
    WIN.blit(Liu_Kang_Character,(LK_rect.x,LK_rect.y))

    for fire in Fire_list:
           pygame.draw.rect(WIN,(255,255,0),fire)

           fire__y = fire.y
           WIN.blit(fireball_image,(fire.x-15,fire__y-45))

    pygame.display.update()

def pressing_keys(keys_pressed,LK):
    if keys_pressed[pygame.K_a] and LK.x >0:
           LK.x -= 8
    if keys_pressed[pygame.K_d] and LK.x < WIDTH - 250:
           LK.x += 8
    if keys_pressed[pygame.K_w] and LK.y > 0 :
           LK.y -= 8
    if keys_pressed[pygame.K_s] and LK.y < HEIGHT - 375:
           LK.y += 8

def handle_fire(Fire_list):
     for fire in Fire_list:
            fire.x -= Fire_vel

            if fire.x < 0:
                   Fire_list.remove(fire)

            if LK_rect.colliderect(fire):
                pygame.event.post(pygame.event.Event(HIT))
                Fire_list.remove(fire)

#liu kang
Liu_Kang_size = (50,50)

Liu_Kang_image= pygame.image.load(os.path.join('mortal kombat','Liu Kang-PNG-File.png'))
Liu_Kang_Character = pygame.transform.scale(Liu_Kang_image,(250,375))
LK_rect = pygame.Rect(100,300,250,375)

run = True

while run:

    draw(Fire_list)

    keys_pressed = pygame.key.get_pressed()
    pressing_keys(keys_pressed,LK_rect)

    for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                break
    ##########
    timez += clock.tick(60)

    if timez >= time_count:
                 fire_y = random.randint(0,800)
                 fire = pygame.Rect(1200,fire_y,15,15)

                 Fire_list.append(fire)
                 timez = 0

    ##########

    print(Fire_list)

    handle_fire(Fire_list)

pygame.quit()

```

...then the fire images appear.

I'm wondering why when I shift it to the function it doesn't appear anymore, while if it's inside the while loop, it does, since the function is called in the while loop anyway.

For easy reference I've marked the area ive changed with ####. All I did was switch around the places.

# Answer
# Fire\_list is empty

My first clue was that in the first (non-functional) code, you have `timez += clock.tick(60)` inside the foreach loop. This seemed weird to me because usually you only want to increment time once per frame, not once per fire per frame.

This turned out not to be the root cause, but it got me thinking, "How many times per frame is this running?"

In the working example, the following code runs exactly once per frame:

```
if timez >= time_count:
    fire_y = random.randint(0,800)
    fire = pygame.Rect(1200,fire_y,15,15)

    Fire_list.append(fire)
    timez = 0

```

In the non-working example, that code runs once *per fire* per frame. If there are zero fires, it will never be run. Because it is never run, fire never gets appended to the list, so the list remains empty.
> 2 votes

---
Tags: python, pygame
---


# Question
Title: Unity: How to draw 2D lines directly on a UI canvas?
The title pretty much tells my issue. I want to simply draw a few lines from a script controlled by start- and endpoint coordinates directly on the UI canvas (so the lines will move at runtime). From what I could read up so far, there are these options:

**LineRenderer:**

Works in 3D space. Since I want this on the UI it seems a bit overkill and also to performance hungry for such a simple task. Further, I will have to add a virtual camera and calculate the positions in 3D space (no problems with that part). My data model represents the positions in 2D Pixel coordinates, it would be quite a lot simpler to directly use those coordinates to place the lines on the screen.

**GL.Line():**

Also works in 3D space, furthermore there is no freedom in terms of line thickness.

**Asset Store:**

I tried out a ui-extension package briefly, however it left me with several warnings not connected to the actual functions I used. However if someone knows a lightweight asset, I'm happy to test!

It kind of baffles me that there is nothing provided in Unity for something seemingly so easy. Or am I missing something fundamental here?

# Answer
> 1 votes
If it is still relevant, here is a nice tutorial that can show you how to draw a line: https://youtu.be/--LB7URk60A?t=321

Small note that he didn't mention, none of this will work if you don't have a canvas renderer component present on the same gameobject BEFORE you add a Graphic component. You can add a `[RequireComponent(typeof(CanvasRenderer))]` To make sure you always have one before your Graphic script is added.

---
Tags: unity
---


# Question
Title: Godot Velocity: Invalid type in utility function "lerp", cannot convert arg 2 from Vector2 to float on line 40
I'm trying to solve a lerp problem on my velocity, searched some stuff here and there, but found nothing that solved it. Can you help me?

```
extends CharacterBody2D

@export_category("Variables")
@export var _movespeed: float = 64.0
@export var _acceleration: float = 0.4 #Atraso na aceleração do personagem
@export var _friction: float = 0.8 #Desaceleração mais rápida

func _physics_process(delta: float) -> void:
    _move()
    move_and_slide()

func _move() -> void:
    var _direction:Vector2 = Vector2(
        Input.get_axis("move_left", "move_right"),
        Input.get_axis("move_up", "move_down")
    )

    print(_direction)

    if _direction != Vector2.ZERO:
        velocity.x = lerp(velocity.x, (_direction.normalized() * _movespeed), _acceleration)
        velocity.y = lerp(velocity.y, (_direction.normalized() * _movespeed), _acceleration)
        return

    velocity.x = lerp(velocity.x, (_direction.normalized() * _movespeed), _friction)
    velocity.y = lerp(velocity.y, (_direction.normalized() * _movespeed), _friction)

    velocity = (_direction.normalized() * _movespeed)

```

# Answer
You're trying to lerp between a float (velocity.x) and a Vector2 (\_direction). Try accessing the x and y params of the \_direction Vector2 for lerping:

```
func _move() -> void:
    if _direction != Vector2.ZERO:
        velocity.x = lerp(velocity.x, (_direction.normalized().x * _movespeed), _acceleration)
        velocity.y = lerp(velocity.y, (_direction.normalized().y * _movespeed), _acceleration)
        return

    velocity.x = lerp(velocity.x, (_direction.normalized().x * _movespeed), _friction) # Normalizing a ZERO Vector2?
    velocity.y = lerp(velocity.y, (_direction.normalized().y * _movespeed), _friction) # Normalizing a ZERO Vector2?

    velocity = (_direction.normalized() * _movespeed) # Normalizing a ZERO Vector2? + Overwrites previous changes to the velocity?

```

the Code below the return statement seems to be incorrect aswell as you're trying to normalize the \_direction Vector2 which is a Vector2.ZERO at this point. I'm not sure how Godot handles that.
> 5 votes

---
Tags: vector, lerp, floating-point, godot-4
---


# Question
Title: What are the things that only a large group of devs (like 30+) can make possible? Can a game still have the same quality with a small team?
I just played Ori and found out the dev team was 25+ ppl(actually it was even more than that). I guess if it was just 5 people the game wouldnt last 15+ hours but is there anything else about the quality of the game that is only thanks to having like 25-30 devs? Or even 100+ devs for other games? Thank you in advance for the answers! I really have no idea about game dev.

# Answer
I think it could be possible to get you an idea of taking a look at a game that took a really large team and look at where all the work-hours went. Let's take Cyberpunk 2077, for example. The credits list 3,169 (!) people. What did all these people do?

* Let's start with the actual main protagonist of the game: The city! It is huge. All the buildings are unique. Lots and lots of areas are created in painstaking detail. Every unique building, every type of object in the streets, every texture needs to be modeled and textured. Every area has *multiple* different lighting designs for different times of day. All of that was created manually, by humans.
* The story characters. The game features a ton of unique characters that appear in the story. Each of them needs an unique body and an unique face. Each of them needs unique clothes and accessories to be modeled. Each of them needs a voice actor to record their lines.
* The background characters. All those nameless pedestrians, bar patrons, car drivers and shopkeepers? And all those guards and gang members that are there just so you can shoot them? Someone needs to create those too. Yes, most of them are procedurally generated from a pool of character parts. But someone has to create all those character parts.
* The story cutscenes. Someone has to write them. Someone has to script the actions the NPCs perform during these cutscenes. Someone has to do the filmography of the cameras. And NPCs are going to perform actions during those scenes they don't perform during the actual game, so those actions need to be manually animated by someone. There are basically two ways to create game animations. You can hire another human actor to do motion capture and digitize it. Or you can hire another animator to manually position the characters joints. Quite often you do both: Use Mocap as a base and then have an animator correct the details.
* The vehicles. There are a hundred different cars and motorbikes in the game. Most of them with really detailed interiors and exteriors. Also a ton of work to model and texturize.
* Clothes. The game has a myriad of clothing option. Every piece of clothing must be modeled, textured and rigged for animation.
* Weapons and other gadgets. Everything the player-character can carry needs a detailed 3d model with unique animations.
* Mission design. Every mission has to be designed, tested and then redesigned several times. The redesign often requires to go back to the artists to create or change art assets. Here is a presentation from the annual Game Developer Conference that goes into how much work goes into designing every single mission.
* Gameplay programming. A game like that has a ton of physics, mechanics, AI and other behaviors that require lots and lots of programming.
* Engine programming. The game has a custom rendering engine. Creating a rendering engine in this day and age is a ton of work too. Getting anything at all to show up on the screen is already a challenge for most programmers. But the engine of this game really does a lot. It ticks a lot of boxes when it comes to utilizing the bleeding edge of rendering technology. And all that while being able to work with a huge and detailed world that can be traversed without visible borders or loading screens. Keeping that all in memory is impossible, so it needs to be capable of loading and unloading geometry in real-time. This is really advanced stuff that requires a lot of programmer hours to get working.
* Music. The game has 11 **hours** of soundtrack with 177 different tracks across several musical genres. Some music might be licensed, but most of it was created specifically for the game. All that music doesn't compose, arrange and master itself.
* ...and I could go on with lots and lots of other things.

**tl;dr:** Making games is a lot of hard work from a lot of professionals with all kinds of different areas of expertise.
> 1 votes

# Answer
There is no valid answer to the question you're asking.

You would have to define what a dev does. Are we talking exclusively about *programmers*? Or those 30 devs are actually programmers, artists, designers, testers, IT staff, managers, accountants, marketing and the person answering calls and welcoming visitors at the front desk? If they're only *programmers*, we need to assume there are other folks working on that game, and the size of the rest of the team may vary a lot based on the type of game developed (as it's been mentioned in the comments).

And then you need to take into consideration what those devs *are*, what kind of experience do they have? The velocity of a team composed of experience devs where the communication, team spirit and goal is good will likely be much different compared to the velocity of a team of folks fresh out of school where everyone wants to pull the design in their own direction and where some key process are just unknown to them.

Then you need to consider how deep the studio's pockets are, which will influence how long the team has to produce the game.
> 0 votes

---
Tags: teamwork
---


# Question
Title: Godot 4 games exiting with "Orphan StringName" messages for production builds
I found some behavior in my own Godot 4 game which is easy to reproduce:

1. Open Godot 4.1, I'm using Windows 10, 64bit
2. Create a new project, I called it `OrphanStringTest001`
3. Add a scene with an empty `Control` node
4. Run once to make that scene the default
5. Export the project for "Windows Desktop (Runnable)" with all default options, choose "Export Project..."
6. **Disable "Export With Debug" checkbox** (this step is crucial)
7. Run from your terminal with an argument: `.\OrphanStringTest001.exe --verbose`

After closing the app:

* **Result:** tons of `Orphan Stringname: ...` messages
* **Expected:** clean exit without any such warnings

Here's the full log (abbreviated the list of "Orphan" messages though), first on startup:

```
Godot Engine v4.1.stable.official.970459615 - https://godotengine.org
TextServer: Added interface "Dummy"
TextServer: Added interface "ICU / HarfBuzz / Graphite (Built-in)"
NVAPI: Init OK!
NVAPI: Disabled OpenGL threaded optimization successfully
Using "winink" pen tablet driver...
Shader 'CanvasSdfShaderGLES3' SHA256: 72cda41890bce2f09217c172023d31e735a3fee605bad83c8e63f1a981a36a77
Shader 'SkeletonShaderGLES3' SHA256: add3f03e6eebdffdf0073fae42195857307eddada333b82998642329511917a2
Shader 'ParticlesShaderGLES3' SHA256: 9bf432d37b0b4792d67aa9f577258845d4047e3f98e990aeca6fd20a868c4db2
Shader 'ParticlesCopyShaderGLES3' SHA256: c778843b0cd1c7ce4c621fa2b924f703ac4001faef0555114b81a76c264a6908
Shader 'CopyShaderGLES3' SHA256: b1bc5a355ed9bda23f291956f121e0535b4e81b54cdac398412d200e6133161f
Shader 'CanvasShaderGLES3' SHA256: 007cddfcf35f7d57b219cffec53f6a7d9fe7a1979be4db64c6450cfac6000053
Shader 'CanvasOcclusionShaderGLES3' SHA256: 968915a469db9a7d505be274e8060c8288c15a5865baeb8362b3b0e2cacb16f3
Shader 'SceneShaderGLES3' SHA256: 7757391c487ac94cfa6418166bd5fdacce470f09394c1a2a875e878c8c5d8596
Shader 'SkyShaderGLES3' SHA256: 1fe105946e63973aecf5198091930c2bdb17778012ef0253e325ade3a297e6c8
Shader 'CubemapFilterShaderGLES3' SHA256: 2b651c285a02b7d4221af1827e1613c03e73e600ebc40b9e6a0b22bb855bd75f
OpenGL API 3.3.0 NVIDIA 528.49 - Compatibility - Using Device: NVIDIA - NVIDIA GeForce GTX 1080
WASAPI: Activated output_device using IAudioClient3 interface
WASAPI: wFormatTag = 65534
WASAPI: nChannels = 2
WASAPI: nSamplesPerSec = 48000
WASAPI: nAvgBytesPerSec = 384000
WASAPI: nBlockAlign = 8
WASAPI: wBitsPerSample = 32
WASAPI: cbSize = 22
WASAPI: mix_rate = 48000
WASAPI: fundamental_period_frames = 480
WASAPI: min_period_frames = 480
WASAPI: max_period_frames = 480
WASAPI: selected a period frame size of 480
WASAPI: detected 2 channels
WASAPI: audio buffer frames: 480 calculated latency: 10ms

TextServer: Primary interface set to: "ICU / HarfBuzz / Graphite (Built-in)".
CORE API HASH: 0
EDITOR API HASH: 0
Loaded system CA certificates

```

And after exiting the "game" it adds:

```
XR: Clearing primary interface
XR: Removed interfaceNative mobile
XR: Removed interfaceOpenXR
Orphan StringName: variant_booleanize
Orphan StringName: string_new_with_utf8_chars_and_len
Orphan StringName: OP_MODULE
Orphan StringName: KEY_SYSREQ
Orphan StringName: file_access_store_buffer
Orphan StringName: PROPERTY_HINT_NONE

    <<<< ABBREVIATED >>>>

Orphan StringName: string_to_latin1_chars
Orphan StringName: KEY_PERCENT
Orphan StringName: Key
Orphan StringName: KEY_BRACELEFT
Orphan StringName: PROPERTY_HINT_PLACEHOLDER_TEXT
StringName: 658 unclaimed string names at exit.

```

This seems like a problem, and my "real" game has nearly 4000 of those "unclaimed string names" at exit. Then again, since this happens in an empty project with default settings, it might just be "normal" and expected behavior?

My questions: what do these log messages mean, should I worry about them, and if so, how should I fix this?

# Answer
> 5 votes
The issue you're describing can be found on the Godot GitHub here, created February 2023 and still open per the time of asking your question. It seems like it is a regression in the engine that is still being investigated. I wouldn't worry for now unless you are exporting your games with a console, where the amount of text dumped may lengthen your shutdown time considerably.

---
Tags: godot-4
---


title: Networking Fire Rate And Shooting

text:
# Question
Title: Networking Fire Rate And Shooting
**Context:** This is for a multi-player shooting game. It's coded in TypeScript however this question is moreso a netcode/theoretical question rather than a question regarding implementation.

My game currently employs client side prediction to give an "lag-free" experience. We use a home-grown reliable (but unordered) UDP for data packet transmission. Each client sends the server their inputs and only their inputs, and the server then returns them with any data needed regarding the game state.

**Problem:**

In client-side prediction, there are various things that cannot be predicted, one thing being shooting (we can calculate a person's position based on their current inputs but we can't magically predict when they will click their mouse.)

**Approach 1:**

* When a client presses their button, we transmit them sending a mouse click to the server including a timestamp as to when that mouse was clicked.
* On the client side, we begin rendering bullets immediately.
* On the server side, we begin creating bullet entities and emitting these new entities to the other connected clients.
* With the mouse click and time of when that mouse clicked and the current position of the player at that time, we can easily figure out where a bullet will be at any given moment, and henceforth, we're able to compensate for this lack of ability to predict.

To kind of visualize this better: If we're in a 0 ping world, our bullets will spawn directly at the tip of a gun barrel. In our current world, instead, they'll be spawning several pixels away from that gun barrel, and the distance away from the barrel is effected by RTT.

Now this works for pressing a button, but what about letting go?

We need to wait for the client to send the server the data packet indicating that they just let go their mouse. Let's say this data packet takes a minute to get from the client to the server, by the time that happens, the server believes that they completely emptied their mag while the client let go their firing button a minute ago.

This is clearly a problem. Network spikes, bandwidth issues, etc., can create a discrepancy regarding how a client vs server understands how this shooting happened.

**Approach 2:**

Instead of sending inputs, why don't we send the bullets the player spawned in to the server? (There's potential security flaws to this, but for now we'll ignore it and say we're able to validate things on the server side.)

The next issue becomes if a player has really spotty internet connection, their bullets can be sent in all different kinds of rates such that on a receiving end, even if they were holding down their mouse button, their bullets fire-rate would be jittery and not consistent.

**Question:**

I feel like this problem is a solved problem, since this is a fundamental aspect to any shooting game for the past several decades. And so I wish to clarify: How would you go about networking the event of shooting such that we are able to account for various networking edge cases? What are things that need to be sacrificed to achieve this sort of idealized gameplay?

Thanks a bunch for reading through this!

# Answer
I've never encountered a situation in a shooter where lag caused me to fire more/fewer bullets, or where there was rubberband-y behavior around how many bullets I had left. This leads me to think that shooting isn't treated like movement (input pressed/input released messages).

Instead of a "mouse pressed" and "mouse released" message, it's more likely handled through a series of "shot fired" messages. Because these games have lag compensation, they avoid the issue in your approach #2. A client can say "I fired a bullet on tick X with position Y and rotation Z", and the server will roll back to tick X to see if that bullet hit anything.
> 0 votes

# Answer
If you have any kind of prioritization system shooting should be near the top of it.

> instead, they'll be spawning several pixels away from that gun barrel, and the distance away from the barrel is effected by RTT.

Yes this is fine. You can hide some of this in animations like:

* spin-up time on the weapon (maybe a couple ms)
* recoil + muzzle flash: Even though the muzzle flash might only last a few ms, it's bright enough and disorienting to your vision that you'll have to re-track where the bullet might be. Coupled with the recoil (deterministic recoil) you have more time to make sure you put your bullets in the right place without the user noticing.

As @Archduke said, shooting is not movement. You can trigger your "shot fired" event at your rate of fire. It's ok to penalize the shooter for being laggy, it's not ok to penalize the other players by over-spawning bullets.
> 0 votes

---
Tags: networking, first-person-shooter
---


# Question
Title: Remove StaticMesh via debug console in ue4
How do I in game dev build debug console:

* list scene meshes
* remove exact mesh causing perfomance hit?

tried:

ue 4.25

# Answer
```
getall actor
destroyall <actor_name_or_class>

```
> 0 votes

---
Tags: unreal-4, debugging
---


# Question
Title: How to change uwidget alignment on/after construction?
Have no idea how to align/realign uwidgets via c++. I have a following widget structure: UButton-\>UOverlay-\>UImage. Have to make UOverlay to HFill and VFill the UButton

# Answer
> 0 votes
Figured out the solution. Add child returns a panel slot, which we can then cast to a button slot and use it to set alignment.

Edit: This solution crashes the engine. Still can't figure out why

# Answer
> 0 votes
You can use a `SizeBox` element as holder of your widget .

Then you can add your widget as a child, cast returned slot to `SizeBoxSlot` and then use `SetAlignment` functions.  It works for me.

---
Tags: c++, unreal-4, unreal
---


title: circular camera, simplest way?

text:
# Question
Title: circular camera, simplest way?
i have a minimap, inside a viewport inside a viewport container, everything folows the player, the player is at the center, the camera doesn't rotate with the player it rotates with the mouse, so looking at a cliff will not only rotate the primary camera to view the cliff but will also rotatethe minimap camera towards the cliff, this regardless of player direction.

so even if a player is facing backwards, if the camera is looking on the other way, so will the minimap too ...

but

it is square... i don't like it.

i need a round minimap like in shooter games.

i have no idea where to start.

# Answer
Using shaders, you can cut off the corners of your rectangular map, making it a circle:

```
shader_type canvas_item;
void fragment(){
    COLOR = texture(TEXTURE, UV);
    // make the pixel completely transparent
    // if it's outside the radius of the circle
    COLOR.a = 1.0 - round(distance(UV, vec2(0.5, 0.5)));
}

```

Apply a ShaderMaterial with that code to the UI node that displays the map. If your map is made of multiple, complex UI elements, you may need to wrap them in their own Viewport and use a TextureRect with a ViewportTexture (then apply the shader to the TextureRect). Below is an example of having a "Map" TextureRect that displays a ViewportTexture targeting the "MapViewport" viewport.

Before shader:

After shader:
> 3 votes

---
Tags: godot-3, minimap
---


# Question
Title: DOS VGA card vertical sync - how to check for blanking interval?
I'm right now developing a game for ms dos in C++ (compiler: DJGPP) and need to test if the VGA card is currently in the vertical blanking interval. Is there a memory address I can just read? How can I check for this?

# Answer
> 3 votes
It's been a while since I've done it, but here's a summary Iof the method I learned from André LaMothe's *Black Art of 3D Game Programming*:

You can write an interrupt service routine (ISR) that triggers when the Vblank interrupt fires. The Vblank interrupt is `0x0A` and typically reserved for IRQ 2. Back when I learned about it, it was a bit of a gamble as not all VGA handled this the same way. I'll stick to the bit settings that I learned at the time, but it's possible you may need to do some additional digging and tweaking depending on the manufacturer. Most of the time this means they clear on a 1 instead of a 0, etc.

To enable the Vblank interrupt:

* Install an interrupt handler at `0x0A`
* Enable the interrupt on the PIC. Usually this means clearing bit `d2` of the PIC IMR (interrupt mask register).
* Clear the vertical blank interrupt latch and the vertical blank interrupt enable bits (`d4` and `d5` respectively) in the Vertical Retrace End Register located at `0x11` of the CRT controller.

It's possible that other devices may generate interrupts on IRQ, so the ISR needs to first ensure that it's responding to actual VBlank interrupts and not something else. This can be done by checking bit `d7` of the VGAs input status register 0 at port `0x3C2`.

The other thing the ISR needs to do is reset the vertical interrupt latch at bit `d4` in the Vertical Retrace End Register in the CRT controller by setting said bit to 0.

---
Tags: c++, vsync
---


# Question
Title: Rotating around 3D cube Camera Controller for Unity
I am Unity game developer with more than 2 years experience. I am working in a personal project, a mobile game for Android in Unity.

I am trying to make a camera controller for a 3D Cube Game in Unity. I have a controller working, I can position the camera in the six faces of the cube. But The problem happens when I move the camera several times. (See the images for more explanation)

For example, I always start the game on the Top face, but after several moves, the controller starts to move West, East when it should move North, South. I understand what the problem is, that the camera depends on the previous movements since it is rotating spherically, but I don't know what data structures to use or how to fix this.

I know is a complex problem that requires 3D Math, but maybe some of you have faced this before or have a better aproach, Thank you.

Here is some relevant code I wrote (with the help of chatGPT) :

```
public class TiltControl : MonoBehaviour
{

    // Define the faces of the cube
    public enum CubeFace
    {
        Front,
        Back,
        Left,
        Right,
        Top,
        Bottom
    }

    // Define the cardinal directions
    public enum CardinalDirection
    {
        North,
        East,
        South,
        West
    }

    // Dictionary to store adjacent faces for each face and direction
    private Dictionary<CubeFace, List<CubeFace>> adjacentFaces;

    private CubeFace currentCameraFace = CubeFace.Top;

    private void Start()
    {
        // Initialize the adjacent faces dictionary based on the current face
        adjacentFaces = new Dictionary<CubeFace, List<CubeFace>>();
        adjacentFaces[CubeFace.Front] = new List<CubeFace> { CubeFace.Bottom, CubeFace.Left, CubeFace.Top, CubeFace.Right };
        adjacentFaces[CubeFace.Back] = new List<CubeFace> { CubeFace.Top, CubeFace.Right,CubeFace.Bottom, CubeFace.Left};
        adjacentFaces[CubeFace.Left] = new List<CubeFace> { CubeFace.Front, CubeFace.Top,  CubeFace.Back, CubeFace.Bottom };
        adjacentFaces[CubeFace.Right] = new List<CubeFace> { CubeFace.Front, CubeFace.Bottom,CubeFace.Back, CubeFace.Top };
        adjacentFaces[CubeFace.Top] = new List<CubeFace> { CubeFace.Front,  CubeFace.Right,CubeFace.Back, CubeFace.Left};
        adjacentFaces[CubeFace.Bottom] = new List<CubeFace> { CubeFace.Back,  CubeFace.Left, CubeFace.Front, CubeFace.Right };
    }

    private void LateUpdate()
    {
         if (cameraJoystick.Horizontal < -0.25)
         {
             ChangeFaceToDir(CardinalDirection.West);
         }
         else if (cameraJoystick.Horizontal > 0.25)
         {
             ChangeFaceToDir(CardinalDirection.East);
         }
         else if (cameraJoystick.Vertical > 0.25)
         {
             ChangeFaceToDir(CardinalDirection.North);
         }
         else if (cameraJoystick.Vertical < -0.25)
         {
             ChangeFaceToDir(CardinalDirection.South);
         }
    }

    private void ChangeFace(CubeFace face)
    {
        currentCameraFace = face;
        cameraText.SetText(currentCameraFace.ToString());
        newPosition = cameraPoints[(int)face];
    }

    private void ChangeFaceToDir(CardinalDirection dir)
    {

        Debug.Log("toDir" + dir);
        currentCameraFace = GetAdjacentFace(currentCameraFace, dir);
        ChangeFace(currentCameraFace);

    }

    private CubeFace GetAdjacentFace(CubeFace face, CardinalDirection direction)
    {
        if (adjacentFaces.ContainsKey(face))
        {

            Vector2Int dirCard = GetCardinalDirection(direction);
            Vector3 rotated = (-1 * myCamera.right * dirCard.x) + (myCamera.forward * dirCard.y);

            Transform newTransform = Instantiate(cameraPoints[0]);
            newTransform.position = myCamera.position;
            newTransform.Rotate(myCamera.forward,Vector3.Angle(myCamera.right,rotated));

            Debug.Log("newTransform" + newTransform.right.normalized);

            int dir;

            dir = (int)GetCardinalFromDirection(new Vector2Int((int)newTransform.right.normalized.x,(int)newTransform.right.normalized.z));

            Destroy(newTransform.gameObject);

            Debug.Log("dir" + dir);

            return adjacentFaces[face][dir];
        }

        Debug.LogWarning("Invalid face: " + face);
        return face;
    }

    private Vector2Int GetCardinalDirection(CardinalDirection direction)
    {
        switch (direction)
        {
            case CardinalDirection.North: return new Vector2Int(1, 0);
            case CardinalDirection.East: return new Vector2Int(0, 1);
            case CardinalDirection.South: return new Vector2Int(-1, 0);
            case CardinalDirection.West: return new Vector2Int(0, -1);
            default: return new Vector2Int();
        }
    }

    private CardinalDirection GetCardinalFromDirection(Vector2Int direction)
    {
        if (direction == new Vector2Int(1, 0))
        {
            return CardinalDirection.North;
        }
        else if (direction == new Vector2Int(0, 1))
        {
            return CardinalDirection.East;

        }
        else if (direction == new Vector2Int(-1, 0))
        {
            return CardinalDirection.South;

        }
        else if (direction == new Vector2Int(0, -1))
        {
            return CardinalDirection.West;

        }
        return CardinalDirection.North;
    }

```

Code explanation:

1. I initialize the 4 possible neighbouring faces that one face can transition to (maybe this is the problem, as is fixed positions and the camera rotates spherically changing the orientation).
2. I check the input from the touch Joystick, that has just 4 valid directions (N,S,E,W)
3. Then in `GetAdacentFace` I should get the correct face depending on the Joystick direction, but here I get the wrong value in some cases. I do some calculations with the orientation of the main camera and the Joystick direction (and it sometimes returns the wrong face)
4. With this returned face, I move the camera to that face

# Answer
I just needed the approach that https://gamedev.stackexchange.com/users/21890/philipp said

A rig inside the cube and a focus point inside the rig. and the following code solve this:

```
private void ChangeFaceToDir(CardinalDirection dir)
{
    Debug.Log("toDir" + dir);
    //cameraText.SetText(currentCameraFace.ToString());

    switch (dir)
    {
        case CardinalDirection.North:
            rigPoint.Rotate(Vector3.right, 90f,Space.Self);
            break;
        case CardinalDirection.South:
            rigPoint.Rotate(Vector3.right, -90f, Space.Self);
            break;
        case CardinalDirection.East:
            rigPoint.Rotate(Vector3.forward, -90f, Space.Self);

            break;
        case CardinalDirection.West:
            rigPoint.Rotate(Vector3.forward, 90f, Space.Self);

            break;
        default:
            break;
    }
    newPosition = focusPoint;

}

```
> 1 votes

---
Tags: unity, c#, camera, rotation, geometry
---


# Question
Title: Why do so many games use non-linear leveling systems (each level taking more XP than the last)?
I see it all the time, in RPGs, FPSs, and more. I never see it talked about though. If level represents prestige, why is a linear progression not used? You can't easily determine somebody's experience that way. I imagine it has to do with something psychological, but I'm unsure. Where does this standard originate from? It's a bit of an open-ended question, so I'm open to responses. Thanks.

# Answer
> 4 votes
TomTsagk's answer already covers several major reasons. I just want to add on a few other ways of thinking about this:

# Feedback loops: Counterbalancing power and skill growth

Typically in an RPG, as you level up, your character gets more powerful, either through stat growth, gaining new abilities, or collecting better gear. This makes them able to deal more damage or take more punishment before you have to retreat and heal.

Alongside this, the player themselves tends to get better at the game: learning enemies' weaknesses, mastering timings, finding optimal strategies. So their efficiency in overcoming similar challenges goes up.

Left alone, this will tend to produce a runaway **positive feedback loop**: you gain a level, which gives you more power and skill, which helps you reach the next level faster, so you gain even more power and skill, so you reach the next level even faster than that...

You'd end up with an **accelerating rhythm of progression**, where the first level is the longest and slowest, and they come faster and faster after that, until in short order you've burned through all the meaningful progression milestones the game has to offer. This is generally the *opposite* of what you want. You want early milestones of progress (and especially the first one) to come quickly, to encourage a player who's just started dabbling in the game and teach them about the systems. Once they get deeper into the game, they're more invested, and have the patience to wait a bit longer between levels, so they don't exhaust all your game's goodies too quickly and run out of challenge or future milestones to look forward to.

Increasing the XP targets is a **negative feedback loop** that counters this runaway acceleration. The more you level up, the harder it becomes to level up. If calibrated well, the curve resulting from these two interacting loops closely tracks the player's investment in the game, starting with rapid, exhilarating progress, and then gradually spacing them out as the player gets into the groove and doesn't need the hand-holding/cheerleading, and can self-direct toward goals on a longer time horizon.

Adjusting the XP targets at each level gives designers a lot of flexibility to fine-tune this curve as needed for the game's specific experience goals.

# Why not reduce XP *earning* instead?

Mathematically, increasing the XP target you need to hit, or lowering the XP you get from a given enemy/task as you level up, both achieve the same end: you have to do more of that task to make the same progress, or you need to seek out more challenging and rewarding challenges. So you could do this, and it would work.

The reasons to prefer increasing the targets are mostly psychological and aesthetic.

**Loss aversion & negativity attention:** humans have a tendency to fixate on the negative, losses, the rewards they're *not* getting. This can make decaying rewards very *demotivating* — "yesterday this enemy gave me 100 XP, now it gives only 90 XP? The game *stole 10 XP from me!* It's not even worth my effort anymore."

World of Warcraft's experience with Rest XP is the classic example here. They started by reducing XP rewards when characters ran out of rest, but that was deeply unpopular. So instead they gave *bonus* XP for well-rested characters, and increased the XP targets to compensate. Mathematically the situation is identical, but psychologically this is much friendlier, and was better received by the player community.

**Integer limitations:** players in RPGs tend to expect XP to come in integer amounts. This limits the granularity with which you can diminish payouts. An enemy worth 10 XP at base gives you only 9 steps to work with before it becomes a worthless 0 XP. If the ideal balancing math says that at this level is should be worth an amount of progress that maps to 6.667 XP, you have to round one way or another and deviate from your ideal curve. You can counter this by making your XP numbers big, but it does look a bit weird seeing huge numbers like 600 XP in level 1, which ties into...

**Numbers getting bigger is motivating:** as TomTsagk's answer mentions, it feels good seeing numbers go up as you progress through the game (and at this point, there's a lot of gaming history contributing to player expectations that they *should* go up). If at the start of the game you were defeating foes worth 10 XP, and now you're defeating foes worth 1000 XP, wow, you're 100 times more powerful than you were back then!

Without this, players can experience a "red queen effect", where it feels like, for all their effort, they're not really progressing — they keep fighting harder and harder enemies for the same 50 XP that the rats in the tutorial level gave.

**Less burden to explain:** this is a minor one, but if you start shrinking players' XP earning, they tend to want to know *why*. What *rule* says how much XP they'll get from doing X at level Y? If you have a very hand-tuned progression curve you might be hard pressed to explain this to players' satisfaction, concisely. But an XP target, by convention, is easier to accept as an opaque fact: it takes longer to level up because you need 10 000 XP to reach level 5, because that's what the number on the XP bar says.

# Bonus: keeping players together in multiplayer

For multiplayer online games, the negative feedback loop provided by increasing level targets also acts as a bit of a leveler between players who've been playing the game a long time and those who joined more recently.

Say a new game comes out and I start playing it day one. For two weeks I'm raving to you about how awesome it is and begging you to make an account and play with me. Finally you join up, but now you're two weeks' worth of play behind my character. Say the gap between starting level 1 and my character at level 20 is 200 000 XP. That's huge! We can't play any dungeons or bosses together with a 19-level gap between us.

But as we both keep playing, earning XP at similar rates, that 200 000 XP gap starts to count for less and less. By the time I hit level 30, each level might be 100 000 XP apart, and so in a couple weeks you've caught up to within a level or two of me — without me needing to stop playing to wait for you.

At scale, this effect makes it easier for cohorts of players to stick together and find people to play with within relevant level ranges, despite the diversity in players' play schedules and histories, and the attrition of high-level players lapsing from the game. It's not a complete solution on its own, but it's one more tool in the designer's toolkit to mitigate these problems. This is why you'll often find online RPGs have *particularly* extreme ramps in XP targets from level to level, compared to their single-player counterparts.

# Answer
> 6 votes
There's a few reasons why this happens:

## Make the experience less predictable

If a user goes from level `1` to level `10`, with a linear scaling, they will have a good grasp of how the next `90` levels will look like. This makes the game boring and predictable.

When leveling is non-linear, it makes things harder to predict, allowing the user to enjoy the experience, and kill as many enemies as it takes to level up.

## Balance

As mentioned in the comments as well, how would this be balanced? If a user can kill `100` weak enemies to level up, what motive do they have to go for stronger enemies? This means that the fastest strategy to level up is to keep killing the weakest enemy, so any user who decides to fight stronger enemies is punished by slower progress.

## Increase the scale

Your XP requirements goes up, your stats go up, your health goes up, everything is getting upgraded. From being level `2`, with `50 HP` needing `10 XP` to level up, you are now level `38`, with `1300 HP` and need `5000 XP` to level up.

This makes the game exciting, the user feels like they are on a new level. Old enemies are now easy to kill, and new enemies are a challenge.

## Conclusion

Having said all that, there is no one correct answer on how to handle leveling. If you are really motivated, you can make a leveling system that is linear and as long as you know what you are doing, you can make it work.

Needless to say it's up to you what you choose for your game.

# Answer
> -2 votes
In skill-based games like League of Legends, non-linear leveling plays a role similar to "progressive overload" in weight training. That is, instead of continually doing the same thing to progress (lifting the same weights for the same number of reps/sets, or killing the same enemies), the player has to take on more difficult or complex challenges to keep making progress (heavier weights/more reps/sets, or killing tougher enemies). Stagnating at the same challenge level will lead to diminishing returns and slower progress.

Non-linear leveling is also used to slow down progression and keep players playing longer before maxing-out the endgame - especially in MMO games (where players might be monetized through subscriptions or microtransactions the longer they play).

Myself, I prefer games with horizontal leveling or no leveling system at all, to encourage player freedom, as seen in Minecraft, for example.

---
Tags: rpg, progression, psychology
---


# Question
Title: Input.GetAxisRaw not returning a 0 in Unity
this is extremely frustrating, basically Input.GetAxisRaw only ever returns a 1 or -1. see my code below

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

public class player : MonoBehaviour
{
    private BoxCollider2D boxCollider;

    private Vector3 moveDelta;

    private void Start()
    {
        boxCollider = GetComponent<BoxCollider2D>();
    }

    private void FixedUpdate()
    {
        float x = Input.GetAxisRaw("Horizontal");
        float y = Input.GetAxisRaw("Vertical");

        // Reset moveDelta
        moveDelta = new Vector3(x,y,0);

        // Swap sprite direction, whether you're going right or left
        if(moveDelta.x > 0){
            transform.localScale = Vector3.one;
        }
        else if(moveDelta.x < 0){
            transform.localScale = new Vector3(-1,1,1);
        }

        //Make this thing move!
        transform.Translate(moveDelta * Time.deltaTime);

        Debug.Log(x);
        Debug.Log(y);

    }
}

```

Here are screenshots from the input settings, I haven't changed anything:

Please help, I am new to Unity. Could not find anything that work, the other related post was unanswered.

# Answer
Hopefully I can post with zero reputation! I had an issue similar to this one. GetAxisRaw was pegged at 1 on vertical with no input from keyboard and no controllers connected.

I did have a 3Dconnexion spacemouse installed at one point and the utilities for that were installed and running. The spacemouse was not connected.

After shutting down all 3dconnexion utilities and rebooting Unity the issue went away.

All this is to say that if you encounter this issue it is very possible that it is related to software that is installed on your system. it's useful to check on a different system.

I hope that this helps.
> 2 votes

# Answer
If you are polling the keyboard, `InputGetAxisRaw` will *always* only return -1, 0 or 1 per the docs. Use `InputGetAxis` instead, assuming you don't want to do your own smoothing.

I've tested your code, zero *does* get returned when no keys are pressed:

Try polling/ logging `Input.GetAxis()` instead of `Input.GetAxisRaw` to see what kinds of values your keyboard is returning when idle. My guess is that it is returning some very small, but non-zero, value. If I'm right, you'll want to change your logic to move the sprite when the axis value is not simply greater than zero, but greater than that small threshold.
> 1 votes

---
Tags: unity, input
---


# Question
Title: How to access webcam in Godot on non-Apple platforms?
When I search for how to access the webcam in Godot, I find the CameraServer, but the docs say:

> **Note:** This class is currently only implemented on macOS and iOS. On other platforms, no CameraFeeds will be available.

But I do now have any Apple devices to test with. Is there a way I can access the webcam on non-Apple devices, or in a cross-platform way?

# Answer
> 3 votes
There's at least one plugin providing some Android support. There are pull requests for both Windows and Linux support.

---
Tags: camera, godot
---


# Question
Title: How to convert a Unity transform to Maya's coordinate system?
I created a level in Unity, and I want to place some of the level objects in Maya so I can create an animation based on these objects.

I can import the model FBX with no problems into Maya, but if I copy the translation, rotation and scale into Maya, the object doesn't get placed correctly. In particular, the rotation doesn't match.

Is there a way to consistently and accurately convert a Unity transform into Maya's coordinate system?

# Answer
It's not trivial.

Maya uses a right-hand coordinate system, while Unity uses left-hand; Maya uses centimeters, while Unity uses meters; Maya also allows you to choose a rotation order for each node, while Unity has a fixed rotation order. When you change the handedness and rotation order, the rotation values won't match in a trivial manner. We need to calculate the correct rotations.

To solve this problem once and for all, you can leverage Maya's Python OpenMaya API, which is compatible with Maya's coordinate system. You can use this function:

```
import maya.cmds as cmds
import maya.api.OpenMaya as OpenMaya

def applyMatrix(node, targetMatrixValues):
    targetMatrix = OpenMaya.MMatrix(targetMatrixValues)
    transformationMatrix = OpenMaya.MTransformationMatrix(targetMatrix)
    targetX, targetY, targetZ = transformationMatrix.translation(OpenMaya.MSpace.kWorld)
    scaleX, scaleY, scaleZ = transformationMatrix.scale(OpenMaya.MSpace.kWorld)
    eulerRotation = transformationMatrix.rotation(asQuaternion = False)
    eulerRotation.reorderIt(cmds.getAttr(node + '.rotateOrder'))

    cmds.setAttr(node + '.translateX', targetX)
    cmds.setAttr(node + '.translateY', targetY)
    cmds.setAttr(node + '.translateZ', targetZ)
    cmds.setAttr(node + '.rotateX', eulerRotation.x * 57.29577951)
    cmds.setAttr(node + '.rotateY', eulerRotation.y * 57.29577951)
    cmds.setAttr(node + '.rotateZ', eulerRotation.z * 57.29577951)
    cmds.setAttr(node + '.scaleX', scaleX)
    cmds.setAttr(node + '.scaleY', scaleY)
    cmds.setAttr(node + '.scaleZ', scaleZ)

```

Basically, what the function does is that it takes a 4x4 matrix, creates an `MTransformationMatrix`, and outputs the translation, rotation and scaling.

For the rotation, we get Euler angles, and we can even use `reorderIt()` to match the rotation to the node's rotation order.

Finally, we convert the Euler angles to degrees, since Maya works in degrees, not radians.

All we have left to do is to export the 4x4 matrix from the Unity transform.

HOWEVER...

We can't simply extract the matrix and expect for it to work as-is. We first need to change the units (cm to m), and change the handedness of the matrix. I have a C# method that does this for me:

```
private static void UnfudgeMatrix(ref Matrix4x4 matrix)
{
    // Convert a matrix from Unity's coordinate system to Maya coordinate system
    matrix[1] = -matrix[1];
    matrix[2] = -matrix[2];
    matrix[4] = -matrix[4];
    matrix[8] = -matrix[8];
    matrix[12] = -matrix[12] * 100.0f;
    matrix[13] = matrix[13] * 100.0f;
    matrix[14] = matrix[14] * 100.0f;
}

```

You could do this on Maya's side instead too. I chose to do it on Unity.

And finally, to extract the matrix, I created a script that takes a transform and outputs the required `applyMatrix()` invokation:

```
private static void Export(Transform t)
{
    var m = t.localToWorldMatrix;
    UnfudgeMatrix(ref m);

    var s = new StringBuilder();
    s.AppendFormat("applyMatrix('{0}', [", t.name);

    for (int k = 0; k < 16; k++)
    {
        s.AppendFormat("{0:0.000}", m[k]);
        if (k < 15)
            s.Append(",");
    }
    s.Append("])");
    s.AppendLine();

    Debug.Log(s.ToString());
}

```

This method outputs the method invokation via `Debug.Log()`, but you can do it in any other way as you wish.

The output of this method I then put it into Maya's Python console along with the `applyMatrix()` definition, I run it, and it automagically places my object in the correct position!

This approach also works for converting more complicated things, such as skeleton poses. The OpenMaya documentation is your best friend if you want to adapt this code for other purposes.
> 1 votes

---
Tags: unity, c#, mathematics, python, maya
---


title: Math formula for game attack speed

text:
# Question
Title: Math formula for game attack speed
I want to create a function for a game stat of attack speed, but I cannot figure out how to write a math function for this.

My formula should work in a way, if attack speed is 200%, it does 4 hits per second., 100% does 2 hits per second, 1000% does 10 hits per second etc..

These are the expected results:

```
 speed       attack_speed
  100000%  = 1000
  10000%   = 100
  2000%    = 20
  1000%    = 10
  200%     = 4
  100%     = 2
  50%      = 1.5
  10%      = 1.1
  1%       = 1.01
  0%       = 1
 -1%       = 0.99
 -10%      = 0.9
 -50%      = 0.75
 -100%     = 0.5
 -200%     = 0.25
 -1000%    = 0.1
 -2000%    = 0.05
 -10000%   = 0.01
 -100000%  = 0.001

```

For example, If I give a `speed` value of -100%, it should return an `attack_speed` of 0.5

I was using the formula `att_speed = 1 / (1 + speed / 100)`, but it didn't return correct results.

# Answer
The target values you show in the table don't follow one consistent rule, so the best we can do is a piecewise approximation, using different formulas for different ranges.

I've highlighted in blue the ranges where each constituent formula fits well. The two rightmost sets show different ways of combining these parts to get a formula for the whole range.

* For high `speed` values (\>= 10), `attack_speed` is equal to `speed`

(taking 100% = 1.0 as is standard convention - if your code stores this as 100 instead, then divide it by 100 first for all formulas in this answer)
* For values close to zero, `attack_speed` is equal to `speed + 1`
* For low values, the relationship is approximately hyperbolic. There's no hyperbola that matches the entire range, but for simplicity, `1 / (1.0 - speed)` is a close approximation.

(I've included the results of Bogdan's answer, which is identical to the formula I show below for `speed <= 200%`, but retains some small error for higher speed values)

We can glue these three ranges together into a single formula as in the following pseudo-code:

```
float get_attacks_per_second(float speed) {

    if (speed >= 0) {
        // Linear segments:

        // Smoothly ramp bias down from 1.0 for low speeds (<= 2)
        // to 0.0 for high speeds (>= 10).
        float bias = 1.25f - speed / 8.0f;

        // Clamp the bias between zero and one.
        bias = clamp(bias, 0, 1);

        return speed + bias;
    } else {
        // Hyperbolic segment:
        return 1.0f / (1.0f - speed);
    }
}

```

You can see this gives quite a good match across the whole range, with the exception of the point (2, 4) where the formula gives an output value of 3 instead. Looking at the graph though, it looks like that point at `speed = 200%` breaks the trend of the points on either side of it, and may be an outlier or error. We'd have to put a pretty severe kink in the curve to pass through that point.
> 4 votes

# Answer
```
 void Update()
    {
        Debug.Log($"100000 = {GetAttcksCount(100000)}");
        Debug.Log($"10000 = {GetAttcksCount(10000)}");
        Debug.Log($"2000 = {GetAttcksCount(2000)}");
        Debug.Log($"1000 = {GetAttcksCount(1000)}");
        Debug.Log($"200 = {GetAttcksCount(200)}");
        Debug.Log($"100 = {GetAttcksCount(100)}");
        Debug.Log($"50 = {GetAttcksCount(50)}");
        Debug.Log($"10 = {GetAttcksCount(10)}");
        Debug.Log($"1 = {GetAttcksCount(1)}");
        Debug.Log($"0 = {GetAttcksCount(0)}");
        Debug.Log($"-1 = {GetAttcksCount(-1)}");
        Debug.Log($"-10 = {GetAttcksCount(-10)}");
        Debug.Log($"-100 = {GetAttcksCount(-100)}");
        Debug.Log($"-200 = {GetAttcksCount(-200)}");
        Debug.Log($"-1000 = {GetAttcksCount(-1000)}");
        Debug.Log($"2000 = {GetAttcksCount(-2000)}");
        Debug.Log($"10000 = {GetAttcksCount(-10000)}");
        Debug.Log($"100000 = {GetAttcksCount(-100000)}");
    }
    float GetAttcksCount(int attackSpeed)
    {
        if (attackSpeed >= 0)
        {
            return 1f + 0.01f * attackSpeed;
        }
        else
        {
            return 1/GetAttcksCount(Mathf.Abs(attackSpeed));
        }
    }

```
> 0 votes

---
Tags: mathematics
---


# Question
Title: Why does my unity Cinemachine camera that follows the mouse only rotate on the x axis not the y axis
I've recently started work on a 3rd person game and want the camera (cinemachine virtual camera) to rotate with the mouse while following the cinemachine camera, it would be best described as when you "aim in" in fortnite and your player is locked to where you are aiming and your player and camera will rotate with your mouse not w a s d. Here is my code that I currently have, it allows me to follow the player like I want but only rotates the camera on the x axis and not the y. I've tried a multitude of different script variations to try to get it to work. Pictured below is my script and my CinemachineVirtualCamera I have set up, along with the player object. I've watched just about every tutorial on camera movement but none cover the issue I'm having.

# Answer
Line 30 remove and paste it in Start or Awake. Because each frame you reset rotation of camera. You do not need to reset it if you want to rotate around Y axis.
> 0 votes

---
Tags: unity, c#, game-mechanics
---


# Question
Title: Loading Custom Resources for Test Cases - Copying the main way and loading in tres files with code
I am at the start of testing my game. I have just loaded in GUT and I am attempting to load some resources so that I can see the players stats and validate that they are initialised.

Basic assert to check that the characters max health, etc., is as it should be. 80 health should be given from the loaded resource and 80 health is the expected...

I will try to keep the code light, and if there is anything missing please tell me :)

---

I have set up the Party Member script in order to keep track of the needed stats. (shortened)

PartyMember.gd

```
extends Node2D

@export var resource : Resource

@onready var health : int

func _ready():
    health = resource.health

```

It is expected that I can load in a custom resource (\*.tres) with various different types of characters and enemies. This has, of course, been working manually.

test\_Battle\_System.gd

```
func test_attackSentAndDamagedEnemy():

    var party = load("res://Resources/Party Members/Party Member.tscn")
    var thief = preload("res://Resources/Party Members/ThiefStats.tres")

    # Attempt to set Resource
    party.resource_path = thief.resource_path
    #set Stats
    assert_eq(party.resource_path, "res://Resources/Party Members/ThiefStats.tres", "Should be Thief")
    assert_eq(party.resource.health, 80, "Should be 80 for Thief")

```

I believe 2 things are unknown.

How to actually set the resource to the needed scene 'entity' (currently Thief) and how to read in the health variable. (should just be party.resource.health)

Thank you for reading this far. I assume it is an easy problem and just me getting used to Godot 4.

# Answer
> 2 votes
I have figured it out, with some help of course!

https://stackoverflow.com/questions/65660219/dont-know-how-to-reference-other-scene-into-script

I needed to grab the Scene and the Resource. I then needed to **instantiate** (changed in Godot 4) the scene and add it into the Scene Tree.

From here I had access to the resource and was able to use it in order to complete the initial prefill of data for the characters.

Code Below - Shortened for clarity:

test\_Battle\_System.gd

```
    var partyPath = load("res://Resources/Party Members/Party Member.tscn")
    var thief = load("res://Resources/Party Members/ThiefStats.tres")

    var party = partyPath.instantiate()
    var root = get_tree().get_root()
    # add tres here, before it starts the ready function
    # Attempt to set Resource
    party.resource = thief
    root.add_child(party)

    assert_eq(party.resource.resource_path, "res://Resources/Party Members/ThiefStats.tres", "Should be Thief")
    assert_eq(party.resource.health, 80, "Should be 80 for Thief")

```

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


# Question
Title: Which pixels does the fragment shader of an unlit shader, applied on an object, affect in Unity?
Let's say that I have a cube that has an unlit shader applied to it. The shader does basic ray-marching.

```
Shader "sdf shader"{
    Properties{
    }
    SubShader{
        Pass{
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            float sphere(float3 posi, float r){
                return distance(posi, unity_ObjectToWorld._m03_m13_m23) - r;
            }

            float4 raymarch(float3 ori, float3 dire, float4 uv, float r){
                float d;
                for(int i; i < 64; i++){
                    if (d > 40){
                        break;
                    }

                    float3 post = ori + (dire * d);

                    if (sphere(post, r) < 0.001){
                        return float4(0,0,0,0);
                    }

                    d += sphere(post, r);
                }
                return uv;
            }

            struct appdata{
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f{
                float4 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            v2f vert (appdata v){
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.vertex;
                return o;
            }

            fixed4 frag (v2f i) : SV_Target{
                float3 pos = mul(unity_ObjectToWorld, i.uv);
                float3 dir = normalize(pos - _WorldSpaceCameraPos);
                float4 output = (1,1,1,1);

                float4 col = raymarch(pos, dir, output, 1);
                return col;
            }
            ENDCG
        }
    }
}

```

Does the shader do calculations for every pixel in the viewport or only the ones covered by the cube? By "covered by the cube", I mean the pixels that are currently displaying the cube and not the area around it.

# Answer
The fragment shader is invoked for every pixel covered by each non-culled triangle of the mesh being rendered, so long the pixel passes the early depth and stencil tests.

(The early depth test fails if the pixel is occluded behind a closer opaque object that was drawn first, or a closer pixel of the same batch drawn earlier in the draw call if depth writes are enabled. The stencil test only runs if you ask for it, and is used to mask out which regions of the screen can be written to)

If you're ever curious which pixels are getting affected by a shader, or a particular branch in a complex shader program, just write something like `return float4(1, 0, 0, 1);` — any pixel that turns red was running that shader / that branch. Any pixel that doesn't, wasn't.

Technically, the shader also gets invoked for some pixels *just* outside each triangle too: the graphics card processes 2x2 blocks of pixels at a time, so that can include stray pixels wherever the triangle only partially covers such a block. These pixels get masked out, so values outside the triangle don't get written into the destination buffer, so for most purposes we can ignore these invocations — they just contribute to lower shading efficiency when using tons of small triangles where the waste adds up.
> 1 votes

---
Tags: unity, shaders, fragment-shader
---


# Question
Title: What's the appropiate way to achieve composition in Godot?
How?

I think I still don't properly understand how composition in Godot works. So, as far as I know, you 'compose' stuff in Godot, right? Like, if you want to make a rock you create a **mesh node** with your rock 3D model. You want the rock to have collisions? oh ok, then add a **body node** and specify its **collision shape** (another node). Now you want the rock to talk...for some reason (?), well you can! add a **'talk' node**! oh want it to shoot lasers? *oh boy*, add a big and juicy **'shoot' node**! And so on, you add and add...and add nodes. You compose your rock through aggregation I guess?

Now, I'm trying to make the controllable character the player is going to use, but to be honest I'm still not sure about its full extent of abilities. It may be able to run, to jump, to fly, or it may not. Through aggregation, this problem is likely solved, isn't it? since I could just make the 'base' character, with some basic functionality, and *then* add more functionality as needed.

I've seen some code that does something like this:

```
class PlayerController()
{
    private Movement _movement;
    private Jump _jump;
    private Attack _attack;

    private DoStuff()
    {
       // Let's imagine we're handling input here
       _movement.DoMovememnt();
       if(_jump != null) _jump.DoJump();
       if(_attack != null) _ attack.DoAttack();
    }
}

```

But the problem here is that the `PlayerController` class is expecting, to some extent, the other classes to exists. I don't think that's how it should work...

If I understood this article, that would some sort of a **Component Container**.

Then, I've also seen stuff like this:

```
class Movement() { // Do stuff }
class Jump() { // Do stuff, and if neccesary, modify properties from `Movement()`}
class Attack() { //Do stuff, and if necesary, modify properties from `Movement()` or `Jump`}

```

Basically, the *PlayerController* doesn't actually exists, and its more of just a concept within the system (in Godot, the player would be just the name of the node, which holds the Movement, Jump and Attack nodes). If the player attacks and an enemy, and you've decided that the player can't move and attack at the same time, then the Attack node could access some properties from the Movement node to block actual movement.

Though I'm not sure if that last bit could be considered aggregation, since in that particular case, wouldn't accessing other class properties create dependency? I don't see much of a problem in here because the 'base' doesn't *need* any of the classes above to work, nor isn't expecting any class to exists.

Although to be honest, I can't see any realistic scenario were, for example, a Jump node doesn't need to know anything about the Movement node, since usually jumping affects somehow movement. Like, it would be physically impossible to entirely isolate both one from each other.

Buuuuut I'm probably not getting the idea behind composition. Or did I?

Keep in mind that I'm using C# and Godot 3.5.2 (unfortunately I can't go 4.x due to my requirements).

# Answer
I have gone from a monolith player controller, to an state machine, to a behavior tree, to something closer to what you describe.

My current character controller looks something like this in the scene tree:

```
character
├ collider
├ model
├ animation_tree
├ character_jump
├ character_run
├ character_auto_walk
├ character_edge_guard
└ character_rotate

```

The `character` node handles gravity, keeps some common properties and has helper methods that `character_jump`, `character_run`, `character_auto_walk`, `character_edge_guard`, and `character_rotate` use.

Now, character does not call them. Godot call them. By virtue of being `Node`s on the scene tree I can use `_ready`, `_enter_tree`, `_exit_tree`, `_input`, `_process`, `_physics_process`, etc. They can also use `Input` on their own.

Instead they call into the `character`. So `character` do not depend on them, they depend on `character`.

---

And they do not depend on each other... And for that their order is key.

For, you see, `character_jump` and `character_run` modify the `velocity` property of the `character`, but if `character_auto_walk` is active, by virtue of `character_auto_walk` being after `character_jump` and `character_run` in the scene tree, it runs afterwards and would overwrite whatever modification to `velocity` that `character_jump` and `character_run` might have done.

Similarly, if `character_edge_guard` is active, it can overwrite `velocity` to prevent the character from walking off a cliff, regardless if it was previously set by `character_jump`, `character_run` or `character_auto_walk`.

*And `character_rotate` is at the end, because I want the character to rotate to face in the direction it is moving (according to `velocity`) when it is all said and done.*

*In my current project I do not have means of attack, but my current thinking is to place a `character_attack` after `character_rotate` so the attack can use the updated orientation. And yes, it can also overwrite `velocity` to make sure the character does not move while attacking, for example.*

---

Picking animations is handled in the `animation_tree`, and it is done by reading the properties of the `character`. *It does not have to be an `AnimationTree`.*
> 12 votes

# Answer
> Basically, the PlayerController doesn't actually exists, and its more of just a concept within the system (in Godot, the player would be just the name of the node, which holds the Movement, Jump and Attack nodes).

It does exist in that a KinematicBody has a built-in connection to the physics engine, it has some assumptions that any physics object will want to display something and have some collision information.

I think it can be dangerous to over-engineer the architecture of a game that might not even have a formal design document yet. I think it's better to start with a real simple prototype and not get sidetracked trying to solve problems you might not ever encounter.

> But the problem here is that the PlayerController class is expecting, to some extent, the other classes to exists. I don't think that's how it should work...

This is an advantage of a game engine though, that it gives you a recommended set of patterns of how things fit together.

The way I organize things is to make a Player scene (Player.tscn) with a KinematicBody "Player" node, whose children are a Sprite or Mesh node, collider nodes, etc. Main player logic is in a single state machine script attached to the parent KinematicBody. The \_physics\_process() loop is just an if statement that cycles every frame to fire off bits of the state machine.

I usually have weapons or items as separate nodes, instanced as children of the Player node, then triggered by state machine. All of the weapon logic, animations, etc. are off in a separate .tscn scene. Other parts of the state machine, like jumping or blocking, can usually happen directly in the Player.cs (or Player.gd) script, or in a Jump.cs that gets preloaded and instanced by the state machine. But not every behavior needs a whole separate .tscn scene the way weapons and items do. I go with the flow of the Godot hierarchy when it makes sense to do so, but I don't pre-build any more complexity into the interface than I need to.
> 1 votes

# Answer
> But the problem here is that the PlayerController class is expecting, to some extent, the other classes to exists. I don't think that's how it should work...

The PlayerController should be expecting the "base" classes to exist. Each new controller would be setup to be able to be composed of all the bases classes and it is these bases classes that you then extend with new specialized children.

I might also recommend bringing in these base classes via dependency injection within the constructor of your controller. That way you can either supply the specialized children of those bases or not.
> 0 votes

---
Tags: c#, architecture, godot, design-patterns, component-based
---


# Question
Title: How to achieve no gaps between triangles in software renderer like in Quake?
I've heard alot that I need to use fixed-point math, top-left rule, etc. to eliminate gaps between triangles but the thing is how did Quake not have any gaps, did it? I've seen Quake's math file and vec2, vec3 were only typedefs for a float array, so I don't really understand how Quake hadn't any 'stitches'. Was the game doing a pixel overfill?

Also, I heard that Quake was an example of a gapless rasterizer but that might be rumors. Haven't seen gaps myself, actually.

# Answer
> 0 votes
Using floating point 3D coordinates isn't an issue because the gaps only show up after converting to integer pixel coordinates, which you need for rendering them on screen. It's at that point that you need to be careful how you define which pixels are inside a triangle.

If you look at the source code for Quake, you can see that they are using integers. Here's what I found with a quick search:

https://github.com/id-Software/Quake/blob/bf4ac424ce754894ac8f1dae6a3981954bc9852d/WinQuake/d\_iface.h#L66

https://github.com/id-Software/Quake/blob/bf4ac424ce754894ac8f1dae6a3981954bc9852d/WinQuake/d\_polyse.c#L150

Note that all standard 3D rendering APIs have similar rules for determining which pixels are considered inside each triangle. Here are the D3D9 ones, for example: https://learn.microsoft.com/en-us/windows/win32/direct3d9/rasterization-rules

---
Tags: graphics, c, rasterization, fixed-point
---


# Question
Title: Detect which child Triggered inside parent script in Unity
I have a parent gameobject with rigidbody and parent script. The gameobject has many children and each child has Box collider and "is Trigger" option is on.

When each child collide with other object, it detected in parent script. But I can't detect which child colided...!

How can I figure it out without add script to children?

Children are too many and if I add any script to them the game performance get lowered.

# Answer
Add this script to the object(player) that collides with your triggers.

```
  private void OnTriggerEnter(Collider other)
    {
        Debug.Log(other.gameObject.name);
    }

```

And when your player collides the trigger it will display the trigger name.
> 0 votes

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


# Question
Title: Discontinuous Normals on a Normalized Cube Mesh with Displacement Texture
In my project, I have created a normalized cube using six plane meshes. To improve its visual quality, I added a displacement texture and calculated the normals for that texture to ensure proper lighting. However, I’m facing an issue where the resulting normals appear discontinuous at the edges, revealing the underlying cube structure rather than achieving a smooth, sphere-like shape. you can see here: example

Here is my shader code:

```
function vertexShader() {
  return `
    varying vec2 vUv;
    uniform sampler2D u_tex;
    uniform vec3 wTl;
    uniform vec3 ps;

 //normalize each plane
 vec3 planeToSphere(vec3 p, vec3 localCenter){
    return 100.0*normalize(p-localCenter) + localCenter;
  }

varying vec3 v3n;
    void main() {
      vUv = uv;
      vec3 newPosition   =  planeToSphere(position,wTl) ;
      vec3 worldp = ( modelMatrix * vec4(newPosition,1.0)).xyz;
      float n = texture2D(u_tex, vUv).x;
      //newPosition = newPosition + 1.0*n*normalize(position-wTl); // this add displacement
      gl_Position = projectionMatrix  * modelViewMatrix * vec4( newPosition, 1.0 ) ;
    }
  `
}

function fragmentShader(){
  return `
    varying vec2 vUv;
    uniform sampler2D u_tex;
    varying vec3 v3n;

  vec4 displacementMapToNormalMap(sampler2D displacementMap, vec2 vUv){
    float scale    = 0.9;   // Adjust this to control the amount of displacement
    float epsilon  = 0.01;  // Small value for calculating gradients
    float strength = 1.;
    float center = texture2D(displacementMap, vUv).r; // Sample displacement map
    float dx = texture2D(displacementMap, vUv + vec2(epsilon, 0.0)).r - center;  // Calculate gradients in the X  directions
    float dy = texture2D(displacementMap, vUv + vec2(0.0, epsilon)).r - center;  // Calculate gradients in the Y directions
    vec3 normalMap = normalize(vec3(dx * scale, dy * scale, 1.0));               // Calculate the normal vector
    normalMap *= strength;                                                       // Apply strength to the normal vector
    return vec4(normalMap * 0.5 + 0.5, 1.0);                                     // Output the resulting normal as a color
  }

void main() {
    vec3 lightDirection = normalize(vec3(0.,1.,1.));
    vec4 normalMapColor = displacementMapToNormalMap(u_tex, vUv);          // Get the normal map color
    float grayscale = dot(normalMapColor.rgb, vec3(0.299, 0.587, 0.114));  // Convert the normal map color to grayscale
    vec4 grayColor = vec4(grayscale, grayscale, grayscale, 1.0);
    float lightIntensity = dot(normalMapColor.rgb, lightDirection);       // Calculate the lighting contribution
    vec4 finalColor = grayColor * lightIntensity;                         // Apply the lighting to the grayscale color
    gl_FragColor = finalColor;                                            // Output the resulting color
}
`
}

```

I have been working on this problem for weeks, but I have yet to make significant progress. During my research, I came across a relevant Stack Overflow question titled “How can I eliminate normal map seams on Cube Mapped Three.js BoxBufferGeometry?” you can see here.

One of the responses suggests not using the tangent frame provided by Three.js and instead generating tangents using the vertex data to align them at the seam. However, this is still wrong because The bi/tangents can not be continuous over the sphere (the Hairy Ball theorem). All the research I have done has led me to a dead end. I have seen a few posts on the web related to this same question but never an actual solution. Someone out there has to know how to tackle this problem.

I would greatly appreciate any guidance or suggestions on how to resolve the issue of discontinuous normals and achieve a smooth appearance for the normalized cube with a displacement texture. Thank you in advance for your help.

# Answer
> 0 votes
so, the solution was to use a CubeTexture to make the normals continues.

solution

compute the normals like so.

```
   vec4 displacemntNormalCubeMap(samplerCube u_displacementMap, vec3 vUV){
    float scale    = 4.9;   // Adjust this to control the amount of displacement
    float epsilon  = 0.1;  // Small value for calculating gradients
    float strength = 1.;
    float center = textureCube(u_displacementMap, vUV).r; // Sample displacement map
    float dx = textureCube(u_displacementMap, vUV + vec3(epsilon, 0.0, 0.0)).r - center;  // Calculate gradients in the X  directions
    float dy = textureCube(u_displacementMap, vUV + vec3(0.0, 0.0, epsilon)).r - center;  // Calculate gradients in the Y directions
    vec3 normalMap = normalize(vec3(dx * scale, dy * scale, 1.0));               // Calculate the normal vector
    normalMap *= strength;                                                       // Apply strength to the normal vector
    return vec4(normalMap * 0.5 + 0.5, 1.0);                                     // Output the resulting normal as a color
  }

```

---
Tags: shaders, glsl, geometry, three.js
---