# Question
Title: How do online games handle frequent updates?
Web/Mobile full stack engineer here. Zero game experience.

How do big multiplayer games handle multiple database updates simultaneously?

I.e. World of Warcraft or similar games with 10k players playing at the same time say defeat 10-20 monsters at once, it drops items & the player gets experience. This is probably 5-15 database updates per player simultaneously

Please let me know if the question isn’t clear or needs further clarification

# Answer
While web applications tend to store everything in the database immediately, games work a bit differently.

Any information pertaining to the players currently in the game is stored in the RAM of the gameserver. This is not just to keep load off of the backend database, but also for performance reasons. Games require very low latency and do a lot of number crunching. Delegating all that to the database would result in unacceptable response times.

And then there is a lot of information which really does not need persisting. Like the positions of monsters, for example. When a server reboots, then nobody will care that the monsters don't spawn in the exact same locations as they were when the server went down.

The information the game *does* need to persist, mostly the state of the player-characters, usually does not get persisted to the backend database in real-time. Usually it only gets persisted when the client disconnects, the server goes offline or at regular intervals (to not lose too much game-state in case of a server crash).

And because character-states are usually persisted and restored in an all-or-nothing manner, I would argue that it is questionable that there is any benefit to properly normalize all the data of the character gamestate. So instead of making different database tables for character stats, character inventories, character quest states etc. it can make sense to just store all the information about each character as a BLOB. The drawback is that BLOBs are far harder to analyze and data-mine. But you can solve that by importing all that data into a properly normalized secondary database used only for analytics. That data doesn't need to be perfectly up-to-date, so you can do that as a daily job which runs during the time where you have the least players online. And then the analytics team can do whatever they want with their analytics database without affecting the actual game.
> 34 votes

# Answer
Firstly, as a comment points out, a properly configured database can be pretty fast, especially in 2022. But MMOs have been around for thirty years, so it's worth looking at the techniques rather than relying on Moore's law to save us.

> I.e. World of Warcraft or similar games with 10k players playing at the same time say defeat 10-20 monsters at once, it drops items & the player gets experience. This is probably 5-15 database updates per player simultaneously

The big trick is that they're not all playing at the same time in the same place. WoW segments its players by server, and then further groups them by "instance", so that there's only ever a much smaller number directly interacting. That allows rapid updates to be made to the instance's copy of the data, which are then persisted to permanent storage at a lower rate.

There are very few MMOs which allow you to have everyone in the same place at the same time. The big exception is EVE Online, which groups players by star system but can still support battles with thousands at one time.
> 6 votes

# Answer
When i was working on a MMORPG (2006-2011ish), we loaded character data from MySQL on login, and held all updates in RAM, until character logout/avatar death, upon which the MySQL database was updated and the RAM released. Also each login was a dedicated OS-level thread, and each player-thread spent the majority of their time synchronizing with the main "game thread" (for example, a player sent a packet for "throw my weapon on the floor", the player thread receives it, tells the main game thread, then the main game thread updates the inventory and floor tile in-ram, and tells all player threads whose avatar is in the vicinity, "update the item list on this floor tile"~)

* the SQL queries was (mostly) only on login and logout, and ran in their own dedicated thread.
* the server had a max limit of 666 concurrent logged in players, and that limit was rarely reached (right now its 347 players, but i no longer work on it, and i don't know if that limit still exist)
> 4 votes

# Answer
When I worked on MMORPGs main issue for such engines was RAM for database handling.

All stuff is in database and it's just changes of database values upon actions on client. Then depending on game code quality there's anticheat which detects separately whether the client is trying to game speed in database (that's why there is a lot of cheaters in online games).

So say you are slashing a dude in MMORPG - that means your client sends to server attack command and receives health and modified values. If you use potion it is sent in a separate command so sometimes lag or network drops can destroy your winnings or potion use or something because that particular packet didn't get through and invalidated request.

For speed most of such exchanges are not really protected so it allows a lot of cheating to happen.

Most of games are made with client doing most of the work because most game programmers have no understanding of proper network programming (with multithreading and asynchronous io. most have no idea about this.)
> 0 votes

---
Tags: mmo, databases
---


# Question
Title: Button to call Application.OpenURL not working
I have a public method

```
public void patreononclick(){
   Application.OpenURL("http://www.patreon.com/HubakaGs");
}

```

This is supposed to open my Patreon page when a button is tapped.

But when I tap the button in the built application, nothing happens.

I have assigned the function to the On Click() section of the Button (Script).

I am building the game for Android and I use Unity 2017.1.0p4 Personal.

How can I make the button function properly?

Update:

I changed the function to

```
public void patreononclick(){
    Debug.Log ("the game should open patreon");
    Application.OpenURL("http://www.patreon.com/HubakaGs");
}

```

But when the button is clicked, there is no message in the console.

# Answer
After hours of pulling hair, I finally noticed that this

was set to off, so I set it to Editor And Runtime, and it worked perfectly. I can even open the link from the editor trough a browser.
> 1 votes

# Answer
Here are four things to check when your UI button click event is not firing…

1. Make sure your canvas has a `Graphics Raycaster` attached.
2. Your Image component's `Raycast Target` must be enabled.
3. Make sure there are no overlapping UI elements.
4. Make sure to have a gameobject with the `EventSystem` component in the scene.
> 1 votes

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


title: What is a vertex color?

text:
# Question
Title: What is a vertex color?
My question is what is written in title. This term "vertex color" appear a lot. I am having hard time to understand this.

For example:

Isn't a vertex simple point on 3D space? If so, how can a point have a color? Or does this "color" mean something else?

There is a "Vertex Color" node in unreal engine's material editor.

Can someone shed light on my question? I couldn't find anything usefull when I googled "what is a vertex color" but the documentations that are too technical for me.

# Answer
Vertex colors aren't that relevant when you have a fully textured 3d mesh. But it gets interesting when you have an untextured but colored mesh. In that case you assign a color to every vertex. The shader would then color each pixel of a polygon by interpolating between the colors of the three vertices.

Vertex colors can also sometimes be interesting in combination with textures. When you want to use a shading algorithm like Gouraud Shading, you just calculate the light intensity on each vertex, assign the light color to the vertex as a vertex color, and when you render the texture you multiply the color value of each texture pixel with the interpolated colors. This allows you to calculate light sources in the vertex shader instead of the pixel shader. This is usually far faster, because the vertex shader is usually executed far less frequently.
> 32 votes

# Answer
In theory, Vertex Color allows to color a model without having to bother with textures. This is quite common in CAD.

In practice, it's just one more slot you can use to push data into the vertex, which you then use in the vertex shader to do crazy stuff.

> "Isn't a vertex simple point on 3D space?"

That's what I used to think, when I first started with 3D. I learned quickly that **I was wrong**.

You can think of a vertex as a data blob that makes up a corner of a triangle you want to paint on screen (and neither the "corner" part nor the "triangle", "paint", or "screen" parts are always true). Position is one -optional - aspect of that data blob we call Vertex.

There is a lot you can do by attaching additional data to the vertex. The most famous example is that you can add uv coordinates to draw a texture on that triangle. You (usually) can't decide what part of a texture to draw on the triangle if you just have a point - you need texture coordinates too.

Other standars examples of what's in that blob are normals, and tangents. What's important is that all of them are optional, including the position. Vertex Color is just one of these optional inputs that you can use or abuse to create a pretty picture on the screen.
> 26 votes

# Answer
Vertices can have colors, it's a property just like the normal of it.

In 3d enviroments a triangle gets colored based on their vertices' color information. The closest fragments to vertex A get the color of it, the closesr to vertex B get the colornof B, and the color interpolates between the 2.

It works the same way as per-vertex lighting

It's an easy way to add colors to a model without using a texture.
> 9 votes

# Answer
There are solid answers here already - I just want to chime in with one more common way you'll see vertex colours used:

**Varying object colours (or other attributes) within a single batch / draw call.**

You'll see this used in rendering particle systems, text, and batched (usually atlassed) sprites.

Imagine you have a particle emitter that spawns particles with a random start colour, or that fade to 0 alpha over the particles' lifetime. If we were to use shader uniforms to send this colour data, we'd need to draw each differently-coloured particle in its own draw call, making the particle system much more expensive. Instead, we can bake these colours into the vertex data for the particles, and render the whole batch together in a single call.

Unity appears to use this technique for particle colour variation, as well as for colouring individual characters in a TextMesh or Sprites rendered together in a batch.
> 1 votes

# Answer
In the context of Roblox, vertex color is a `Vector3` with a range of 0...1 (negative values -1...0 are flipped and treated the same as positive values). The greater the value, the brighter the color is.
> 0 votes

---
Tags: vertex, terminology
---


# Question
Title: Invalid maximum heap size: -XX:MaxHeapSize=4096m
I am trying to package android project in UE4.27. And getting this

I tried changing environment variable \_JAVA\_OPTIONS: -Xmx512M -Xms512M not worked.

Where can I change MaxHeapSize, please tell me exact location. Or any solution is there?

# Answer
> 1 votes
It looks like you are using a 32 bit version of Java (because if it was a 64 bit version it would explicitly say so).

The problem is that the 32 bit version doesn't support heaps larger than 2GB. You are asking for a heap twice that size.

You can solve this problem by either reducing your heap size or switching to a 64 bit JVM.

---
Tags: java, unreal-4, unreal, mobile
---


# Question
Title: Sprite created with RenderTexture and ReadPixels() has multiplied colors
I'm working on a character generator that creates thumbnail sprites for each character. I'm using a separate camera that renders to a `RenderTexture`, which is used to create a sprite using `ReadPixels()`. The resulting sprites appear to have their colors multiplied. I'm stumped. I've messed around extensively with lighting and ambient lighting. Right now the only lighting is ambient. I've tried various color formats for the `RenderTexture`. I've tried assigning different materials to the resulting sprite, including the default.

Here is the relevant code, which generates the sprite:

```
IEnumerator GeneratePortrait(Npc npc)
    {
        Texture2D tex = new Texture2D(512, 512);
        RenderTexture.active = rt; //assigned at Start()
        tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0);
        yield return null;
        tex.Apply();
        RenderTexture.active = null;
        npc.sprite = Sprite.Create(tex, new Rect(0, 0, 512, 512), new Vector2(256, 256));
    }

```

**Update** I tried changing the line that creates the texture to `Texture2D tex = new Texture2D(512, 512, TextureFormat.ARGB4444, false);` This shouldn't work; the format of the RenderTexture is the default for the target platform `R8G8B8A8_UNORM` but the result is much better. Still some multiplication happening, but acceptably close.

# Answer
> 2 votes
**Use `Graphics.CopyTexture()` instead of ReadPixels()**

CopyTexture Docs

Not sure why ReadPixels is doing the weird stuff, but CopyTexture doesn't. Here's the updated code:

```
IEnumerator GeneratePortrait(Npc npc)
    {
        Texture2D tex = new Texture2D(512, 512,TextureFormat.RGBA32, 1, false); // need to specify only 1 mipmap level
        RenderTexture.active = rt;
        Graphics.CopyTexture(rt, tex);
        yield return null;
        RenderTexture.active = null;
        npc.sprite = Sprite.Create(tex, new Rect(0, 0, 512, 512), new Vector2(256, 256));
    }

```

---
Tags: unity, rendertexture
---


# Question
Title: How does Unity's FromToRotation work? A major part of its behavior seems undocumented
All Unity's documentation states about what `FromToRotation` does is:

> Creates a rotation which rotates from fromDirection to toDirection.

This seems to leave a major part undefined - what about the other axes?

I can't help but think of the saying - If it isn't documented, the behavior is undefined.

And there seems to be no documentation of what happens to the rest of the axes. Theoretically you could spin them around `toDirection` as much as you'd like and still get what you were promised.

So, what exactly happens to the other axes when you use `FromToRotation`?

# Answer
`FromToRotation` chooses the shortest possible rotation that maps `fromDirection` to `toDirection`.

That is, the rotation about the axis

```
axis = Vector3.Cross(fromDirection, toDirection);

```

through an angle of

```
angleRadians = Mathf.Acos(Vector3.Dot(
                  fromDirection.normalized,
                  toDirection.normalized
               ));

```

This does become indeterminate if the two directions are exactly opposite: then a 180 degree rotation about *any* axis perpendicular to them is an equally short option, so the engine has to choose one arbitrarily.

I'm currently on mobile, so I have not tested which axis it uses in this special case, but I'd expect it uses a routine something similar to:

```
var right = Vector3.Cross(Vector3.up, fromDirection);
if (Math.Approximately(right.sqrMagnitude, 0)) {
    axis = Vector3.forward;
} else {
    axis = Vector3.Cross(fromDirection, right);
}

```

This gives the y+ axis if the two inputs are in the xz plane, the axis closest to y+ if the two inputs aren't themselves vertical, and the z+ axis if the two inputs *are* vertical. That choice is arbitrary, but seems to make sense for typical 3D navigation use cases.
> 4 votes

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


# Question
Title: How can I move my package folders into another folder to clean up Assets?
I've seen a couple different answers or weird workarounds to this topic: Package folders usually just go straight into the Assets folder, pretty much turning everything into a huge mess.

Here's a related but old question to this: Import Unity Package Into Specific Folder

I can't imagine that there is no way to clean this up without doing weird workarounds like that. Do professionally developed games like Rust and Yooka-Layle really just have a messy Assets folder?

I've read that moving the folders will cause problems down the line, if packages have hard-coded paths or during updating. This info is a few years old by now, is that still a real concern?

I'm currently getting to a point where my Assets folder contains more external packages (NuGet, TextMeshPro, Ink, etc, etc) than my own, and its getting fairly chaotic.

Can I move my external packages to a different folder?

(Out of curiosity: how do large game productions handle this? Do they just live with the chaos?)

# Answer
The Assets folder is a root folder where you put all of your assets (whether you've developed them or they're from a third-party). How you organize files within the Assets folder is up to you. My Assets folders usually end up looking something like this:

```
Assets/
    AcmeGames/
        SomePackage/
            Examples/
            Scripts/
            Textures/
        SomeOtherPackage/
            Scripts/
    {MyStudio}/
        Shared/
            Scripts/
        {MyGame}/
            Animations/
            Audio/
            Meshes/
            Scripts/
            Shaders/
            Textures/
    XYZ Studios/
        SoundFXPackage/
            Audio/

```

Each package is organized into a subfolder named for the author of the package. You'll note that I organize the files for the game I'm working on into `Assets/{MyStudio}/{MyGame}`. I feel this approach is clean and easily to navigate; it also works best with Visual Studio's ability to automatically generate namespaces based on the folder structure. Some teams don't want to have to navigate into a subdirectory and prefer to put the folders for their game in the Assets root, usually preceded by an underscore to ensure they sort at the top of the alphabetical order:

```
Assets/
    _Audio/
    _Animations/
    _Scripts/
    _Textures/

```

I do not recommend this approach as I find it messy and it's not always obvious which assets were developed internally and which are from third-party sources.

If you have a large number of third-party packages, you can put them all in a subfolder:

```
Assets/
    ThirdParty/
        AcmeGames/
        Misc/
        Odin/
        Microsoft/
        Photon/
        PlaceholderSoftware/
        Unity/
        Vuforia/
        XYZStudios/

```

**Otherwise, the only way to keep packages out of the Assets folder is to configure them for compatibility with the Unity Package Manager**, so that they can be installed in the Packages folder. I've never seen a third-party asset that is configured as a Package Manager package, but in theory you can manually create Packages from third-party assets.

> I've read that moving the folders will cause problems down the line, if packages have hard-coded paths or during updating. This info is a few years old by now, is that still a real concern?

I don't often encounter this as an issue. If you do run into such an issue, it's usually easy to fix. What typically causes difficult problems is if you modify any of the files in the package, since your changes will be overwritten and lost when you update the package.
> 3 votes

---
Tags: unity, asset-management
---


title: Move player towards screen

text:
# Question
Title: Move player towards screen
I've got a fixed projection perspective camera with a vertical FOV of 70 deg and rotated 45deg on Y axis.

Player movement is along Camera's X axis (right/left), Z axis (front/back), Y axis is set to 0.

What I'd like to achieve is for the player to move directly towards the screen top/bottom when pressing forward/back keys instead of moving along camera's Z axis which causes and illusion of traveling at an angle the further from the center of the screen you are (which makes sense but is not desired in this case).

The screenshot below depicts:

* **Green**: Direction to camera
* **Blue**: Camera's Z axis (player movement forward/back)
* **Red**: Desired forward/back movement vector

I was able to brute-force some values like if camera's Z axis are at 45deg to the player-camera direction then the desired rotation would be half of that (22.5deg) but I can't seem to find a solution for the rest of the world positions due to my lack of Math knowledge.

# Answer
I've thought of a possible solution to this, but it feels really inelegant, so I would be interested in hearing other people's take on this.

My idea is as follows:

Take the position of the player in screen space (2D). Add to it the desired movement direction (0,1) to get another 2D point in screen space.

Now, project both those points (the player position and the result of adding the vector) into 3D space. If you are using godot (which I think is what that screenshot is), the camera has a `project_position` method that does this. The catch here is that any point in the screen maps to infinitely many points in space, so you need to specify a depth to get a single 3D point. I believe any depth should work, as long as you keep it consistent for both points, but it probably makes the most sense to use the depth of the player character (its z position in the camera's local space).

If you now connect those two 3D points you get a vector in 3D space which, when drawn on the camera, looks completely vertical.

Of course, this vector is not going to be parallel to the surface on which the caracter is walking, so you probably want to project it there and whatnot.

I feel like there is a much better solution using the camera's projection matrix to undo the perspective deformation, but I'm afraid I don't know how :(
> 2 votes

---
Tags: 3d, mathematics, camera, vector, projection
---


title: What's "isMatchingTarget" in Unity?

text:
# Question
Title: What's "isMatchingTarget" in Unity?
I came across this line of code below.
What the boolean "isMatchingTarget" is used for?

```
 private void OnAnimatorMove()
 {
   if(_animator.isMatchingTarget)
       _animator.ApplyBuiltinRootMotion();
 }

```

# Answer
As the documentations says, this property tells you

> If automatic matching is active.

OK, not very helpful, because it does not tell us what "automatic matching" actually *is*. But if we look at not just the scripting reference but at the regular Unity manual, we can find the article Target Matching which does explain the concept:

> Often in games, a situation arises where a character must move in such a way that a hand or foot lands at a certain place at a certain time. For example, the character may need to jump across stepping stones or jump and grab an overhead beam.
>
> You can use the Animator.MatchTarget function to handle this kind of situation.

In other words, you can use the script function `animator.MatchTarget` to tell the animator to move the animated object, so one of the characters limbs ends up interacting with a certain object in the environment (defined by position and rotation). The method `animator.isMatchingTarget` tells you whether or not this was done for the current animation.

---

By the way, there is also another way to make sure that character hands or feet (or gaze) end up exactly where you want them to be: Inverse Kinematics. The difference between target matching and IK is that target matching achieves that by translating and rotating the root of the gameObject, while IK adjusts the pose of the character to match.
> 3 votes

---
Tags: unity, animation, animator, character-controller
---


# Question
Title: Barycentric coordinates outputting coordinate outside of triangle
So I am trying to draw and fill a triangle on the screen using the barycentric method, but my barycentric implementation seems to be outputting outside triangle coordinates, why?

```
#include <iostream>
#include <cmath>
using namespace std;
double triarea(double a, double b, double c)
{
    double s = (a + b + c)/2.0;
    double area=sqrt(fabs(s*(s-a)*(s-b)*(s-c)));
    return area;
}

// compute the distance between two 2d points
double dist(double x0, double y0, double x1, double y1)
{
    double a = x1 - x0;
    double b = y1 - y0;

    return sqrt(a*a + b*b);
}
double returnMax(double A, double B, double C)
{
    return (A > B ? A : B) > C ? (A > B ? A : B) : C;
}
double returnMin(double A, double B, double C)
{
    return (A > B ? B : A) > C ? C : (A > B ? B : A);
}
double barycentric(double x0, double y0, double x1, double y1, double x2, double y2, double px, double py)
{
    double a = dist(x0, y0, x1, y1);
    double b = dist(x1, y1, x2, y2);
    double c = dist(x2, y2, x0, y0);

    double ABC= triarea(a, b, c);

    double pa = dist(x0, y0, px, py);
    double pb = dist(px, py, x2, y2);
    double pc = dist(x2, y2, x0, y0);
    double PAB= triarea(pa, pb, pc);

    double paa = dist(x1, y1, px, py);
    double pbb = dist(px, py, x2, y2);
    double pcc = dist(x2, y2, x1, y1);
    double PBA= triarea(paa, pbb, pcc);

    double inorout = 1 - (PAB/(double)ABC) - (PBA/(double)ABC);

    return inorout;
}
void drawtriangle(double x0, double y0, double x1, double y1, double x2, double y2)
{
    double maxx = returnMax(x0, x1, x2);
    double minx = returnMin(x0, x1, x2);

    double maxy = returnMax(y0, y1, y2);
    double miny = returnMin(y0, y1, y2);

    for(double x = minx; x < maxx; x++)
    {
        for(double y = miny; y < maxy; y++)
        {
            if(barycentric(x0,y0, x1,y1, x2,y2, x,y) >= 0)
            {
                //draw pixel
                cout <<  "(" << x << "," << y << ")" << endl;
            }
        }
    }

}
int main()
{
   drawtriangle(-5,-5,10,30,20,5);
    return 0;
}

```

# Answer
> 1 votes
It looks to me like you've taken a Barycentric coordinate function designed for determining the coordinates of a point *known* to be inside the triangle.

It does not account for the way the sign of the area flips when the point exits the triangle, inverting the winding, and it does not check whether areas `PAB` or `PBA` (really CAP and BCP) are negative, only the third triangle ABP. So it's not suitable for determining the barycentric coordinates of a point that could be outside the triangle.

It's also a very wasteful method, repeatedly computing distances and areas that are constant for the whole triangle, with all the expensive square rooting and divisions that entails.

If you just want a binary yes/no answer as to whether a point is inside a triangle, you can do that by checking its winding instead.

```
bool isInsideTriangle(double ax, double ay, double bx, double by, double cx, double cy, double px, double py)
{
    if ((bx - ax) * (px - by) - (by - ay) * (px - bx) < 0) return false;
    if ((cx - bx) * (px - cy) - (cy - by) * (px - cx) < 0) return false;
    if ((ax - cx) * (px - ay) - (ay - cy) * (px - ax) < 0) return false;

    return true;
}

```

Reverse the sign checks if your front-facing triangles are wound the opposite way.

What this does is compute the z component of the cross product of two edges of each triangle ABP, BCP, CAP. That component will be positive if the triangle winds in one direction, and negative if the triangle winds in the opposite direction. If the point P is inside the triangle ABC, all three sub-triangles wind the same way. As soon as P crosses an edge, one of the sub-triangles flips its winding.

No more square roots or divisions, and with a little elbow grease you could probably vectorize this calculation so you check all three failure cases in parallel.

---
Tags: c++, mathematics, rasterization, barycentric-coordinates
---


# Question
Title: Player overshoots path using NavigationAgent2D and NavigationPolygonInstance in Godot 3.5
I'm trying to add a click to move feature in my game using the new NavigationAgent2D and NavigationPolygonInstance but sometimes when the player reaches the end of the navigation path or changes direction it overshoots the next point so it gets stuck there moving back and forth.

The logic to move the player is pretty straight forward:

**Player.tscn**

```
extends KinematicBody2D

export var MAX_SPEED := 250

onready var navigation_agent := $NavigationAgent2D

var velocity := Vector2()

func _ready():
    set_target_location(position)

func set_target_location(target: Vector2) -> void:
    navigation_agent.set_target_location(target)

func _physics_process(_delta):
    if navigation_agent.is_navigation_finished():
        return

    var move_direction = position.direction_to(navigation_agent.get_next_location())
    velocity = move_direction * MAX_SPEED
    navigation_agent.set_velocity(velocity)

func _on_NavigationAgent2D_velocity_computed(safe_velocity):
    velocity = move_and_slide(safe_velocity)

```

**World.tscn**

```
extends Node2D

onready var player := $Player

func _input(event):
   if event is InputEventMouseButton and event.pressed:
       var target_location = get_global_mouse_position()
       player.set_target_location(target_location)

```

I tried checking if the player arrived by measuring the distance between its position and the navigation agent next location and forcing it it stop if it gets close. This works if the navigation is a straight line but if it isn't then the player stops as soon as it needs to change direction:

```
func _physics_process(_delta):
    if navigation_agent.is_navigation_finished() || position.distance_to(navigation_agent.get_next_location()) < 4:
        return

    ...

```

I created a repo with some minimal code to reproduce the issue, hopefully it can help: https://github.com/jahvi/godot-sample

I think ideally I need to check if my player is within a certain distance from the next point and if so force it to change direction but I'm not sure how to do this.

Can anyone advise how to avoid this overshooting?

# Answer
> 2 votes
I've never used Godot, but just searching the API for NavigationAgent2D turns up this:

> float **path\_desired\_distance**
>
> | Default | 1.0 |
> | --- | --- |
> | Setter | set\_path\_desired\_distance(value) |
> | Getter | get\_path\_desired\_distance() |
>
> The distance threshold before a path point is considered to be reached. This will allow an agent to not have to hit a path point on the path exactly, but in the area. If this value is set \[too\] high the NavigationAgent will skip points on the path which can lead to leaving the navigation mesh. **If this value is set \[too\] low the NavigationAgent will be stuck in a repath loop cause it will constantly overshoot or undershoot the distance to the next point on each physics frame update**.

(Emphasis added - sounds like exactly your problem, right?)

It looks like you're measuring your distances in pixels, and trying to move at 250 pixels per second. At 60 fps that's 4.166 pixels per frame, which means you'll almost never land within the default tolerance range of 1.0. Increase the tolerance to a little over one full time step's worth of movement at your max speed and you should avoid the overshoot.

Do so similarly for `target_desired_distance` for the end of the path.

---
Tags: path-finding, godot, navmesh
---


# Question
Title: How do I take a scene-object popup window, and use instances of a prefab button to initiate it?
I have a button that invokes a modal window (a market transaction). Using the inspector `onclick`, I have successfully setup so that 1 of the 9 buttons will pop the window (`GameObject.SetActive ✅`), and then the Done button in the window will close it ().

However there are 9 of these buttons, and they use a prefab for their design.

Here's a pic of the hierarchy with the button instance highlighted:

Each `rowItem` is the exact same (from a `rowItem` prefab). Also, each row has data that needs to be passed into the modal. An index would probably be enough.

How do I setup the prefab so that the 9 instanced buttons invoke the popup and pass the data?

I'm a JS webdev by day, so I generally understand the concepts. I'm just newbie on the syntax and where everything is in Unity.

# Answer
> 0 votes
I'm not 100% sure I understand your question, but if you want to get the index of the button you pressed, you can do something like this:

```

public class MarketTable : MonoBehaviour {
    [SerializeField] private IndexedButton buttonPrefab;
    private List<IndexedButton> buttons;

    void Awake() {
        AddButtons();
    }

    void AddButtons() {
        buttons = new List<Button>(9);
        for (int i = 0; i < 9; i++) {
            var button = Instantiate(buttonPrefab);
            button.Index = i;
            buttons.Add(button);
            button.ClickEvent.AddListener(OnClickButton);
        }
    }

    void OnClickButton(IndexedButton button) {
        int index = button.Index;
        //do something with the index here
    }
}

[System.Serializable] public class IndexedButtonEvent : UnityEvent<IndexedButton>

[RequireComponent(typeof(Button)]
public class IndexedButton : MonoBehavior {
    [SerializeField] private IndexedButtonEvent clickedEvent = new IndexedButtonEvent();

    public int Index { get; set; }
    public IndexedButtonEvent ClickedEvent => clickedEvent;

    void Awake() {
        button = GetComponent<Button>();
        Assert.IsNotNull(button);
        button.onClick.AddListener(OnClickButton);
    }

    void OnClickButton() {
        clickedEvent.Invoke(this);
    }
}

```

Here we've created a custom component for the Market Table UI panel and a custom component for our buttons. We add the `IndexedButton` component to our button prefab. When we instantiate a button, we set its index. When we click a button, the button's `ClickedEvent` is invoked, which calls the `OnClickButton()` function with a reference to the button that was clicked. We can then check the index on the button.

You could also replace the `Index` property with some other type of data that you want to associate with the button.

---
Tags: unity
---


# Question
Title: Unity text is very blurry. How can I fix it?
Unity text is very blurry. How can I fix it?

To be honest, I have no idea why it behaves this way:

Hope that someone faced the same problem and will be able to share how it was tackled.

# Answer
> 3 votes
**Make certain your UI Text object is not inadvertently upscaled.**

This can happen any number of ways. In my experience, the most common occurrence of this happening is due to generating UI objects from prefabs, but it can also happen after you change the reference resolution, reorder/ reparent objects in the hierarchy and probably other situations as well.

Since the OP is using a World Space Canvas (possibly the most prone to scaling issues, as the canvas is rendered as an object in the scene vs. an overlay) I will use that as an example.

New Canvas (including World Space) rect bounds will default to whatever the game view pane is currently set to. Note that if you have your game view set to **Free Aspect**, that bounds is going to be something fairly arbitrary! For this example, I have set my game view to 2880 x 1920 (blue box).

As expected, our new Canvas component is scaled to 1,1,1 and is sized to our game view window size by default. I've rotated the canvas 45° in Y to utilize its "world-spaciness" and moved it a bit so it is in view of the default camera.

The text component is also scaled at 1,1,1 so everything looks just fine.

Now this is a fresh scene, created "out of the box" with just these simple components -- it's kind of hard to go wrong in this situation. Suppose instead you are knee deep in scene creation with a complex UI system. You have been moving, resizing and reparenting elements, maybe generating child UI objects from prefabs created with a different scene configuration -- pretty soon you have child objects with (up)scaling applied which is not immediately obvious. For a trivial example, let's say I created the World Canvas and then scaled it up by 10, and then created a text object child. This is the result:

The text object's local scale is still 1,1,1, but it is being upscaled 1000% by its parent canvas. The result is blurry text.

The OP in their answer already pointed out that the Canvas Scaler with its `dynamic pixels per unit` setting is also key to having Text UI elements properly rendered on screen.

# Answer
> 2 votes
In order to fix the problem I just went to the game object which contains the `Canvas` component and added the `Canvas Scaler`. After that I played around with the `Dynamic Pixels Per Unit` field value until my text got the sharpness I want.

# Answer
> 1 votes
Unity ui text is always blurred and have quality issue. You can use TextMeshPro for better quality crisp and sharp text with lots of other options for text customisations.

---
Tags: unity, text, unity-ui
---


# Question
Title: Decal Projector equivalent in unity's standard shader pipeline
I have a script in my Unity project that creates glowing outlines around objects when highlighted in a scene. The shaders don't work properly with the URP or HDRP. However, I want to create a move target object for a point and click interface that will "paint" itself onto the environment where the player is going to move. Since this is a constantly changing dynamic placement, I figured the HDRP's decal projector would be the best way to do it.

Is there any kind of Decal Projector equivalent available in Unity's standard shader pipeline?

# Answer
> 0 votes
Didn't know about the Projector component, thanks DMGregory.

---
Tags: unity, shaders, rendering, projection, decal-system
---


# Question
Title: Remove or skip splash screen from Unity Free/Personal game binary for modding
How can I modify a Unity game (Windows) binary to skip the 5-second Unity logo splash screen?

I know how to mod game code using dnspy to modify `Assembly-CSharp.dll`. I'm able to find isShowingSplashScreen but that appears to be irrelevant. I'm at a loss whether I can find the splash screen code in any .dll or if one would have to edit the game .exe or some other file. Looking at the game .exe in HxD (hex editor), I see multiple occurrences of `unity_SplashScreen` but have no idea whether I can use this for anything.

# Background

I'm modding a Unity game and I am not very good at it. I have to try a lot and start the game a lot. This means each time I test something, I lose five seconds because the game was made with the free Unity version.

As a player I made no commitment to the Unity ToS. I also have no intent to distribute a modded file that removes the splash screen. However, I want to remove it during development.

I am **not** asking how to remove the splash screen while building the game. I am not developing in Unity, I am modding a game made in Unity and I'm trying to streamline the process.

I did see Unity remove logo in splash screen, Alternatives to remove Unity splash screen after developing a game with the free version?, Can I legally remove the default Unity splash screen by removing it from the APK?. They revolve around the question of removing the splash screen with intent to distribute, which is not the topic here.

I had hesitations about asking this question, due to the answer being useful to developers willing to violate the ToS. However it seems on-topic and legal. I would also argue that the solution to my problem is probably going to be too much effort for active game dev projects to bother using it (having to repeat the steps for each new update) and that "bad apple" devs would rather use pirated versions of Unity Pro.

# Answer
It is possible to skip the Unity splash screen without manipulating any of the game files using a tool that accelerates the execution of a process.

Cheat Engine (be weary of bloatware during download **and** installation) provides this functionality and even automation through Lua scripting language.

I made a video guide: https://youtu.be/Oje1QEC-R9c

## Instructions

1. Install and start Cheat Engine
2. Open **Table/Show Cheat Table Lua Script**
3. Paste following code in it (replace `game.exe` with your game's process name file - might differ from .exe file name, see video)

```
appName="game.exe" -- name of the application process

function listenOnceStops(timer)
  if getProcessIDFromProcessName(appName) == nil then
    object_destroy(timer)
    startLoop(attachOnceStarts)
  end
end

function attachOnceStarts(timer)
  if getProcessIDFromProcessName(appName) ~= nil then
    object_destroy(timer)
    openProcess(appName)
    speedhack_setSpeed(20)
    sleep(1000)
    speedhack_setSpeed(1)
    startLoop(listenOnceStops)
  end
end

function startLoop(loop)
  f = createForm(false) --create an invisible window
  t = createTimer(f);
  timer_setInterval(t, 500)
  timer_onTimer(t,loop)
end

startLoop(attachOnceStarts)

```

Code also available here.

4. Press **Execute script**.

This will skip the first 20 seconds in one second, which includes the five second Unity splash screen. One drawback is that the script might start while the Resolution Dialog (resolution picker/screen selector) window appears, if the exe is configured to show it.

This might also work on macOS, since there seems to be a version of Cheat Engine for that platform. Not tested. No clue about Linux.

A simpler solution would still be welcome.
> 4 votes

# Answer
A morally and legally sound way that can be openly discussed on a public forum like this one is to **contact the original developer**.

If you meet with such circumstances, chances are the game is one of these 2:

1. The game is new/early access, reasonably successful (otherwise there's rarely a modding community) and the developer hasn't gotten around to switch to Unity Professional - which the free license requires them to do after making $100'000.
2. The game is a completely free hobby project, in which case the developer might be open to the idea of people sponsoring his license, or giving source code access to some trusted modders.

In both of these cases, it's usually possible to reach the developer directly through any and all of their company's support addresses. When you do so, concentrate on describing your problem (load times) rather than proposing a solution (spend money), unless you're willing to provide a solution for them (pay in their stead).

This doesn't work if the game was made by a single developer who just disappeared (for whatever reason). Should that be the case, Iwan's answer seems to be the best option.
> 5 votes

# Answer
It is possible to disable the unity splash screen on build game files.

I used unity pro to determine what files change when you switch splash screen on and off and it's the globalgamemanager file if you manually edit a specific part in it using a hex editor you can disable the splash screen

I made a tutorial on how to do it here: https://youtu.be/xvh0AeZCX9E

This was tested on Unity 2020.3.38f1 lts
> 0 votes

# Answer
You can not do this unless you have access to the engine environment that they use and have to hope that they have the enterprise edition and have selected to remove it
> -3 votes

---
Tags: unity, modding
---


title: Fetching IAP localized price in Unity

text:
# Question
Title: Fetching IAP localized price in Unity
How can I obtain localized price of products to show on my purchase page?

# Answer
If you are using Unity's IAP solution, `ProductMetadata.localizedPriceString` will give you localized price of an in-app product. `ProductMetadata` has other properties as well, including localized title & description.

ProductMetadata documentation
> 3 votes

---
Tags: unity
---


# Question
Title: Is it possible to calculate a direction vector without sqrt?
I'm not using Unity or any other library for making game logic. I'm making a basic game logic that needs to do basic vector math on the backend side.

I just wrote a direction function that needs to do `sqrt` for normalization. `sqrt` is not a performant function, so it is especially good to avoid on the backend side.

I need to know if I can make a normalizing function without `sqrt` — is there a way around it?

Do libraries like Unity's `Mathf` use `sqrt` under the hood?

# Answer
> 6 votes
If you want a correct mathematical result (correctly rounded to within floating point precision), a square root is the way to go.

It's true that it's more expensive than a multiply, but it's still very likely *not* the bottleneck in your app's performance. Even expensive operations still cost far fewer CPU cycles than a single cache miss. And you've likely got cache misses happening more often than you normalize vectors.

To make this concrete with some numbers, let's summarize typical cycle counts for floating point operations in the magnitude ranges we tend to use, based on timings on an Intel Core i7 CPU from this document, and cache info from here (not the exact same model, but close):

| Operation | (Approximate) Cycles |
| --- | --- |
| Addition | 5 |
| Multiplication | 5 |
| Division | 8 |
| Sqrt | 10 |
| L3 Cache Latency | 42 |

So you can do at least 4 square roots (very likely 2-4x more, due to pipelining) in the time it takes to pull in the next object to update that wasn't already hot in cache.

Trying to eliminate `sqrt` at this stage is almost certainly a premature micro-optimization. I'd bet that you're paying much greater inefficiencies in architectural choices like data layout that are far easier to change than the laws of geometry.

Very old games like Quake III used to use an *approximation* of `1/sqrt(x)` for normalizing vectors, which you can read about in the Wikipedia article "Fast Inverse Square Root", but it points out that this strategy isn't really your best option on modern hardware:

> With subsequent hardware advancements, especially the x86 SSE instruction `rsqrtss`, this method is not generally applicable to general purpose computing, though it remains an interesting example both historically and for more limited machines, such as low-cost embedded systems.

If you're normalizing big batches of vectors where the square root cost is a substantial fraction of the total computation time, you'll likely get better gains by vectorizing the code so you compute four normalizations at once, rather than trying to get clever with how you compute the square root itself.

Overall, be wary of programming by hearsay. When folks say "square root is expensive, avoid it when you can", they're mainly talking about cases where the square root is *unnecessary* to the value you care about: like comparing the length of a vector against a threshold or finding the shortest/longest vector in a collection. Those are cases where you get the same answer using squared length, so paying for a square root there is cycles burned for no improvement in accuracy. Where there's accuracy to be gained (like in getting a correct unit vector), it's worth paying the modest cost of a square root and division.

---
Tags: mathematics, vector, optimization, linear-algebra
---


# Question
Title: Where to trigger load from PlayerPrefs for data in a static class?
I have this save system that saves screenshots in consecutively-numbered files. I store the number of the last number used in `PlayerPrefs`, so that the next save continues from there.

But I'm not sure where to call the `LoadNumber` method to load the last used number, since this is a static class with no `Start()` function.

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

public static class SaveSystem
{
    private static int countName;

    public static string Load(string FileName)
    {
        string content = File.ReadAllText(FileName);

        return content;
    }

    private static string ScreenShotName(int width, int height)
    {
        return string.Format("{0}/Saved Games/SaveSlot{1} SavedGameSlot_{2}x{3}_{4}/SavedGameSlot_{1}x{2}_{3}.png",
            Application.persistentDataPath,
            countName,
            width, height, System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
    }

    public static void Save(string saveString, int resWidth, int resHeight)
    {
        string filename = ScreenShotName(resWidth, resHeight);
        string directory = Path.GetDirectoryName(filename);
        Directory.CreateDirectory(directory);
        ScreenCapture.CaptureScreenshot(filename);
        string fileName = Path.Combine(directory, "savegame.txt");
        File.WriteAllText(fileName, saveString);

        countName++;

        SaveNumber();
    }

    public static void SaveNumber()
    {
        PlayerPrefs.SetInt("countName", countName);
    }

    public static void LoadNumber()
    {
        countName = PlayerPrefs.GetInt("countName");
    }
}

```

# Answer
You can read PlayerPrefs lazily, the first time someone tries to read the current count:

```
static int? _count;

public int count {
    get {
        if (!_count.HasValue) {
            _count = PlayerPrefs.GetInt("countName", 0);
        }
        return _count.Value;
    }
    set {
        _count = value;
    }
}

```

Or you can read it eagerly as the game boots up, after all scripts in your starting scene have gotten their `Awake()` message, using the RuntimeInitializeOnLoadMethodAttribute:

```
[RuntimeInitializeOnLoadMethod]
static void LoadNumber()
{
    countName = PlayerPrefs.GetInt("countName", 0);
}

```
> 2 votes

# Answer
I think it can be simple like this,

```
public static int CountName
{
    get => PlayerPrefs.GetInt ("countName", defaultValue);
    set => PlayerPrefs.SetInt ("countName", value);
}

```

This is as simple as like changing normal variable value.
> 1 votes

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


# Question
Title: Setting the theme default/font color in Godot
Is there a way to set the default/font/fill color for a theme, either in the editor or in the .tres file?

I've found ways to change colors through scripts and by overrides, but I can't find anything on setting a color (besides outline) for a theme. This seems like the most basic thing a theme should do, and I can't find any useful information on it.

By theme I mean the resource type: https://docs.godotengine.org/en/stable/classes/class\_theme.html. The end result should be a default color for text (RichTextLabel) objects by assigning a theme, without having to use theme overrides or scripts.

# Answer
> 5 votes
I found the answer elsewhere. There's a little button in the theme toolbar:

This button adds node types to the theme. Font fill color needs to be set per each component type. In the .tres file the line is (for RichTextLabel):

```
RichTextLabel/colors/default_color = Color( 1, 1, 1, 1 )

```

with each digit representing r, g, b, a on \[0,1\]

You can style multiple types through inheritance:

```
Control/colors/font_color = Color(1, 0, 0, 1)

```

Most UI elements use "font\_color". RichTextLabel uses "default\_color" and Tabs use "font\_color\_\[bg/disabled/fg\]".

---
Tags: godot
---


# Question
Title: Holding "Shift" to lock mouse movements to a straight line?
I'm making a little program that's a bit like paint but instead of filling in pixels, it drops a block on `mousebutton(0)`. I'm now trying to add a straight line toggle on it to make the mouse only move up/down + left/right. Tried a few things so far, but none worked and can't find anything on this specific question. Have you guys done something similar and if not, how would you approach this?

Current code:

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

public class MouseStraightLine : MonoBehaviour
{
    //If the shift key is pressed the mouse should only move in a straight line
    public bool straightLine = false;

    void Update()
    {
        if (Input.GetKey(KeyCode.LeftShift))
        {
            straightLine = true;
            StraightLine();
        }
        else
        {
            straightLine = false;
        }
    }

    public void StraightLine()
    {
        //Locks the mouse to only be able to move in a straight line up/down or left/right
        //Get the mouse position and store it
        Vector3 mousePos = Input.mousePosition;
        //If the mouse is moving in the x axis
        if (Input.GetAxis("Mouse X") != 0)
        {
            //Lock the mouse to only move in the x axis
            mousePos.y = 0;
            mousePos.z = 0;

            //Disable y axis movement

        }
        //If the mouse is moving in the y axis
        if (Input.GetAxis("Mouse Y") != 0)
        {
            //Lock the mouse to only move in the y axis
            mousePos.x = 0;
            mousePos.z = 0;
        }

        //Set the mouse position to the new position
        Input.mousePosition.Set(mousePos.x, mousePos.y, mousePos.z);
    }
}
```
</code></pre>

# Answer
> 3 votes
**Cache relevant x or y value after shift key is detected**

PseudoCode:

```
Vector2 oldMousePos, mousePos
float x, y

Update
 mousePos = mouse.position
 x = mousePos.x
 y = mousePos.y
 if ShiftKeyDown //fires on frame shift key is first pressed
   //detect users desired axis: x or y
   if (ABS(mousePos.x - oldMousePos.x) > ABS(mousePos.y - oldMousePos.y)) //user is going left to right
     y = mousePos.y
   else
     x = mousePos.x

// Do drawing here or whatever, using x & y coords

  oldMousePos = mousePos

```

Here's a tested implementation (C#):

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

public class ShiftLine : MonoBehaviour
{
    [SerializeField] GameObject cube; //our voxel prefab
    List<Vector2> occupiedVoxels; //to record filled positions
    public enum LockedState
    {
        none,
        x,
        y
    }

    public LockedState state;

    void Start()
    {
        occupiedVoxels = new List<Vector2>();
        state = LockedState.none;
    }

    Vector2 oldMousePos, mousePos;
    float x, y;

    void Update()
    {
        mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        if (Input.GetKeyDown(KeyCode.RightShift))
        {
            // which way are we moving?
            if (Mathf.Abs(x - oldMousePos.x) > Mathf.Abs(y - oldMousePos.y))
            {
                y = oldMousePos.y;
                state = LockedState.y;
            }
            else
            {
                x = oldMousePos.x;
                state = LockedState.x;
            }
        }
        else if (Input.GetKeyUp(KeyCode.RightShift))
        {
            state = LockedState.none;
        }

        if (Input.GetMouseButton(0))
        {
            switch (state)
            {
                case LockedState.none:
                    x = mousePos.x;
                    y = mousePos.y;
                    break;

                case LockedState.x:
                    y = mousePos.y;
                    break;

                case LockedState.y:
                    x = mousePos.x;
                    break;
            }

            // round coordinates down
            x = Mathf.Floor(x);
            y = Mathf.Floor(y);

           // is this voxel position already occupied?
           // only drop voxel if position is empty.

            if(!occupiedVoxels.Contains(new Vector2(x, y)))
            {
                occupiedVoxels.Add(new Vector2(x, y));
                var go = Instantiate(cube);
                go.transform.position = new Vector3(x, y, 0);
            }
        }
        oldMousePos = mousePos;
    }
}

```

Demo:

---
Tags: unity, grid
---


# Question
Title: Changing sound pitch in sync with airplane propeller rotation speed
I'm trying to synchronize a rotating propeller with a engine sound by changing the sound's pitch.

I have a script attached to an airplane's propeller which, after the game starts, causes it to gradually increase rotation speed from slow to maximum.

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

    public class Spin : MonoBehaviour
    {
        public float RotationSpeed = 1;

        // Start is called before the first frame update
        void Start()
        {

        }

        // Update is called once per frame
        void Update()
        {
            transform.Rotate(0, 0, RotationSpeed, Space.Self);

            if (RotationSpeed < 10)
            {
                RotationSpeed += 1f * Time.deltaTime;
            }
        }
    }

```

On an empty gameobject I added an `AudioSource` and made its `AudioClip` an .mp3 sound effect of a propeller. To this gameobject I attached this script:

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

public class AudioExample : MonoBehaviour
{
    public int startingPitch = 4;
    public int decreaseAmount = 5;
    public Spin spin;

    private AudioSource _audioSource;

    void Start()
    {

        _audioSource = GetComponent<AudioSource>();
        _audioSource.pitch = startingPitch;
    }

    void Update()
    {

        if (_audioSource.pitch > 0)
        {
            _audioSource.pitch += Time.deltaTime * startingPitch / spin.RotationSpeed;
        }
    }
}

```

Screenshot of the propeller object :

and a screenshot of the gameobject with the `AudioSource` component:

The pitch in the audio source by default starts at value 1 and should be changed between the values of -3 and 3. The rotation speed in the Spin script is in other units.

The behavior I want is: as the propeller starts rotating slowly and increases to max speed, the audio source pitch will automatically change its value in sync with the propeller rotation speed.

However, the script AudioExample as it is now is making the pitch value to well exceed 3, in fact it goes up to 10. The calculation in the AudioExample script is wrong and I'm not sure how to correct it:

```
    _audioSource.pitch += Time.deltaTime * startingPitch / spin.RotationSpeed;

```

# Answer
Seems like there are some strange things going on in the AudioExample code.

first of all, the pitch parameter in AudioSource is a float not an int. It would make sense to have the variables that affect pitch also be floats.

As a starting point, I would simply update the AudioSource.pitch at the same time I am updating the propeller rotation speed. You'll need to scale the pitch range to the rotation speed range as well if I understand what you are trying to do.

Your pitch range is -3 to 3 and your rotation speed is 0 to 10, so this math should do the trick:

> *p* = *s* x (6/10) - 3

So, resulting code would look something like this:

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

public class Spin : MonoBehaviour
{
    public float RotationSpeed = 1;
    [SerializeField] AudioSource propellerSoundSource; //populate in inspector

    // Start is called before the first frame update
    void Start()
    {
        propellerSoundSource.pitch = -3f;
    }

    // Update is called once per frame
    void Update()
    {
        transform.Rotate(0, 0, RotationSpeed, Space.Self);

        if (RotationSpeed < 10)
        {
            RotationSpeed += 1f * Time.deltaTime;
            propellerSoundSource.pitch = (RotationSpeed * .6f) -3f;

        }
    }
}

```
> 2 votes

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


# Question
Title: Testing Message-Based Events using Unity's New Input System and InputTestFixture, getting unhelpful error
My player has an Action in the Input System `Move`, that takes a `Vector2` and moves the player based on that input. Straight-forward. I'm using the "Send Messages" behavior on my Player's `PlayerInput` component.

For the life of me, I can't figure out how to test if `OnMove` is being called effectively. Here's my most recent attempt, I've tried instantiating the player piecewise from a new game object, loading the player as a prefab, finding the player in the scene, doing any and all of these things in the test and in a setup test function, and I've gotten nowhere.

I have not even managed to get a Minimum Viable Example of this feature actually working. I'm sure I'm completely missing something, but don't know what it is.

**The Error**

```
Player_Should_Be_Able_To_Move (0.437s)
---
Unhandled log message: '[Exception] ArgumentOutOfRangeException: Cannot be negative
Parameter name: value'. Use UnityEngine.TestTools.LogAssert.Expect
---
UnityEngine.InputSystem.Users.InputUser.set_listenForUnpairedDeviceActivity (System.Int32 value) (at Library/PackageCache/com.unity.inputsystem@1.2.0/InputSystem/Plugins/Users/InputUser.cs:406)
UnityEngine.InputSystem.PlayerInput.StopListeningForUnpairedDeviceActivity () (at Library/PackageCache/com.unity.inputsystem@1.2.0/InputSystem/Plugins/PlayerInput/PlayerInput.cs:1686)
UnityEngine.InputSystem.PlayerInput.OnDisable () (at Library/PackageCache/com.unity.inputsystem@1.2.0/InputSystem/Plugins/PlayerInput/PlayerInput.cs:1721)
---
ArgumentOutOfRangeException: Cannot be negative

```

As far as I can tell, there's no reference to a line of code in my files that would help me isolate the issue.

**Test**

```
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Core;
using FluentAssertions;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
using UnityEngine.TestTools;

namespace Tests.PlayMode {
    public class PlayerTests {
        public class Physics {...}

        public class Animations {...}

        public class Movement : InputTestFixture {

            [UnityTest]
            public IEnumerator Player_Should_Be_Able_To_Move() {
                SceneManager.LoadScene("TestScene");
                yield return new WaitForSeconds(0.1f);

                InputSystem.RegisterLayout<Keyboard>();
                var keyboard = InputSystem.AddDevice<Keyboard>();

                var playerPrefabObject = Resources.Load("Player");
                var playerGameObject = (GameObject)Object.Instantiate(playerPrefabObject);
                var player = playerGameObject.GetComponent<Player>();

                yield return new WaitForSeconds(0.5f);
                player.Rigidbody.velocity.x.Should().Be(0);

                Press(keyboard.dKey);
                yield return new WaitForSeconds(0.1f);
                Debug.Log(player.MoveDir);
                Debug.Log(player.Rigidbody.velocity);
                player.Rigidbody.velocity.x.Should().BePositive();

                Release(keyboard.dKey);
            }
        }
    }
}

```

**Player**

```
using UnityEngine;
using UnityEngine.InputSystem;

namespace Core {
    public class Player : MonoBehaviour {
        public Rigidbody2D Rigidbody { get; private set; }
        public CapsuleCollider2D Collider { get; private set; }
        public Vector2 MoveDir { get; private set; }

        private void Start() {
            Rigidbody = GetComponent<Rigidbody2D>();
            Collider = GetComponent<CapsuleCollider2D>();
        }

        public void OnMove(InputValue value) {
            Debug.Log("OnMove called");
            MoveDir = value.Get<Vector2>();
            Rigidbody.velocity = MoveDir * 10f;
        }
    }
}

```

# Answer
> 1 votes
So, I think you're hitting a red herring with the error you're seeing. I'm unsure of exactly how Unity handles deleting objects in PlayMode tests if you don't manually control it with `Object.Destroy` in a TearDown step - my assumption is that it is disposed of when it goes out of scope of the test.

When I was hitting this error in my tests, it was because the `Player` `GameObject` was being destroyed after the input system had been torn down, which I assume was causing the input test framework to throw this device error.

My suggestion would be to try and manually control the object lifecycle:

```
public class Movement : InputTestFixture
{
    private GameObject _player;

    public override void SetUp()
    {
        base.SetUp();
        _player = Object.Instantiate(/* player prefab */)
    }

    public override void TearDown()
    {
        Object.Destroy(_player)
        base.TearDown();
    }

    [UnityTest]
    public IEnumerator Player_Should_Be_Able_To_Move()
        // Removed for brevity
    }
}

```

If you need the `WaitForSeconds` and thereby need the `UnitySetUp` / `UnityTearDown`, you'll need to manually instantiate and handle the `InputTestFixture` instead of inheriting from it, as the order of operations is

* `UnitySetUp`
* `SetUp`
* `Test`
* `TearDown`
* `UnityTearDown`

Alternatively, you could use LogAssert in any input tests that you write to either expect the error message or ignore all error messages, or but I would say this should only be a last resort, as you may end up hiding errors that would otherwise cause your tests to fail.

Resources:

# Answer
> 0 votes
The error mentions a parameter name "value". When you set MoveDir to value.Get(), MoveDir could be positive or negative. You then set Rigidbody.velocity to 10 times this. In Test, you say that the velocity should be positive, but it may be negative at times. This is what the error means by "cannot be negative". I hope this helps you fix your problem.

---
Tags: unity, c#, input, unit-testing, test-driven-development
---


# Question
Title: Movement system for thousands of entities
I want to implement a movement system for armies of multiple thousand units. However, I struggle to get the movement "stable" when there are more than a few hundred units.

**The problem:** When too many units move and start pushing against each other, the center of the army becomes "unstable" and jiggles around. This is especially noticeable when an army tries to move through a chokepoint or against a soft blocker.

For reference, the goal is a movement system like in *They Are Billions*: https://youtu.be/zYGTbt2vXtQ?t=788 (from 13:10). While I don't need THAT many entities, emphasis is on how smooth the zombies group/clump up when their path is blocked. No jiggling, just smooth pushing against a common front.

I tried impulse-based collision resolution, Verlet integration, and classical steering behaviors. However, I eventually always ran into the same issue. It seems that I am not able to properly stabilize the center of forces where most entities push into each other, but maybe I am just taking an incorrect approach.

Do you have an idea how to approach this or have resources on implementing such a system? If you need more information, please let me know.

**Some more information/constraints:**

* I really want to understand how to solve this, *"just use library XY"* unfortunately does not help
* Solution must not be tied to a specific game engine
* Movement is currently just constant velocity towards a common point for all entities
* Entity shape is always a circle (although of different sizes)
* Efficiency in general is important, *"just do 1000 substeps per iteration"* is not a solution

Cheers!

# Answer
> 2 votes
Myself, I'd solve this with a combination of flow field pathfinding and local avoidance.

First, the flow field: for each army, initialize a graph of map locations spanning the army and their goals (could be a grid, a navmesh, or whatever you like to use). Each node should initially store "infinite" distance to goal as its value. Then select the goal nodes - the places or targets that army should be pathing toward - and set those node values to 0, adding them to a queue of recently changed nodes.

While that queue is non-empty, take a node out, call it "parent", and iterate over its neighbours. If the neighbour's value is more than the parent's plus the distance between the parent and that neighbour, reduce it to that value and stuff it into the queue. (If your terrain has different traversal costs, traps the armies should try to avoid, etc., you can add this as a penalty to the distance)

When this iteration completes, you have a distance field that you can convert to a flow map: at each node, the flow direction points toward the neighbour with the least sum of value + edge cost (or an interpolation between two neighbours, if that makes sense for your graph structure). Now an army unit anywhere can just do a simple look up to find the best direction to move toward the army's goals.

The advantage here is the processing work scales with the size and density of your pathing graph, not the number of units. So you can support gobs of units, as long as you keep your map subdivisions reasonable.

You can also use the distance field to order your units from those closest to the goal to those farthest away, and iterate over them to update their positions in that order. This helps avoid bottlenecking: units in front have a chance to move out of the way before units behind them try to move.

(In case you're worried about the cost of sorting many units, note that the order will usually change very little from frame to frame, and does not have to be perfect to be of benefit. So you can store the units in almost-sorted order, and incrementally update it a bit each frame, so that it converges toward sorted order without ever needing to sort the whole list in one go)

Now you don't need to do any fancy force-based repulsion or anything like that. Each time it's a unit's turn to move, the units ahead of it are already at their final positions for the frame, so it can treat them as stationary obstacles. Use spatial hashing so you can find obstacles within one movement step of this unit quickly, without searching the whole map. You can alternate between moving units of opposing armies to neutralize any advantage one side gets from moving first.

The unit can now sample points in an arc with the radius of its movement step - directly in the flow field direction, and if that's obstructed, also check a little to the left and right. For each possible destination, check whether it's within the collision radius of another unit plus this unit's own collision radius - if so, backtrack the destination point to the circumference of that summed radius and try again. Of those non-intersecting points, choose the one with the lowest distance field value to path towards.

You can keep track of units that have moved less than their full speed in recent ticks, and increase how wide / how many times they scan for alternatives, so stalled units get more aggressive about trying to go around the obstacle, while unobstructed units just march forward without paying any extra cost to look around.

This type of approach should be jitter-free, since units only move "downhill" and collision influence only flows one way, and scale up to many thousands of units with the right graph/spatial hashing structures and cache-friendly data layout.

---
Tags: physics, algorithm, movement, collision-resolution, collision-avoidance
---


title: How to come up with game ideas?

text:
# Question
Title: How to come up with game ideas?
One thing that always stops me when I want to start making a game is having no idea what to do.

How can I get ideas for my game?

I mean realistic ideas for someone who is alone with the minimum resources (no money for assets, using free tools like Blender and Unity).

I will never stop being impressed by all new concepts, mechanics or wild game ideas of indie developers come up with, like making games out of random everyday objects. I wish I was able to do that.

* Do developers get their inspiration by looking at other games and trying to mix them or change the concept?
* Do they look outside trying to come up with what they wish was a game?
* Or do they simply walk around and try to imagine a game with whatever they see in real life situations?

What can I do to come up with better game ideas?

# Answer
There is unfortunately no one-size-fits-all answer for this question: it will be different for every game dev. We've set up a Wiki-style answer to help gather general advice.

---

One thing you should consider is **survivorship bias**. You're not seeing every game idea someone started working on. You're only seeing the ones:

* ...where the creator got far enough with the idea to share it
* ...where what they shared got popular enough to reach you through social media
* ...where what you saw was noteworthy enough for you to remember seeing it, etc.

So that means that the game ideas you remember seeing will skew very heavily toward the amazing/innovative/wow end of the spectrum, even if that's actually a very tiny fraction of these developers' total creative output.

Make enough small games and prototypes, and a few of them are bound to be good/clever. The best developers don't have better ideas than other folks, they just dive in and try things and and produce a lot of sketches/experiments/prototypes to explore different angles. Most of it is junk that gets thrown away. But with practice, they learn when to let something go or when to chase stuff that works. Sift enough silt, and you'll find a few grains of gold.

So, through that lens, and especially when starting out: **prioritize quantity over quality**. Paradoxically, racing through a tonne of garbage will help you learn more and take you farther than sitting in analysis paralysis trying to think of and polish that one perfect idea.

An old game development adage is "Your first 10 games will be terrible, so get them out of the way as fast as you can!"

---

**Cross-pollinate**: if you only look at existing games, you'll tend to make things that look like what you've seen before, or repeat the same mistakes. Spend some time doing something, anything else. Develop a non-gaming hobby, consume non-game media, cultivate non-game skills. Those outside influences will give you a unique perspective on life and your work, different from other players and developers, and that will inform your craft in big and small ways.

A great example of this is the much-lauded Nemesis System in Shadow of Mordor, that creates emergent narratives through your repeated encounters with orc chieftains and their movement through the ranks. In this GDC microtalk (starting around 50 minutes in), Michael de Plater discusses how this system was not created by just studying game narrative systems or the Lord of the Rings source material. Instead, the inspiration came from sports, and the rivalries that emerge between teams through the systemic interactions of tournaments and seasons.

---

Speaking of lenses, Jesse Schell's *The Art of Game Design* and its accompanying deck of lenses (available as a free mobile app) I find is a great source of inspiration.

The Art of Game Design: a Deck of Lenses (iOS)

The Art of Game Design: a Deck of Lenses (Android)
> 2 votes

---
Tags: game-design
---


# Question
Title: OBI Rope, Create a curve from list of Vector3 points
I am using a Unity Plugin Obi Rope to create rope-based mechanics. I am working on creating an obi rope curve through code and rendering rope on that curve. I am stuck at the moment where I can spawn points of the curve in the correct position but tangents are disturbed due to which the curve is irregular(as shown in the screenshot).  Following code focuses on generating curve for rope:

```
Vector3 tangentLS = default;
        for (int i = 0; i < ropeSaveData.ropeCurvePoints.Count; i++)
        {
            // Calculate control point positions and tangent vector:
            Vector3 currentPointPosition =
                generatedRope.transform.InverseTransformPoint(ropeSaveData.ropeCurvePoints[i]);
            if (i == 0)
            {
                Vector3 nextPointPosition =
                    generatedRope.transform.InverseTransformPoint(ropeSaveData.ropeCurvePoints[i + 1]);
                tangentLS = (nextPointPosition - currentPointPosition).normalized;
            }
            else if (i < ropeSaveData.ropeCurvePoints.Count - 1)
            {
                Vector3 previousPointPosition =
                    generatedRope.transform.InverseTransformPoint(ropeSaveData.ropeCurvePoints[i - 1]);
                Vector3 nextPointPosition =
                    generatedRope.transform.InverseTransformPoint(ropeSaveData.ropeCurvePoints[i + 1]);
                tangentLS = (nextPointPosition - previousPointPosition).normalized;
            }

            // Build the rope path:
            blueprint.path.AddControlPoint(currentPointPosition, -tangentLS, tangentLS, Vector3.up,
                0.1f, 0.1f, 1, filter, Color.white, "start_" + i);
        }

```

So mainly **AddControlPoint** is responsible for creating curve for obi rope.

Following is the method signature:

```
public void AddControlPoint(Vector3 position, Vector3 inTangentVector, Vector3 outTangentVector, Vector3 normal, float mass, float rotationalMass, float thickness, int filter, Color color, string name)

```

Additional information around this. I tried this with 2 points(vector3) and following code works perfectly fine since this curve is just a line but the above one is not a straight line it's a list of vector3 points.

```
 // Calculate control point positions and tangent vector:
        Vector3 startPositionLS = generatedRope.transform.InverseTransformPoint(start.position);
        Vector3 endPositionLS = generatedRope.transform.InverseTransformPoint(end.position);
        Vector3 tangentLS = (endPositionLS - startPositionLS).normalized;

        // Create the blueprint:
        var blueprint = ScriptableObject.CreateInstance<ObiRopeBlueprint>();
        blueprint.resolution = 0.5f;
        // Build the rope path:
        int filter = ObiUtils.MakeFilter(ObiUtils.CollideWithEverything, 0);
        blueprint.path.AddControlPoint(startPositionLS, -tangentLS, tangentLS, Vector3.up, 0.1f, 0.1f, 1,
            filter, Color.white, "start");
        blueprint.path.AddControlPoint(endPositionLS, -tangentLS, tangentLS, Vector3.up, 0.1f, 0.1f, 1, filter,
            Color.white, "end");

```

Helping note for readers here that are willing to help:

> Tangent length affects the curvature of the path, just line in any spline. Depending on how far away from each other your points are, using normalized tangents (with length 1) may be too much and the path will have a weird shape. Try reducing the length of the tangents, proportionally to the distance between points.

This is something which is useful but I am unable to actually transform this into a code.

# Answer
> 0 votes
Thank you @DMGregory for pointing me out in the right direction.

So earlier I was just normalizing the tangents with length 1 which was creating problems since as I mentioned in the question that tangent length affects the curvature of the path so I modified that by reducing the length of the tangents, proportionally to the distance between points.

The value 0.8 is something that worked(I liked the look of it) for me so basically, my thought process behind that is to keep 80% of the distance of 2 points instead of keeping 100% thus retaining the tangent between points.

Now it is working perfectly fine. Here's the updated code:

```
Vector3 tangentLS = default;
        for (int i = 0; i < ropeSaveData.ropeCurvePoints.Count; i++)
        {
            // Calculate control point positions and tangent vector:
            Vector3 currentPointPosition =
                generatedRope.transform.InverseTransformPoint(ropeSaveData.ropeCurvePoints[i]);
            if (i == 0)
            {
                Vector3 nextPointPosition =
                    generatedRope.transform.InverseTransformPoint(ropeSaveData.ropeCurvePoints[i + 1]);

                tangentLS = (nextPointPosition - currentPointPosition) * 0.8;
            }
            else if (i < ropeSaveData.ropeCurvePoints.Count - 1)
            {
                Vector3 previousPointPosition =
                    generatedRope.transform.InverseTransformPoint(ropeSaveData.ropeCurvePoints[i - 1]);
                Vector3 nextPointPosition =
                    generatedRope.transform.InverseTransformPoint(ropeSaveData.ropeCurvePoints[i + 1]);

                tangentLS = (nextPointPosition - previousPointPosition) * 0.8;
            }

            // Build the rope path:
            blueprint.path.AddControlPoint(currentPointPosition, -tangentLS, tangentLS, Vector3.up,
                0.1f, 0.1f, 1, filter, Color.white, "start_" + i);
        }

```

---
Tags: unity
---


# Question
Title: Scalable way to have interaction button place item on campfire
I have been wondering how I can place a bowl on a campfire in Unity using C#, similar to how it is done on Green Hell.

I currently have an inventory system set up where you can equip the item in your hands from the hotbar.

The reason I am asking this is because my current brute force method is to have the campfire find the player's bowl with `GameObject.Find` after it has been instantiated. The player can then press E at the campfire to place it on it.

It would obviously be silly to have the campfire find the bowl and any other item that is capable of going onto the campfire like meat or wood etc., so I'm wondering what would be a more scalable way to have this work with multiple items.

# Answer
The item being held by the player is a property *of the player*, so extend your player class to have a

```
public GameObject currentlyHeldObject;

```

And make sure your inventory system sets it as appropriate (or set it to `null` if your hands are empty).

Then from your campfire script, find the player *once* at startup and keep a reference.

```
MyPlayerController player;
void Awake() {
    player = GameObject.Find(...).GetComponent<MyPlayerController>();
}

```

In future your fire can reference `player.currentlyHeldObject`
> 0 votes

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


# Question
Title: How do I write unit tests in ECS when behaviors cause creation of deletion of entities?
I am writing a game using a custom ECS architecture. I recently had a chain of nasty bugs where fixing one bug caused regressions elsewhere. Being a software engineer by trade, I suppose that unit tests would allow me to fix these bugs more safely (and so faster) - but the approaches I'd usually take to unit testing seem to get tangled up in the ECS architecture.

For example:

* Items are entities (there is a component which marks an entity as an item)
* Some entities have inventories, so inventories are components.
* Some items can stack when picked up, where what was two entities on the ground becomes a single entity representing the stack if both are picked up.

I would like to create a test to cover this stacking behavior because I recently had bugs in that area. The scenario seems like a basic 1+1=2 test: Verify that an empty inventory that picks up two identical stackable items has a stack of two of that item afterward, however, running that test requires instantiating the ECS system because this interaction involves creating and deleting entities (the stacked item is a different entity than either of its constituent items).

Is this scenario not such a good candidate for unit testing after all, and I should write it as an integration test instead? (If so, is it a problem if I find that almost none of my components or systems can be meaningfully unit tested?) Should I reframe my thinking around unit tests and consider a test that covers Component+ECS as a "unit" test? Is the fact that I can't unit test this sort of scenario evidence of a messy code base that I should refactor?

# Answer
It is entirely normal for unit tests to involve **dependencies of the thing you are testing**. For example, you have probably written many tests that (directly or indirectly) invoke the memory allocator to allocate objects that you are going to test, or test data. That doesn't mean they're integration tests.

What you should do in this kind of situation is make sure that it is easy and concise to set up the ECS in a test, and to make assertions about what entities and components exist at the end. That way it is not tedious to write multiple tests, and the tests are focused on the thing being tested rather than cluttered with setup code. Hopefully, this will pay off many times over in writing tests for many components.
> 2 votes

---
Tags: entity-component-system, testing
---


# Question
Title: Compute the difference between two quaternions and iterate with the difference
I would like to solve this with quaternions:

```
A - B = C

for(int i = 0; i < 10 ; i ++){

  B += C/10

};

```

I want to get the difference (C) between two quaternions (A & B), and then add the difference to the subtrahend (B) multiple times.

Is there a way to do this? Or do I need to convert to eulerAngles?

# Answer
> 2 votes
Quaternion difference:

```
 C = Quaternion.Inverse(B) * A;

```

Quaternion division by a scalar:

```
 C_fraction = Quaternion.Slerp(Quaternion.identity, C, 1f/steps);

```

Quaternion increment:

```
 for (int i = 0; i < steps; i++) {
     B = B * C_fraction;
 }

```

Though a more idiomatic way to write this would be...

```
 for (int i = 0; i < steps; i++) {
     float progress = (i + 1) / (float)steps;
     interpolated = Quaternion.Slerp(start, end, progress);
 }

```

If you don't need every step to be exactly the same, `Lerp` also works in place of `Slerp`, but is a little cheaper. It takes smaller steps at the beginning and end of the interpolation and bigger steps in the middle.

Note that order matters, and expresses sequence of rotations, or which rotations should be performed relative to the parent/world axes (terms on the left) or using the object's local axes (terms on the right right).

Writing `C` as I did above, it's a local space rotation that needs to be multiplied on the right to have its intended effect: `B * C == B * Inverse(B) * A == A`.

Flipping the order of multiplication to `C * B` will not, in general, give me `A`. To get a difference for left-multiplication like that (applying C in parent/world space), I'd need to define `C` with `A` on the left too: `C = A * Inverse(B)`

---
Tags: unity, mathematics, rotation, quaternion
---