# Question
Title: Box collisions between vehicles in traffic pattern
I'm working on a traffic simulator. Right now, I have ways to manage 4-way stop intersections and a solution for efficiently determining which vehicles are colliding with one another. All vehicles operate independently of each other and will overlap/ignore any vehicles they pass.

I'm looking to build a way to resolve collisions between vehicles such that a `Vehicle` will follow the `Vehicle` in front of it. If a `Vehicle` stops at an intersection, any `Vehicles` that follow thereafter should stop and wait as well.

Below are the relevant components I already implemented:

* **`TileGrid`** containing road segments.
* **`TravelGraph`** graph of waypoints for `Vehicles` to travel along the `TileGrid`.
* **`CollisionTracker`** for efficiently determining which vehicles are colliding, i.e. O(1) lookup for `get_collisions(<vehicle_id>) -> List[<vehicle_ids>]`
* **`Intersection`** for determining which vehicles are waiting at an intersection and determining which `Vehicles` may pass through it.

The only seemingly-viable algorithm right now is:

1. Calculate velocities and position of all vehicles after tick
2. Determine which vehicles are in a collision
3. Determine which vehicles are in a "collision group" (e.g. if A collides with B, collides with C, then (A, B, C) are in a group)
4. Determine the order of the vehicles in each group based on their velocities (e.g. if A, B, and C are moving to the right and C is the rightmost, followed by B, followed by A, then the order is \[C, B, A\]).
5. Recalculate the positions of all vehicles, in order from front to back (e.g. C, B, A) such that they reside adjacent to, but not touching the `Vehicle` in front of them.

Problems with this solution:

* This requires a lot of recalculations. If there's a line of `n` vehicles waiting on a light, I'd effectively compute 2\*`n` positions per tick in addition to all other overhead for establishing groups, order, etc.
* If the vehicles are following each other around a turn, the logic for finding the "vehicle order" becomes more complex, adding on to the computations per tick.

Ideally moving the vehicles would require `n` calculations per tick.

I'm open to any/all suggestions here. I've tried building my code as modular as possible, so I'll happily rewrite large parts of it if there's a better architecture to solve this problem.

---

Below is the visual representation of the `TileGrid` (black), `TileGraph` (purple), and `Vehicle`s (circles).

# Answer
> 1 votes
This is commonly achieved by casting rays out from the front of your vehicle.

If your engine doesn't have an implementation of that, at a high level you could implement it manually as:

For each vehicle:

* Find all vehicles in a radius r (or just round up to a bounding square to save the maths)
* Determine whether a line projected forward from the vehicle passes through the bounding box of any target vehicle¹.
* Check line length \< radius (or don't bother an instead account for overshoot in the next step)
* Perform some scaling/clamping to get a "braking" factor.

The closer your vehicle gets to one in front, the more rapidly it will brake. Cars behind will follow in turn.

You'll probably want to fire 3 or 5 rays per vehicle in a fan pattern to handle corners/lane changes.

¹ For this step, it's basically just checking whether the ray crosses any of the 4 lines defining the bounding box, althoughn I'm guessing you have this already.

# Answer
> 0 votes
Couldn't you create an event collision box in or around your vehicles to detect if there is another vehicle in front of them?

Then, on that collision you could get the id of the leading car, and create the chain. Since it'll compute once, on\_collision\_enter, you won't have to keep constant track of every cars speed and velocity.

---
Tags: collision-detection, path-finding, python, collision-resolution
---


title: How do I storing a Score in each level?

text:
# Question
Title: How do I storing a Score in each level?
I have a problem when I store the DistanceScore to text, the problem is why the DistanceScore always storing at `text number 1`, this happens when I play at `level 2` which is the DistanceScore could be store in `text number 2`and so on, FYI I have 3 levels here.

here the preview

as you can see on the top of level 2 gameplay is distance so when i dead the distance saved and storing to text each level.

and when I go to the main menu the `Level 1`text updated instead of `Level 2`.

this is my script:

```
public Item[] _item;

public int mapIndex;

public enum ITEM_TYPE
{
    LEVEL
}

public ITEM_TYPE _type;

private void Start()
{
    loadItemInformation();
}

public void loadItemInformation()
{
    for (int i = 0; i < _item.Length; i++)
    {
        if (_type == ITEM_TYPE.LEVEL)
        {
            _item[i].bestScore.enabled = true;
            _item[i].distance.enabled = true;

            float distanceUi = PlayerPrefs.GetFloat("distance" + i.ToString());
            float value = PlayerPrefs.GetFloat("Time" + i.ToString());
            float minutes = Mathf.FloorToInt(value / 60);
            float seconds = Mathf.FloorToInt(value % 60);

            if (value == 0)
            {
                _item[i].bestScore.text = "No Record Yet";
            }

            else
            {
                _item[i].distance.text = "Unstopable ";
                _item[i].bestScore.text = "Best Time = " + string.Format("{0:00}:{1:00}", minutes, seconds);
            }

            _item[i].distance.text = "Long distance = " + distanceUi.ToString();

        }
    }
}

```

}

```
    [System.Serializable]
    public class Item
    {
        public TextMeshProUGUI bestScore;
        public TextMeshProUGUI distance;
    }

```

here the distance script:

```
#region Distance
[Header("Distance")]
public Transform checkPoint;
public TextMeshProUGUI distanceText;
M_GameManager _GameManager;
private float distance;
private float highDistance;
float index;
#endregion

private void Start()
{
    _GameManager = FindObjectOfType<M_GameManager>();
    checkPoint = GameObject.FindGameObjectWithTag("Finish").transform;
    distanceText = GameObject.FindGameObjectWithTag("DistanceTxt").GetComponent<TextMeshProUGUI>();
    index = (float)(PlayerPrefs.GetInt("Level"));// typo here i call it set and now I've fix it
}
index = PlayerPrefs.GetFloat("Level");
distance = (checkPoint.transform.position.x - transform.position.x);
    if (transform.position.x > checkPoint.transform.position.x)
    {
        distance = 0;
        //PlayerPrefs.SetFloat("distance" + index, distance);
    }
    if (_GameManager.isDead || _GameManager.isTimeout || _GameManager.fuelFinished)
    {
        PlayerPrefs.SetFloat("distance" + index, distance);
        PlayerPrefs.Save();
    }
    distanceText.text = distance.ToString("F1") + "m";

```

and for `_item[i].bestScore.text` this work to storing each level but why for the `distance` not working.

# Answer
> 0 votes
**index = (float)(PlayerPrefs.GetInt("Level"));** // typo here on the distance script i call it set not get and now I've fix it.

here the complete script:

```
public Item[] _item;
public int mapIndex;

public enum ITEM_TYPE
{
    LEVEL
}

public ITEM_TYPE _type;

private void Start()
{
    mapIndex = PlayerPrefs.GetInt("Level");
    Debug.Log(mapIndex);
    loadItemInformation();
}

public void loadItemInformation()
{
    for (int i = 0; i < _item.Length; i++)
    {
        if (_type == ITEM_TYPE.LEVEL)
        {
            _item[i].bestScore.enabled = true;
            _item[i].distance.enabled = true;

            float distanceUi = PlayerPrefs.GetFloat("distance" + i.ToString());
            float value = PlayerPrefs.GetFloat("Time" + i.ToString());
            float minutes = Mathf.FloorToInt(value / 60);
            float seconds = Mathf.FloorToInt(value % 60);

            if (value == 0)
            {
                _item[i].bestScore.text = "No Record Yet";
            }
            else
            {
                _item[i].bestScore.text = "Best Time = " + string.Format("{0:00}:{1:00}", minutes, seconds);
            }

            if (distanceUi == 0)
            {
                _item[i].distance.text = "Unstopable ";
            }
            else
            {
                _item[i].distance.text = "Long distance = " + string.Format("{0}", distanceUi);
            }
        }
    }
}

```

---
Tags: unity
---


# Question
Title: How do I generate platforms in a specific position in godot?
I am making a rogue-like game in Godot. Currently, I am stuck with the world generation. I know how to add children, but I am wondering if there is a way to add those children in a specific position. I also need to know how to add nodes to an array, and then choose one from the array to spawn.

# Answer
> 2 votes
## Placing Nodes from code

To change the position you need to…

* For a Node2D set the `position` or `transform2D`.
* For a Control set the `rect_position` (call `set_position`).
* For a Node(3D) set the `transform`.

If you have a `Node` (scene loaded and instantiated) you want to add to the scene, you can do that before you call `add_child` on the pregnant future parent `Node`.

---

## Adding and removing from arrays

To add an element to an `Array`, you can call on the `Array` either `push_back` (adds at the end, alias: `append`), `push_frost` (adds at the beginning), or `insert` (adds at the specified position).

To remove, you have `pop_back` (removes from the end, returns the value, null when empty), `pop_front` (remove from the beginning, returns the value, null when empty) and `remove` (removes at a given position, no return). You also have `erase` to remove by value instead of position. And `clear` to remove all.

To access an item (to read it or write to it with assignment) you can use square brackets (e.g. `array[2]`).

---

## On the ways to use arrays and scene nodes

If you want to make a `Node` pool, you can treat the `Array` as a queue. Pushing at one end and popping form the other. When you need an object, pop, if null create a new one. When you no longer need an object, push.

If you are making an `Array` for the objects that are in the scene… There is no need. You can add to the scene with `add_child`, remove with `remove_child`, get by index with `get_child` and so on.

Although, there is value in working with other structures such as a `Dictionary` or a multidimensional array (There are no true multidimensional arrays in GDScript, only jagged arrays (arrays within arrays, just like these parenthesis), but there are in C#), there are also third party oct and quad tree solutions.

---

To randomize your `Array`, call `shuffle` on it. For example, you could make an `Array` of `Node` that you will add, shuffle it, and then add them one by one in the resulting order.

There is also a `RandomNumberGenerator` type you could find useful in GDScript. For example, you could have an `Array` of `PackedScene` (scenes loaded, but not instantiated), and use the random number generator (call `randi_range`) to pick which to instantiate (or use a pool here) and then add to the scene. Don't forget to call `randomize` on the `RandomNumberGenerator` to seed it (this is usually done in `_ready`).

---
Tags: procedural-generation, platformer, random, godot, gdscript
---


# Question
Title: Unity's new Input system does not work after building the game
I've made a test project to test the new Input system pointers (touch and mouse), in the editor, everything works perfectly however when I build the game they don't. it's like there is not an input system. I'm not sure if I'm missing a setting or something.

I've made simple sean where the Ui displays the available devices, whether they're enabled or not, and if a touch or mouse click detected it will display general information about it.

this is how it works in the editor:

And this is the android version, note that button press still works:

I did not record the PC standalone version but it still does not respond.

this is the link to the build:
https://github.com/Venay/Input\_test

this is the code I used and couple of screenshots of my settings:

```
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.InputSystem;

namespace Testing.InputDebugger
{
    public class InputDebugger : MonoBehaviour
    {
        PointerInput pointerInput;
        public Text inputText;
        public Text deviceText;
        public Text buttonText;

        private void Awake()
        {
            pointerInput = new PointerInput();
            pointerInput.General.Pointer.performed += ctx => OnPointer(ctx.ReadValue<myCompositData>());
            pointerInput.General.Pointer.canceled += ctx => OnPointer(ctx.ReadValue<myCompositData>());

            string text = "";

            foreach (var S in InputSystem.devices)
            {
                text += S.device + " : " + S.enabled + "  \n";
            }
            deviceText.text = text;
        }

        private void OnEnable() => pointerInput.Enable();
        private void OnDisable() => pointerInput.Disable();

        public void OnPointer(myCompositData data)
        {

            string n = "\n";
            string Press = "Press: " + data.Press.ToString() + n;
            string PressCount = "Press Count: " + data.PressCount + n;
            string Position = "Position: " + data.Position + n;
            string Delta = "Delta: " + data.Delta + n;
            string Radius = "Radius: " + data.Radius + n;

            string Tap = "Tap: " + data.Tap + n;
            string StartPosition = "Start Position: " + data.StartPosition + n;
            string StartTime = "Start Time: " + data.StartTime + n;

            string Scroll = "Scroll: " + data.Scroll + n;

            inputText.text = Time.time + n + Press + PressCount + Position + Delta + Radius + n + Tap + StartPosition + StartTime + n + Scroll;

        }

        public void OnButtonPress() => buttonText.text = "Pressed at:\n" + Time.time;
    }

}

```

# Answer
> 1 votes
The was a bug in the input system where builds only supported "x86\_64". Go to your project settings and make sure that is explicitly set.

It is marked as fix now https://issuetracker.unity3d.com/issues/windows-ds4-controller-doesnt-work-in-built-scene

---
Tags: unity, input
---


title: What is an actor in game development?

text:
# Question
Title: What is an actor in game development?
I am reading a book about game development (Game Coding Complete, Fourth Edition) and there is an "Actors" topic which just explains how to use them briefly instead of explaining what it is.

Here's how the book introduces these actors:

> Games are full of objects that bring your world to life. A World War II game might be full of tanks and planes, while a futuristic science fiction game might have robots and starships. Like actors on a stage, these objects are at the heart of the gameplay. It seems fitting that we call them “game actors” because that’s exactly what they are.
>
> A game actor is an object that represents a single entity in your game world. It could be an ammo pickup, a tank, a couch, an NPC, or anything you can think of. In some cases, the world itself might even be an actor. It’s important to define the parameters of game actors and to ensure that they are as flexible and reusable as possible.
>
> There are as many ways for defining a game actor as there are games. Like everything else in computer programming, there is rarely a perfect solution.

I could only understand a very few things: it is an abstraction of everything in the game which can perform actions; it has it's own state; it's behaviour is usually implemented as a state machine. This is it. I am coming with systems programming background to the game development, and so I would like to know in general, what the **actor** is in game development meaning, how to use it, how it is used in general, what problem it solves, how and why. I would like the explanation to be such that a kid could understand.

I have tried to find this information on google but it heads me to another "actors" instead: concurrent programming most of the time or game actors but without a good explanation of it.

# Answer
> 38 votes
As you mentioned, an actor can be literally anything; trees, NPCs, buildings, etc. A similar term is "entity". It doesn't need to have a behaviour in the traditional sense, it can be static.

It's just a way to say "an object in the game".

# Answer
> 14 votes
By my understanding the term is a side effect of hiring writers to make the stories for games. Since they usually come from theater or screen, they are accustomed to the terms `Actor` and `Prop`. `Actors` being things that move and play a real role in the game, and `Props` being things like trees, buildings, etc.

From my early days of coding in college, before we were allowed to use an engine like Unity, we had to code our own engine. `Actor` was an abstract base class that had a transform, empty lifecycle functions, and a function called `Act()` which was our version of Unity's `Update()`.

Our main game loop basically followed:

```
for(Actor actor in actors)
{
   actor.Act();
}

```

Most engines use the Entity concept, so from your reading, just translate `Actor` as `Entity` in your head and you'll be fine.

# Answer
> 1 votes
Others already gave good answers, but i wanted to add and clarify couple of things. There are various approaches to architecture and it may seem like Actor is the same as Entity or GameObject, but there are pretty big differences between them in practice.

* Actor indeed lives in a Scene and acts, "living in a scene" means that it has some positional data attached to it, be it matrix components or a Transform for managing matrices, an object cant have a meaningful position representation in a scene without it.
* Different architectures solve the composition over inheritance problem differently. Unreal4 uses a mix of component model and inheritance with its Actor, as it has a "root" class extending Actor and representing a "thing" in the scene, (look at AStaticMeshActor for example), and a bunch of supporting components. GameObject in unity does not allow extension and is purely a collection of components, which makes it agnostic to its use, which is great for scene graph related problems. Entity in ECS in its purest form, is absolutely agnostic to its use and doesn't have to have any transformation data or behavior, and so its the most "low level" approach. These approaches have deep implications on how you treat your objects in game code.

An example would be skeletal meshes:

* Unreal4 has a skeleton actor, which represents the bones with independent FBoneNode type.
* Unity represents bones by using GameObjects themselves, which allows you to intuitively operate on them (attaching components right in editor for example).
* ECS approaches may use any of the above or not have any bones at all, since performance is the key over there, its most likely the whole animation will be baked into a texture and played on geometry shader.

So to summarize my ramblings: Traditionally Actors combine data and behavior (and most likely inheritance), and optionally have some form of components attached they are very convenient/intuitive to reason about and to work with as they represent a concrete "thing", GameObject may do exactly the same, however nowadays popularized by Unity approach they will most likely only act as a component container and have no behavior, but components do. And ECS Entity would act as a key id for a group of independent components that can represent anything through data components with no behavior attached (its implemented by systems which act on them).

As with any architecture what approach for your "Actor" you chose is best decided by what fits your game better.

---
Tags: architecture, terminology
---


# Question
Title: Java - how to reduce iteration loops for enemies
I have many places in my code where I'm iterating through the enemies array and it seems to me it could be optimised somehow, but I can't see how it can be done. For example these two loop checks:

```
private void arc1() {
    for (Enemy e : gs.getEnemies())
        if (e.distanceFromPlayer() < 32 && !e.seen) {
            arc1.setActive(true);
            return;
        }
    arc1.setActive(false);
}

private void arc2() {
    for (Enemy e : gs.getEnemies())
        if (e.distanceFromPlayer() < 24) {
            arc2.setActive(true);
            return;
        }
    arc2.setActive(false);
}

```

They're both just checking the distance from the player with one having an extra condition and a different distance. Is there a way to combine them into one? I tried doing it but it didn't work correctly.

Will it actually give any benefit performance wise to combine into one in any case? It does look like duplicate code but not sure if there would actually be any performance benefit.

# Answer
If it is just about combining the code, something like this should have the same result with only one loop.

```
private void combinedArc() {
    arc1.setActive(false);
    arc2.setActive(false);
    for (Enemy e : gs.getEnemies()) {
        float distanceFromPlayer = e.distanceFromPlayer();
        if (!arc1.isActive() && distanceFromPlayer < 32 && !e.seen) {
            arc1.setActive(true);
        }
        if (!arc2.isActive() && distanceFromPlayer < 24) {
            arc2.setActive(true);
        }
        if (arc1.isActive() && arc2.isActive()) {
            return;
        }
    }
}

```
> 1 votes

# Answer
These two examples in particular seem to search for entities in a given area. Queries like that can often be sped up considerably by storing entities (or at least references to them) in a data-structure optimized for spacial queries.

Two common options are various variants of spacial trees or spatial hashing.

Example of options for spacial trees are quadtrees or k-d trees. What most trees have in common is that it is pretty quick to get all entities within an given rectangular area, but it's usually a rather expensive operation to move entities, because doing so can require to recalculate large sections of the tree. That makes them most useful for immobile entities.

Spatial hashing means that you divide your game world into a grid of rectangular sections and then have a list for every section with the entities which are currently in that section. You store those sections in a 2-dimensional array, so acquiring a section by coordinates is a very fast operation. When you want to check against all entities around the player, you only need to iterate the lists of the section the player is in and adjacent sections.
> 0 votes

# Answer
I was able to get my own previous attempt at this combined function to work by moving the `setActive(false)` to the top as in the answer from Zibelas, so just for completeness, am adding it as an alternative answer too.

```
private void combinedArc() {
    arc1.setActive(false);
    arc2.setActive(false);
    for (Enemy e : gs.getEnemies()) {
        float distanceFromPlayer = e.distanceFromPlayer();
        if (distanceFromPlayer < 24)
            arc2.setActive(true);
        if (distanceFromPlayer < 32 && !e.seen) {
            arc1.setActive(true);
            return;
        }
    }
}

```
> 0 votes

---
Tags: java, game-loop
---


# Question
Title: Why it's not adding gaps between the prefabs?
gap value is 7 but all the prefabs Instantiated at 0,0,0

```
private void GenerateLines()
    {
        for (int i = 0; i < numberOfLines; i++)
        {
            var prefab = Instantiate(linesPointsPrefab, Vector3.zero, Quaternion.identity);

            prefab.transform.position = new Vector3(prefab.transform.position.x * gap, prefab.transform.position.y * gap, prefab.transform.position.z * gap);
            prefab.transform.parent = linesParent.transform;
        }
    }

```

After added gaps between the prefabs it's creating lines using linerenderer between the prefabs. then when I drag the prefabs around it's making curved lines and then the NAVI object can move on the curved lines :

It was working before too but I wanted to generate the curved lines automatic. So with the gaps I can drag the prefabs around and make curved lines and next I will add automatic random positions option too so it will make the curved lines already.

# Answer
This line:

```
var prefab = Instantiate(linesPointsPrefab, Vector3.zero, Quaternion.identity);

```

Creates an *instance* of the prefab at (0, 0, 0).

(I'd recommend calling this variable "instance" or "line" or something because it's *not* a prefab now, it's a scene object)

Then this line:

```
prefab.transform.position = new Vector3(prefab.transform.position.x * gap, prefab.transform.position.y * gap, prefab.transform.position.z * gap);

```

Multiplies the `x`, `y`, and `z` of its position by `gap`.

But `x`, `y`, and `z` are all zero, since you spawned this instance at `Vector3.zero`

```
0 * gap = 0

```

You might have wanted to combine these lines into one, something like this:

```
var instance = Instantiate(
                  linesPointsPrefab,
                  Vector3.right * gap * i,
                  Quaternion.identity
               );

```

This says "place each new instance exactly `gap` units further to the `right` than the one before it" (change the direction if you want them stacked vertically or in the z axis, etc)
> 1 votes

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


# Question
Title: Does gimbal lock occur only when a combination of local and world rotation axis are used?
In all the explanations I've seen of gimbal lock, they always refer to the fact that when performing a series of rotations on all axes, it is possible that one rotation might end up aligning an axis with another which causes us to lose a degree of freedom. This never made sense to me since a rotation around e.g. the LOCAL\_RIGHT axis will rotation the whole LOCAL\_BASIS, no alignment happens. The only explanation I've seen that made sense was this one by DMGregory where it clearly explains that gimbal lock occurs when we e.g. change the yaw using the local basis and the pitch using a world basis.

My question is: Is that the only scenario where gimbal lock occurs or am I missing something? I also thought that quaternions help avoid gimbal lock but again, I'm missing something here because it seems to occur regardless of the rotation representation method (euler/quaternion).

# Answer
Gimbal lock occurs when your internal structure for storing/composing rotations uses a gimbal model:

Image via Wikipedia, attributed: "By Lookang many thanks to Fu-Kwun Hwang and author of Easy Java Simulation = Francisco Esquembre - Own work, CC BY-SA 3.0"

That is, when you construct your orientation as a sequence of component rotations with their own persistent angle, composed together.

When you do that, the resulting axis that a component rotates around depends on where it sits in the composition sandwich, and how the other components are twisting its local frame of reference.

Your rotations don't need to be "global" or "local" per se, but rather "composed" where you track and update a persistent value for two or more separate rotations - in any coordinate space at all - then combine them together. The value of the outer one changes the effect of the inner one.

When you use **Euler angles / Tait-Bryan angles**, the gimbal model is almost automatic. It's built right into the coordinate conventions you're using.

For example, in Unity, a rotation formed with angles `(pitch, yaw, roll)` is equivalent to the following three-step composition:

```
Quaternion rotation = Quaternion.AngleAxis(yaw, Vector3.up)        // Outer gimbal.
                    * Quaternion.AngleAxis(pitch, Vector3.right)   // Middle gimbal.
                    * Quaternion.AngleAxis(roll, Vector3.forward); // Inner gimbal.

```

So if `pitch` is +- 90, then the inner gimbal's axis (local `z`) is turned until it's parallel to the outer gimbal's axis (parent `y`), and you have gimbal lock.

The angle triplet presentation misleads us into thinking these three angles are independent, like the three components of a translation vector. But they aren't truly. So if we store our rotation as 3 angles and add/subtract increments from them, they can eventually wander into a gimbal configuration where those increments do something very different than we intuitively expect!

Note that the gimbal lock is still there, even though we rephrased the multiplication in terms of quaternions. So that's the sense in which "quaternions don't avoid gimbal lock": they don't retroactively erase gimbals that you already baked into your model for how your application stores/updates its rotations.

But there is a sense in which **quaternions *do* help avoid gimbal lock**. That is: they don't *make* us construct our rotations from stacked yaw pitch and roll components, the way that Euler/Tait-Bryan angle approaches lure us into.

Instead of storing three persistent *angles* and adding to them separately (gimbals), we can store one persistent *orientation* and update it all at once.

```
Quaternion newWorldOrientation = oldWorldOrientation * localIncrement;

```

Now we're not relying on three separate angle variables (gimbals) tracking a persistent state. Our state is represented by a single quaternion, which treats all rotations uniformly - it is "gimbal-free".

Note that here, we sill have a combination of local and world rotations, but without creating gimbal lock.

We can do the same thing with Euler angles even - it's just a bit more convoluted:

```
// Encode the angles into a form that we can compose "gimbal-free".
oldRotationMatrix = MatrixFromEuler(currentEulerAngles);

// Do the composition as a whole, rather than one sequenced step per gimbal.
newRotationMatrix = oldRotationMatrix * localIncrementMatrix;

// Decode back to a (potentially *very* different) angle triplet.
currentEulerAngles = newRotationMatrix.eulerAngles;

```

We can even use angles to compute our local increment:

```
localIncrement = Quaternion.Euler( Input.GetAxis("Vertical") * -rotationSpeed * Time.deltaTime,
                                   Input.GetAxis("Horizontal") * rotationSpeed * Time.deltaTime,
                                   0);

```

Just note that here again, we're not storing a persistent yaw and adding/subtracting an increment to it each frame. Instead, we're composing-together just our incremental angle changes (which is reasonably safe since the increment on any single frame will be close to zero), then applying that change *as a whole* to our persistent rotation state - not composing it one gimbal at a time.
> 5 votes

---
Tags: rotation, quaternion, gimbal-lock
---


title: Add Camera Dynamically?

text:
# Question
Title: Add Camera Dynamically?
I have a "A1" scene, and from there, I want to create a new scene "A2" on button click and then I want to load the same scene. Creating a scene can be done with,

```
Scene NewScene = SceneManager.CreateScene("A2");

```

But this scene is an empty scene and as it is not added in build settings so I used

```
EditorSceneManager.LoadSceneInPlayMode

```

which would allow me to load scene without having it in build settings. Till here it is going well but now how do I add the maincamera in this new scene programmatically? I have tried something like

```
 public void CreateNewScene()
    {
        Scene NewScene = SceneManager.CreateScene("A2");
        EditorSceneManager.LoadSceneAsyncInPlayMode("A2",new LoadSceneParameters {loadSceneMode = LoadSceneMode.Single});
        LoadCamera();
    }

public void LoadCamera()
    {
        Camera camera = gameObject.AddComponent<Camera>();
        Instantiate(camera, new Vector3(0, 0, 0), Quaternion.identity);
    }

```

after the new scene is loaded.

# Answer
Maybe look into passing the existing camera between scenes using a DontDestroyOnLoad() script on your main camera.

This will ensure the whole GameObject is preserved.

Example script for your main camera:

```
void Awake()
{
    DontDestroyOnLoad(transform.gameObject);
}

```
> 0 votes

---
Tags: unity, camera, scene, scenemanager
---


title: Web Game Security - AntiBot

text:
# Question
Title: Web Game Security - AntiBot
I'm going to develop a real-time browser game using NodeJS in backend for a fast WebSocket, but I'll both prevent bots and other cheats, so my frontend JS might be very advanced.

I'm experienced with developing bot scripts, so I already know that I have to prevent all scripting methods for automating the game (clicking elements, using in-game functions, and so on), but to do that, I have to keep the WebSocket in an anonymous function where the whole game script will be.

Is there a good way to verify that the WS connection is in the official script in case cheaters would like to find a way to stop it to run a modified script?

### My current ideas, might not be the best?

* Generate the HTML with a script with a unique ID from the backend that the backend will accept only once, and other connections using this ID will just be rejected
* Same as above, but push the ID through headers (might improve performance when comparing)
* Bind the WS handshake value to their IP in the backend (will not allow multiple users on same IP, and will require the backend to unbind the IP before it can be used again - will easily be a problem)
* Captcha, I know it can be pushed like every 10 min, but I don't want to use captcha after the login has been verified because the game will require the player to be able to do actions fast in some cases (to survive)

### Why so complicated?

I've tried 2 other web games of same category, and another game.

The first was full of issues like latency and UI issues, so it was pain to play. The latency was unstable, but actions was done anyway, no matter if I wasn't aware about it before it was too late, but I'm pretty sure this game uses SSE instead of WS.

The 2nd game was too annoying because it had captcha way too often, like every 10 min. The 3rd game too, it sent captcha way too often. I think that it's okay with a captcha to verify login and registration, but when playing, captchas will make players leave because it's annoying

# Answer
> 1 votes
With web - accept as a fact "Any client is a potential cheater".

If you have any game logic on the frontend - nothing will save your game from the cheaters.

If you move all the logic to the server (Or duplicate logic and make the server always arbitrary right) and can prevent any attempts to compromise WebSocket messages (like sending invalid JSON to crash the server) - it's more than enough. And practically all you can do.

**Don't try to bind IP to the client**. For your server, my IP and IP of my GF machine will be the same.

**WSS (SSL)** \- also mush have. Glad we have `lets-encrypt` now in 2k20.

**Don't bother with super-complex HTML generation.** It gives nothing and guarantees nothing. Learn about JWT tokens.

**CAPTCHA is awful.** With all the above you don't need a captcha. In fact, with `captcha pushed like every 10 min` the only thing you can achieve - it 0 players online.

---
Tags: html5, node.js, websocket
---


# Question
Title: How to create terrain made of small tiles?
The terrain in my game must be created using tiled assets. I have unique textures for each tile (all with the same height and width that can be used to compose the terrain) and the information of each map is baked in binary files; these binary files contains each tile height and texture.

I'm thinking about creating the terrain at runtime (or create a tool to bake the terrains in unity's proper formats). Each tile would be an mesh composed by 2 triangles. This way I can represent individually each tile and associate a unique tile texture for each tile. My concerns is about performance as it will end up with several different meshes just for the terrain.

Am I thinking in the right direction? Is there other better way to implement a tiled terrain like this in Unity3d?

# Answer
Whether performance is an issue depends on the size and quantity of the tiles. If the environment is 10x10 tiles, there shouldn't be any performance issues. If the environment is 1000 x 1000 tiles, spawning 1 million tiles at once is probably going to kill performance.

If the map is very large (in terms of number of tiles) but only a small portion of it is visible at a time (e.g. due to a top-down camera angle), you can use a pooling system. E.g. say the map is 1000 x 1000 tiles but only 10 x 10 tiles are visible at once. You could spawn a 12 x 12 block of tiles, which gives you 1 row of padding on each side. When the camera moves towards one edge of the screen, you move the tiles from the opposite edge of the screen over to create the new row of tiles that's coming into view.

Here's a diagram with a 2x2 viewable area and 1 row of padding around each edge.
> 1 votes

---
Tags: unity, terrain-rendering
---


# Question
Title: How can I change the script so it will not be with a while loop inside Update or using coroutine instead?
The script is working fine as it is and I don't fell any performance problems and yet I wonder if it's a good idea to run a while loop inside the Update function ?

The idea is to be able to move an object over a curved lines with a lot of positions in any speed. So I'm calculating how much positions there is next each time and it's working fine I just wonder about the while in the update.

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

public class MoveOnCurvedLines : MonoBehaviour
{
    public LineRenderer lineRenderer;
    public float speed;
    public bool go = false;
    public bool moveToFirstPositionOnStart = false;

    private Vector3[] positions;
    private Vector3[] pos;
    private int index = 0;
    private bool goForward = true;
    private List<GameObject> objectsToMoveCopy = new List<GameObject>();

    // Start is called before the first frame update
    void Start()
    {
        pos = GetLinePointsInWorldSpace();

        if (moveToFirstPositionOnStart == true)
        {
            transform.position = pos[index];
        }
    }

    Vector3[] GetLinePointsInWorldSpace()
    {
        positions = new Vector3[lineRenderer.positionCount];
        //Get the positions which are shown in the inspector
        lineRenderer.GetPositions(positions);

        //the points returned are in world space
        return positions;
    }

    // Update is called once per frame
    void Update()
    {
        if (go == true)
        {
            Move();
        }
    }

    void Move()
    {
        Vector3 newPos = transform.position;
        float distanceToTravel = speed * Time.deltaTime;

        bool stillTraveling = true;
        while (stillTraveling)
        {
            Vector3 oldPos = newPos;
            newPos = Vector3.MoveTowards(oldPos, pos[index], distanceToTravel);
            distanceToTravel -= Vector3.Distance(newPos, oldPos);
            if (newPos == pos[index]) // Vector3 comparison is approximate so this is ok
            {
                // when you hit a waypoint:
                if (goForward)
                {
                    bool atLastOne = index >= pos.Length - 1;
                    if (!atLastOne) index++;
                    else { index--; goForward = false; }
                }
                else
                { // going backwards:
                    bool atFirstOne = index <= 0;
                    if (!atFirstOne) index--;
                    else { index++; goForward = true; }
                }
            }
            else
            {
                stillTraveling = false;
            }
        }

        transform.position = newPos;
    }
}

```

# Answer
**Edit:** This solution assumes the points are far enough apart that it will take multiple frames to travel from one point to the next. There's also some loss of speed when our object reaches the next point. This solution probably is not suitable if the points on the line are extremely close together and we'll be passing one or more waypoints each frame. The original code is probably better in that case.

---

Your move function is more complicated than it needs to be. The while loop is unnecessary. Here's a simplified version of the function:

```
void Move()
{
    float distanceToTravel = speed * Time.deltaTime;
    Vector3 oldPos = transform.position;
    Vector3 newPos = Vector3.MoveTowards(oldPos, pos[index], distanceToTravel);
    if (newPos == pos[index]) // Vector3 comparison is approximate so this is ok
    {
        // when you hit a waypoint:
        if (goForward) {
            bool atLastOne = index >= pos.Length - 1;
            if (atLastOne) index--; goForward = false;
            else index++;
        } else { // going backwards:
            bool atFirstOne = index <= 0;
            if (atFirstOne) index++; goForward = true;
            else index--;
        }
    }

    transform.position = newPos;
}

```

You can use a coroutine but I don't think it's necessary in this case.
> 1 votes

# Answer
Try changing your `Move()` method into a Coroutine...

```
private IEnumerator Move() {
    //Your code until
    //
    while (stillTraveling) {
        //All your per-step code up until the end of the loop
        ...
        transform.position = newPos;
        yield return new WaitForFixedUpdate(); // Wait for the physics tick
    }
}

```

Start it running by calling `StartCoroutine(Move());`

Every time there's a `yield return`, control will return to Unity. What you return determines how long Unity will wait before picking up again at the next line.

"Fixed Update" is the clock tick used by the physics engine, hence `new WaitForFixedUpdate()`. Others exist, eg you can return `null` to wait for the next frame.

As mentioned by DMGregory, you should only invoke this once.

You can do that using a simple boolean to track if it's running. More usefully, `StartCoroutine` returns an objec of type Coroutine, so you can hold on to a reference..

```
Coroutine mover;
mover = StartCoroutine(...);

```

You can then use `mover` to cancel a running routine...

```
StopCoroutine(mover);

```

See https://docs.unity3d.com/ScriptReference/Coroutine.html for more information
> 1 votes

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


# Question
Title: How can we sell rights to our computer game
We have an indie team that created a game on PC using Unity. We created the game for a long time and everything was exciting. We just don't even have money for advertising.

We had to borrow $100 for steam direct to release the game into early access. Since there was no money for advertising, the game collected only $66. But we did not receive them either, due to the fact that payments from Steam come only when income is above $100.

I'm looking for a way to sell the rights to this computer game to recoup our costs. We are so desperate that we are ready to sell all the rights to the game together with source code (The game was created for more than two years).

How can we go about finding a buyer for this game?

# Answer
To sell the rights to something, you first have to have rights to sell. Have you filed formal government paperwork to register copyright and trademark for your game? If not, you probably still have some automatic copyright protection in most countries, but it will be a lot more difficult to sell. If you can't afford advertising or a $100 fee on Steam, you may not be able to afford to file the paperwork for registering copyright/trademark.

Next, you have to find a buyer who is interested in purchasing the rights and sees a potential for profit from the purchase. There's no guarantee that anyone will want to buy the rights to your game. Most indie games are not exceptional and would have a hard time finding a buyer. There can also be underlying issues, such as poor-quality code or badly organized files, that affect the value proposition.

I think a good general rule of thumb is, if you have to go looking for a buyer, you probably can't expect much of a payout. If a potential buyer contacts you on their own initiative, that shows they are very interested in the game and see a lot of profit potential; then they're more likely to pay you something worthwhile. However, this is extremely unlikely to happen unless you have had enough success for word of your game to spread around. This takes you back around to the advertising problem - you need to advertise your game so it has more players so that you can show that the rights to the game are worth buying.

Third, you'll need a lawyer to help you with the selling process. If you try to go into a potential sale without a lawyer, the buyer is going to run you through the wringer and you'll be lucky to walk away from the deal with pocket change. However, if you can't afford advertising or a $100 fee, you probably can't afford a lawyer (unless they're willing to work on commission, which they won't be unless they see actual profit potential out of working with you).

If you have a formal business (with employees/salaries/revenue), you might consider asking your bank for a business loan to use for marketing. Otherwise, your best bet is to try to market your game on forums and social media (e.g. create a Twitter account, Instagram account, and Facebook page, and post regularly about the game).

If your game has a low score on Steam, you're probably already sunk. Nobody is going to want to buy the game on Steam *or* buy the rights to the game from you if the game has a bad score. Your best avenue would be to release some updates that address complaints that players have about the game, and put it on mega sale to try to draw in some new players who are willing to try out a game with a low score if it's very cheap.
> 5 votes

---
Tags: business, intellectual-property
---


# Question
Title: Why the random positions are not random?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteAlways]

public class GenerateCurvedLines : MonoBehaviour
{
    public GameObject linesPointsPrefab;
    public GameObject linesParent;
    [Range(3, 100)]
    public int numberOfLines;
    [Range(5, 50)]
    public int gap;
    public bool randomLinesPositions;
    public bool generateLines;
    public bool clearPositions;

    private List<Vector3> randomPositions = new List<Vector3>();
    private GameObject instance;

    // Start is called before the first frame update
    void Start()
    {
        if (randomLinesPositions)
        {
            for (int i = 0; i < numberOfLines; i++)
            {
                randomPositions.Add(new Vector3(UnityEngine.Random.Range(5, 50), UnityEngine.Random.Range(5, 50), UnityEngine.Random.Range(5, 50)));
            }
        }

        GenerateLines();
    }

    // Update is called once per frame
    void Update()
    {
        if (clearPositions)
        {
            var lr = GetComponent<LineRenderer>();
            lr.positionCount = 0;

            clearPositions = false;
        }

        if (generateLines)
        {
            GenerateLines();

            generateLines = false;
        }
    }

    private void GenerateLines()
    {
        for (int i = 0; i < numberOfLines; i++)
        {
            randomPositions.Add(new Vector3(UnityEngine.Random.Range(5, 50), UnityEngine.Random.Range(5, 50), UnityEngine.Random.Range(5, 50)));

            if (randomLinesPositions)
            {
                instance = Instantiate(
                      linesPointsPrefab,
                      randomPositions[i],
                      Quaternion.identity
                   );
            }
            else
            {
                instance = Instantiate(
                      linesPointsPrefab,
                      Vector3.right * gap * i,
                      Quaternion.identity
                   );
            }

            instance.transform.parent = linesParent.transform;
        }
    }
}

```

At this part I'm trying to Instantiate random positions of the prefabs but each time I check true the flag generateLines it's Instantiating the prefabs at the same positions instead each time to Instantiate them in a new random positions. It's like it's Instantiate once random positions and then using this positions each time and not Instantiating new random positions.

```
randomPositions.Add(new Vector3(UnityEngine.Random.Range(5, 50), UnityEngine.Random.Range(5, 50), UnityEngine.Random.Range(5, 50)));

                if (randomLinesPositions)
                {
                    instance = Instantiate(
                          linesPointsPrefab,
                          randomPositions[i],
                          Quaternion.identity
                       );
                }

```

# Answer
> It's like it's Instantiate once random positions and then using this positions each time and not Instantiating new random positions.

That's exactly what your code tells it to do. `randomPositions` is a member variable, so any values you add to it are going to stay there unless you overwrite or remove them. You first do this from `Start()`:

```
for (int i = 0; i < numberOfLines; i++) {
    randomPositions.Add(new Vector3(UnityEngine.Random.Range(5, 50), UnityEngine.Random.Range(5, 50), UnityEngine.Random.Range(5, 50)));
}

```

You've already filled the list with some values. These values are never cleared or overwritten in your code.

Later you do this:

```
for (int i = 0; i < numberOfLines; i++) {
    randomPositions.Add(new Vector3(UnityEngine.Random.Range(5, 50), UnityEngine.Random.Range(5, 50), UnityEngine.Random.Range(5, 50)));

```

You're calling `Add()` here, so it's adding new random values to the end of the list. Your list of positions just keeps getting longer and longer, but the elements in each index never change.

The list is pointless and is just wasting memory. Write your code like this:

```
if (randomLinesPositions) {
    var position = new Vector3(UnityEngine.Random.Range(5, 50), UnityEngine.Random.Range(5, 50), UnityEngine.Random.Range(5, 50));
    instance = Instantiate(
        linesPointsPrefab,
        position,
        Quaternion.identity
    );
}

```
> 2 votes

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


# Question
Title: How to create an illustrator/photoshop-like pentool for creating bezier curves in Unity
I found a very useful bezier curve creation code here, which I am using. I need to create complex segmented bezier curves so I want update the code to create illustrator/photoshop-like pen tool bezier curves. This video shows how the pentool behaves.

Please note that instead of creating a quadratic bezier curve with the first two anchor points (as shown in the video) I would rather prefer a cubic (as in the linked code example).

The following are features I've realised of the illustrator/photoshop pen tool that are necessary for replication in Unity.

* all anchor/control points are created at the same mouse point on the first click (object is created on the first click)
* as the mouse point is moved from the first click (not pressed) the control points fall in with the two anchor points to create a straight line (cubic curve)
* when the mouse is clicked and dragged (any distance from the first click) a control points move away from the straight line to form a curve based on the direction of the drag, they also increase in length as the drag increases in distance from the second click.
* the path should be closed when the first anchor point is re-selected during the curves creation

From the code below I created all my initial 4 points at the same point (I don't know how to click in the scene view to have game object created at the click point). I'm also not sure how to move the mouse point to drag the other anchor and click it to manipulate the control points.

Here is the code I've written so far:

BPath:

```
[System.Serializable]
public class BPath
{

    [SerializeField, HideInInspector]
    List<Vector2> points;

    [SerializeField, HideInInspector]
    public bool isContinuous;

    public BPath(Vector2 centre)
    {
        points = new List<Vector2>
    {
        centre+Vector2.left,
            centre+Vector2.left,
            centre+Vector2.left,
            centre+Vector2.left
    };
    }

    public Vector2 this[int i]
    {
        get
        {
            return points[i];
        }
    }

    public int NumPoints
    {
        get
        {
            return points.Count;
        }
    }

    public int NumSegments
    {
        get
        {
            return (points.Count - 4) / 3 + 1;
        }
    }

    public void AddSegment(Vector2 anchorPos)
    {
        points.Add(points[points.Count - 1] * 2 - points[points.Count - 2]);
        points.Add((points[points.Count - 1] + anchorPos) * .5f);
        points.Add(anchorPos);
    }

    public Vector2[] GetPointsInSegment(int i)
    {
        return new Vector2[] { points[i * 3], points[i * 3 + 1], points[i * 3 + 2], points[i * 3 + 3] };
    }

    public void MovePoint(int i, Vector2 pos)
    {

        if (isContinuous)
        {

            Vector2 deltaMove = pos - points[i];
            points[i] = pos;

            if (i % 3 == 0)
            {
                if (i + 1 < points.Count)
                {
                    points[i + 1] += deltaMove;
                }
                if (i - 1 >= 0)
                {
                    points[i - 1] += deltaMove;
                }
            }
            else
            {
                bool nextPointIsAnchor = (i + 1) % 3 == 0;
                int correspondingControlIndex = (nextPointIsAnchor) ? i + 2 : i - 2;
                int anchorIndex = (nextPointIsAnchor) ? i + 1 : i - 1;

                if (correspondingControlIndex >= 0 && correspondingControlIndex < points.Count)
                {
                    float dst = (points[anchorIndex] - points[correspondingControlIndex]).magnitude;
                    Vector2 dir = (points[anchorIndex] - pos).normalized;
                    points[correspondingControlIndex] = points[anchorIndex] + dir * dst;
                }
            }
        }

    else {
         points[i] = pos;
    }
    }
}

```

BPathCreator:

```
public class BPathCreator : MonoBehaviour
{

    [HideInInspector]
    public BPath path;

    public void CreatePath()
    {
        path = new BPath(transform.position);
    }
}

```

BPathEditor:

```
[CustomEditor(typeof(BPathCreator))]
public class BPathEditor : Editor
{

    BPathCreator creator;
    BPath path;

    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
        EditorGUI.BeginChangeCheck();

        bool continuousControlPoints = GUILayout.Toggle(path.isContinuous, "Set Continuous Control Points");
        if (continuousControlPoints != path.isContinuous)
        {
            Undo.RecordObject(creator, "Toggle set continuous controls");
            path.isContinuous = continuousControlPoints;
        }

        if (EditorGUI.EndChangeCheck())
        {
            SceneView.RepaintAll();
        }
    }

    void OnSceneGUI()
    {
        Input();
        Draw();
    }

    void Input()
    {
        Event guiEvent = Event.current;
        Vector2 mousePos = HandleUtility.GUIPointToWorldRay(guiEvent.mousePosition).origin;

        if (guiEvent.type == EventType.MouseDown && guiEvent.button == 0 && guiEvent.shift)
        {
            Undo.RecordObject(creator, "Add segment");
            path.AddSegment(mousePos);
        }
    }

    void Draw()
    {

        for (int i = 0; i < path.NumSegments; i++)
        {
            Vector2[] points = path.GetPointsInSegment(i);
            Handles.color = Color.black;
            Handles.DrawLine(points[1], points[0]);
            Handles.DrawLine(points[2], points[3]);
            Handles.DrawBezier(points[0], points[3], points[1], points[2], Color.green, null, 2);
        }

        Handles.color = Color.red;
        for (int i = 0; i < path.NumPoints; i++)
        {
            Vector2 newPos = Handles.FreeMoveHandle(path[i], Quaternion.identity, .1f, Vector2.zero, Handles.CylinderHandleCap);
            if (path[i] != newPos)
            {
                Undo.RecordObject(creator, "Move point");
                path.MovePoint(i, newPos);
            }
        }
    }

    void OnEnable()
    {
        creator = (BPathCreator)target;
        if (creator.path == null)
        {
            creator.CreatePath();
        }
        path = creator.path;
    }
}

```

# Answer
If you had some sort of generic spline object whose control points you could manipulate you could easily mirror the control points with small movable cubes. Implement a click and drag interface, use raycasts when needed and voila. The interface would be the fun part.

Here is a simple example of this in action without the modifiable control points
> 0 votes

---
Tags: unity
---


# Question
Title: Is good idea to use single threaded server for games? Also can it handle multiple clients?
I was developing an game. I using single threaded nodejs(socket.io) server. It is good for simple games or games like basic 3d world? Usually game will have 10-20 players(clients).

Also is single threaded server can handle multiple clients same time?

like player 1 walks player 2 jumps same time.

# Answer
> 2 votes
There is nothing good or bad about using **NodeJS**.

I have experience with multiple relatively heavy loaded projects (2-500 users on a 1 CPU machine) using nothing but NodeJS and Web sockets. No problems with performance. Games were not very complicated - mostly moving units on a 2D plane, units can shoot missiles or do melee attacks.

I'd recommend one of these packages: `wse` or vanilla `ws`.

NodeJS is actually not that slow in compare with c++ or g++.

Talking about performance - I'd recommend avoiding socket.io - is a very comfortable and simple library, but it works much slower. But it still not a problem for quick prototyping or a small number of connections (2-30 is small here).

I hope this answer is subjective enough to match the subjectivity of the subject.

P.S.: I'm currently working on a thing capable to handle 1000+ connections per machine. With no fear.

# Answer
> 2 votes
Usually you would have multiple threads in the case of TCP, each for one client connection, and a thread for gamestate/logic. In the case of UDP you have one listening/sending thread and one game state/logic thread.

## TCP:

Anything comes in from a client you put it in a shared queue. For instance, you may have a seperate queue for jumps, for shooting, etc. Any game event happens you broadcast it across the clients.

Anyway, using TCP is a pretty bad idea anyway (for the game itself, for a chat it's good). You want to get packets out as fast as possible, and not wait for stuck packets that may take seconds to clear (which is why you have to use seperate threads, otherwise one bad player connection can throttle everything).

## UDP:

You might want to keep track of the order of packets, if that is important to you. Also include a little header in each packet of what packets were last received, so you know if you have packet loss and need to resend anything. Here's some links that explain in more detail with code: https://www.gafferongames.com/post/virtual\_connection\_over\_udp/ https://www.gafferongames.com/post/reliability\_ordering\_and\_congestion\_avoidance\_over\_udp/

## Conclusion

As you can tell, both TCP and UDP have drawbacks and strongpoints.

TCP: very reliable, but slow, blocks a thread. Good for web servers, chats, user account login, anything that does not require millisecond speeds, but *does* require reliability.

UDP: lightning fast, non-blocking, unreliable. Used for things that just need very fast speed, use your own programming or a library to make it reliable.

Luckily since you are using node, somebody else has *probably* figured it out, sadly I'm not familiar with the node ecosystem.

Also, I'm not sure if it still applies on modern routers and modems, but it's often claimed that using both TCP and UDP on the same port can lead to connection problems. So I recommend you use different ports for your chat (TCP) (if you have a chat) and your game (UDP). It doesn't hurt either way.

---
Tags: server
---


# Question
Title: In a visual novel game with optional sidequests, how to encourage the sidequests without requiring them?
## Context

I'm working on a small visual novel-style game, telling the story of a defense attorney and investigator. The story is split into chapters, with each chapter being a new case, and there are also recurring characters who develop throughout the story. It's a mini Phoenix Wright-style experience, with some point-and-click detective work mixed in.

As part of the game, you can embark on optional character-based sidequests, each of which focus on a different character and showcase some development between them and the protagonist. A few of these sidequests unlock after completing each case, and are usually related to the case that just happened. For example, after finishing a case involving a video game convention, you unlock an optional sidequest where you can take one of the supporting characters (the "tough guy who's secretly a dork on the inside", of course) to the convention before it leaves town.

I want to make these sidequests optional, and not force the player to do all of them or make them feel like they have to say "yes" to all of them - that is, I want to establish that they're free to decline an invitation if they don't like a particular character as much as the others and would rather not take them out for ice cream. However, I still want to make sure the player does *some* of them, because I feel many of them, if missed, would cause the player to miss out on really neat parts of the game. (If it helps, the game doesn't have a "completion percentage" or anything, just small achievements for doing certain things.)

## My question

Given this design, I have a conundrum. I want the player to do at least *some* of the optional sidequests, but I don't want to force it or make them feel like it's necessary to see every single one of them. I don't want to place an arbitrary "you must do 3 sidequests to proceed" roadblock, but I also don't want the player to skip all of them and do the entire story without developing any of the characters. That obviously defeats the point of a heavily character-based visual novel! So, this is my dilemma:

**What game mechanics in a visual novel are best to encourage optional sidequesting, but not *require* it for story progression or completion?**

I have a couple ideas for this, since a lot of games have offered solid solutions for this problem already:

* **Making the sidequests optional, but having rewards for doing them.** This is the approach that most games take nowadays. You don't *have* to do the sidequests, but maybe if you do one, it unlocks a palette swap, an item, or a hint coin.
* **Affinity mechanics.** Maybe if you do enough sidequests for your prosecutor buddy, he gets closer to you and gives important hints in a later cases. This would work similarly to "friendship" in other games, where there's a number that keeps track of how good your relationships with different characters are and doing quests increases that number. At the same time, I think this encourages too much of a "metagame" approach, where players will just do every sidequest for a character all at once to unlock their bonus. It also makes the difficulty curve of the game wonky, since I want the cases to start easy and get progressively harder, and giving substantial bonuses in the late game might mess with that design.
* **Requiring the player to do at least X of them.** This is the roadblock approach - blocking the progression of the story until the player does at least 1, 2, or 3 of the available sidequests. I dislike this because it feels like I'm being arbitrary and might frustrate the player if they don't like the current sidequest options and really want to do the next case.

Ideas and other suggestions are welcome!

# Answer
For the purpose of this answer I will assume you are developing another Phoenix Wright game which is exactly like those of the original trilogy, just with additional optional side-content. That makes it easier to write an answer because I need to make less guesses about what you already do and don't do in your game.

In a Phoenix Wright game, it's crucial for the player to speak to *everyone*, pick *every* dialog option, examine *everything* and assume that *every little detail is important*. Because usually it *will* be important during the trial phase. This includes getting to know all the characters as well as possible. Because most characters will eventually appear on the witness stand, and when they do they are going to lie to the player. And then the player has to point out which part of their testimony exactly is a lie. In order to do so successfully, the player needs to understand those characters, what they can and can not know, why they would lie and how they would lie.

This is anathema to optional content, because it's not possible for the player to see which content is really optional and which content looks like it's optional but does actually include an important hint for the case. So the most crucial thing is to develop a UI convention which makes it clear to the player that whatever content they are about to enter is not related to the main case.

The best way might be to put the optional content into separate episodes. One thing the player can usually trust is that they won't require knowledge from previous episodes to solve the current one. So after completing a case, you could add a couple additional "bonus episodes" to the episode selection menu.

If you really want to integrate the optional content into the regular episodes, then you could tell the player which dialog options are part of the bonus quests and which aren't. You could, for example, communicate that via the background color of buttons or by adding an icon to them. You might want to follow this throughout the whole bonus content, so the player does not get confused about whether they are on the bonus content or the regular content. However, I would advise against that. My experience is that completing a regular Phoenix Wright episode (without consulting a walkthrough) already requires 120% of the players attention. Providing additional distraction in form of optional sidequests might make it even more difficult to unravel the contradictions of the main plot.
> 20 votes

# Answer
**"Visual novel" and "you should only play the parts you want to" are contradictory.**

The whole point of a visual novel is to explore the story and characters, or to discover the different possible outcomes of the player's choices. Trying to tell the player that they don't "have to" explore every possible option is like trying to tell a Mario player that they don't "have to" jump.

It's very much possible to beat a Mario game without jumping, and it's usually also possible to "beat" a visual novel while skipping a fair amount of content. But in both cases, that's not really the point of the experience. Your players will come into your visual novel with the assumption that they are "supposed to" see all of the content, because for every other visual novel they have played, that's how it works.

If you really are set on making certain parts of the game optional, I think you really only have a small set of options:

* Present the player with two (or more) mutually-exclusive sidequests. They can play the other one next time (and many players will do exactly that, so don't worry about people missing content that they wanted to see; this is what the skip button is for). This helps if your main problem with the sidequests is related to pacing rather than player freedom. For obvious reasons, this is no good if you have one mandatory and one optional sidequest.
* Make something other than a visual novel, by including elements not commonly found in that genre. For example, Telltale Games, before they went bankrupt, would often include a lot of quicktime events, timed dialog options, and frequent reminders that "\[character\] will remember that," all of which are uncharacteristic of the VN genre. Of course, many players of TTG's games would *still* go back and experience everything anyway, so this only goes so far.
* As Philipp suggests, break the optional bits out into a separate episode, or give a clear UI indicating that they are truly optional. If you go for a UI indication, you will need to explain this to players up-front, because you will be violating genre expectations.
* Just accept that many players will play through all of the content. Don't worry about it unless you gets complaints of pacing or "boringness."
> 11 votes

# Answer
**Look to Persona**

In the Persona games, between bouts of dungeon crawling, there are long segments heavily influenced by the visual novel genre, that consist of talking to and hanging out with friends. Whilst this can affect the dungeon crawling to some degree, with perks (of varying utility) unlocked, it mostly functions as a separate way to have the players relate to the characters.

**Why does this matter here?**
Whilst you could incorporate minor perks (the outfit swap/item works, but more engaging may the characters having more tailored, unique skills from the events; or even just an extra line of dialogue referencing it); the part that compels new players to try talking to the characters is that they have a set amount of (in-game) time to do so, with few other options. This seems like it would map very well onto your game. Give the player, say, one week with five character events and some chores they can choose to do instead, and instead of seeming like a chore, it becomes a challenge to optimise their time to do the events they want. Or the can ignore everything and decide to nap or whatever the "secret" skip button is. And of course, it doesn't hurt to guide the player to the first event.
> 4 votes

# Answer
It's great that you've already collected feedback from play testers. Based on that, it sounds like you might be trying to fix problems that aren't there. If your core audience is choosing to experience the optional content & enjoying your game, it sounds like you've already made a good product.

That said, if you're still concerned about player's skipping optional content, I would look for ways to communicate your intent. You could do this either in game, outside the game or both.

Communicating your intent outside the game play is the easiest solution because you don't necessarily need to worry about breaking immersion. By directly communicating the intent in the game description, your message is less likely to be misinterpreted. Ideally, this allows potential buyers/players to make informed choices. Unfortunately, not everyone reads product descriptions carefully.

Communicating your intent in game may require more work. If you are trying to tie the optional content to game mechanics I recommend respecting the player's time by clearly indicating the material is in fact optional. This avoids player's feeling tricked into doing work that doesn't change the game state or confused as to why nothing changed in the game after doing optional things. Again, the idea is to allow players to make informed choices.

In terms of game mechanics, I would consider giving the player some way to see how much optional content they have explored. Second, I would consider unlocking cosmetic changes; it's difficult to give on point recommendations without knowing the specifics of your game, but here are a couple examples:

* If your art style lends itself well to layering or you can afford extra assets, allow the player to customize some characters' appearances. This may also work well if you had more art than you needed, but be mindful of including stuff that was cut because it was of low quality or poor fit.
* If the game supports it, consider cosmetic dialog options. For instance, if the player consumed the background content about a character's time abroad, include phrases that reflect that.

Ultimately, you have to accept that optional content means that players may not see everything; if you feel that detracts too much from the experience, then the content isn't optional.
> 3 votes

# Answer
Ration how much optional content the player is permitted to do.

In the main plot line, have some measure of success. Depending on how well you do in the main plotline, "reward" the player with the ability to (optionally) do 1, 2, or 3 "side quests" as the end of the episode.

This "this side quest is a reward" should motivate players to consume the side quest even if it is otherwise pointless. The side quests should include "Easter Eggs" that put later parts of the story in a new light, but are not required for the main plot to make sense or progress in it.

For example, on a side quest with someone, they might talk about wanting to set up a restaurant (by name). Later, that restaurant can be in the background (physically, or an advertisement for it), or even a location where another scene happens.

That scene can occur regardless of if you did the side quest or not; the side quest just makes that scene have more meaning, rewarding the player with story connections but not mechanics for the main plot.

By labeling them as rewards (explicitly), and bonus content, the player won't feel obligated to do them all (and possibly unlikely to be able to on their first play through). But they should feel motivated to do them, and rewarded when the main story does callbacks that they'd only understand if they did the bonus content.
> 0 votes

---
Tags: game-design, game-mechanics, quests, visual-novel
---


# Question
Title: Is linear filtering possible on depth textures in OpenGL?
I'm working on shadow maps in OpenGL (using C#).

First, I've created a framebuffer and attached a depth texture as follows:

```
// Generate the framebuffer.
var framebuffer = 0u;

glGenFramebuffers(1, &framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);

// Generate the depth texture.
var shadowMap = 0u;

glGenTextures(1, &shadowMap);
glBindTexture(GL_TEXTURE_2D, shadowMap);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, 1024, 1024, 0, GL_DEPTH_COMPONENT, GL_FLOAT, null);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, shadowMap, 0);

// Set the read and draw buffers.
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);

```

Later (after rendering to the shadow map and preparing the main scene), I sample from the shadow map in a GLSL fragment shader as follows:

```
float shadow = texture(shadowMap, shadowCoords.xy).r;

```

Where `vec3 shadowCoords` is the coordinates of the fragment from the perspective of the global directional light source (the one used to create the shadow map). The result is shown below. As expected, shadow edges are jagged due to using `GL_NEAREST` filtering.

To improve smoothness, I tried replaced the shadow map's filtering with `GL_LINEAR`, but the results haven't changed. I understand there are other avenues I could take (like Percentage-Closer Filtering), but I'd like to answer this question first, if only for my sanity. I've also noticed that other texture parameters (like `GL_CLAMP_TO_EDGE` rather than `GL_REPEAT` for wrapping) don't function for the shadow map, which hints that this may be a limitation of depth textures in general.

To reiterate: **Is linear filtering possible using depth textures in OpenGL?**

# Answer
> 4 votes
Shadow maps, the way you're using them, don't filter well. The linear filtering does what it's supposed to, it's just not the thing you actually want for this context.

Take a sample point halfway between an occluded sample (say, depth from light = 5 vs my depth from light = 10), and a non-occluded sample (depth from light = far plane). We somehow want to interpolate these two adjacent samples to get a "half-shadowed" anti-aliased effect, rather than a stairstep.

If we just linearly interpolate these two depth values, with a far plane that's say 1000 units out, we get:

```
   0.5 * (occluderDepth) + 0.5 * (farPlaneDepth)
 = 0.5 * 5 + 0.5 * 1000
 = 502.5

```

That 502.5 is *much* farther away from the light than my position, so we conclude we're not shadowed at all!

A similar thing happens if we interpolate with a sample at the receiver's depth:

```
  0.5 * (occluderDepth) + 0.5 * (receiverDepth)
= 0.5 * 5 + 0.5 * 10
= 7.5

```

Now we have a depth that's substantially closer to the light than our receiver point, so we conclude we're entirely in shadow!

You can see that even when we work out the math by hand, instead of a smooth falloff when we sample between depth points, we still get a hard stairstep edge between completely shadowed and not at all shadowed.

So: **interpolating depths does not do the same thing as interpolating "shadowed-ness"**.

You can store your shadow maps in an alternative format, like Variance Shadow Maps. These store not just a depth value, but some distribution information designed so that filtering the shadow map *does* filter "shadowed-ness" - or something similar to it, at least. You get a different type of artifact with these, which is light leaking - areas of the shadow map with large depth discontinuities trick the filtering into thinking some light could get through, even if no light should.

---
Tags: opengl, glsl, fragment-shader, shadow-mapping, filtering
---


# Question
Title: Building a unified interface for a swap chain in both DirectX 12 and Vulkan
Most objects in DirectX 12 have natural analogues in Vulkan, e.g.

* `VkInstance` = `IDXGIFactory`
* `VkPhysicalDevice` = `IDXGIAdapter`
* `VkDevice` = `ID3D12Device`
* `VkQueue` = `ID3D12CommandQueue`
* `VkCommandBuffer` = `ID3D12CommandList`

However, when it comes to the swap chain, it's not clear how the entries in `VkSwapchainCreateInfoKHR` correspond to entries in `DXGI_SWAP_CHAIN_DESC1`.

Clearly, there is not always a 1-1 correspondence, but I would really like to know how I can implement a unified interface for both.

# Answer
The whole point of APIs like DirectX 12 and Vulkan is to minimize CPU overhead, and therefore they have extremely *thin* API abstractions. As such, wrapping them in a low-level API basically defeats their whole purpose.

Furthermore, both DirectX 12 and Vulkan expose more of the underlying hardware behavior, so again by design the application needs to have a lot more context about the overall API usage than older graphics API designs.

As such, if you want to implement both a DirectX 12 and Vulkan version of the same application or engine, then you want to create higher-level abstractions. Not "a function to create a swap chain" but "code module to manage the display/output window/system message loop".
> 1 votes

---
Tags: software-engineering, cross-platform, vulkan, directx12
---


title: Bullets Stop when Shooting Unity 2D

text:
# Question
Title: Bullets Stop when Shooting Unity 2D
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Makarov : MonoBehaviour
{
    public GameObject Bullet;

    public float BulletSpeed;

    public Transform ShootPoint;

    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            shoot();
        }
    }

    void shoot()
    {
        GameObject BulletIns = Instantiate(Bullet, ShootPoint.position, ShootPoint.rotation);
        BulletIns.GetComponent<Rigidbody2D>().AddForce(BulletIns.transform.forward * BulletSpeed);
    }
}

```

When I shoot the bullets just stop right in front if the gun. This is for a top down shooting.

# Answer
> 0 votes
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Makarov : MonoBehaviour
{
    public GameObject Bullet;

    public Transform ShootPoint;

    public float bulletSpeed = 20f;

    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Shoot();
        }
    }

    void Shoot()
    {
        GameObject bullet = Instantiate(Bullet, ShootPoint.position, firePoint.rotation);
        Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
        rb.AddForce(ShootPoint.up * bulletSpeed, ForceMode2D.Impulse);

    }
}

```

This works!

---
Tags: unity, 2d
---


# Question
Title: Given a 2D array, how do I generate a random path of fixed length from a random point at length 0 to a random point at max length?
I'm trying to generate a random path on a 2D grid given that:

* The width and height of the grid are given
* The length of the path to generate is given
* The path can't move "back"
* The path starts from a random point at height 0 and ends at a random point at max height
* A path segment cannot "touch" with a path segment that is at its height - 1 that is not the latest generated segment of the previous height

This is what two paths generated from the parameters {Width:11, Length:17, PathLength:30} would look like:

and this is an example of a path that should **not** be generated:

The result of the algorithm should be a list of value pairs such as this: (8,6) in any order, which indicates the segments of the path. I've been trying to solve this problem for a while, but I have problems understanding how to make this have a given length. If the given length was not a requirement I could just generate it with a nested for cycle and some rules. Please help!

# Answer
> 1 votes
Some pseudo algorithm that can at least give a start.

1. Since start and endpoint can be random, generate them at the start to make sure we can generate a valid path.
2. Find out how many side steps the path can take: PathLength - Length - abs((start.x - end.x)). This gives you the shortest path to the goal. If this value is bigger than your pathlength, your end.x needs to be closer to start.x. If this value cannot be divided by 2 - since it is the length of shortest path, for every sidestep we need to go one in the other direction - you need to move goal.x to either +1 or -1.
3. From 2 you got now the value of how many detour steps you can take. You have now a few options on how you want to generate the path. My approach would be to make a collection of predefined segments you pick from. You can sort them by their amount of sidesteps and just chain them together.
4. If you have used up all sidesteps but are still missing a pathlength, prolong the connection between segments.

Some elements with sidestep count 3:

```
0001 0001 1111 0111
0111 0011 1000 1100
1100 0110
     1100

```

---
Tags: algorithm, path-finding, random, grid, path
---


# Question
Title: Rotate relative to set point in a specified direction in a 3D space
I know there's a geometry formula to calculate the next point in rotation relative to another point in 2D but I'm working in 3D and I want to calculate the next position in specified direction as well. Think Spiderman or the Bloodstalkers from ARK. I'm working in a game engine that uses the basic {x = 1, y = 2, z = 1} for vectors. I'm pretty bad at math so I honestly can't figure this out myself.

# Answer
> 2 votes
First of all, game engines and math go hand in hand so understanding the underlying theory should be high in your priority list. I will try to explain this at a high level, based on what I understood and will try to elaborate later when I get the time. I will also put in bold terms you should look at.

Taking the spiderman swinging example, this means you have 2 points, namely the *building corner* the spiderweb is attached to and *spiderman* himself. These 2 points will give you a vector which we will name `spiderwebVector`. There is also a second vector which is what you refer to as *specified direction*. I'm assuming you know which direction that is (the direction spiderman is going). Let's name that vector `swingdirectionVector`.

Your steps should be the following:

1. Execute a **cross product** between the 2 vectors. This will give you a 3rd vector which will be the **axis of rotation** (the vector around which you are rotating).
2. Execute a second **cross product** between the `spiderwebVector` and the `axisVector`. This will give you another vector. (note: the new vector will probably have the same or inverse direction as the `swingdirectionVector`).
3. **Normalize** the 2 new vectors and the `spiderwebVector`. These new **unit vectors** now form a new **basis**. Essentially they are a new set of \\$x',y',z'\\$ basis vectors but their coordinates are expressed in **standard basis** \\$x,y,z\\$ values. Assume \\$z\\$ is the up vector.
4. Any rotation of angle \\$θ\\$ around an up axis (in our case either \\$z\\$ or \\$z'\\$) is defined by the following **rotation transformation matrix** $$R=\begin{pmatrix} \cos\theta & -\sin\theta & 0 \\ \sin\theta & \cos\theta & 0 \\ 0 & 0 & 1 \end{pmatrix}.$$
5. Because the rotation is around \\$z'\\$ (remember, the new **basis**) this transformation will rotate the points by \\$θ\\$ assuming they are expressed in the new **basis** coordinates, which I assume is not your case since everything is expressed in the **standard basis** \\${x,y,z}\\$.
6. In order to create the transformation that will rotate all the points expressed in **standard basis** coordinates, we execute a **change of basis** transformation first. This is another 3x3 matrix. Each **column** of that matrix represents \\$x',y'\\$ or \\$z'\\$ expressed in the **standard basis**. For example if \\$x'=(0.57,0.57,0.57)\\$ then the *first column* will be $$\begin{pmatrix} 0.57 \\ 0.57 \\ 0.57 \end{pmatrix}.$$ We now have a change of basis matrix $$C=\begin{pmatrix} a & d & g \\ b & e & h \\ c & f & i \end{pmatrix}.$$
7. Finally, to execute the whole rotation, we sandwich the \\$R\\$ rotation matrix with the change of basis matrix and its **matrix inverse** $$ U=CRC^{-1} $$ It is important to note that the **inverse** comes on the right. The reason for this is a little more complicated but if you understand the change of basis concept it makes sense. More info can be found here.
8. You take the \\$U\\$ **transformation matrix** and you multiply it with the vector that needs to rotate, in this case the `spiderwebVector`. Note that the vector must come from the **right-multiplication** `U * spiderwebVector`. This will give you a new vector that points to the new location spiderman ends up at after a rotation of angle \\$θ\\$.

I believe this is the gist of it, however I'm also new at this and any input/edits/**corrections** from more experienced members is very welcome.

---
Tags: mathematics, rotation, lua
---


# Question
Title: How to assign an index to different node clusters? (for pathfinding)
Hellow~

So for a bit of context: i'm currently working on a RTS (way above may league) which already has a level editor and a node grid which maps the terrain, i previously make a navigation system with A\* as explainned by Sebastian Lague in his tutorial series about the topic, but then i run into a problem when running with multiple units (not the point here: but never manage to find each unit cluster within the selection), so i change it into a navmesh mapping which if made dynamic by assigning navmesh obstacles to the unwalkable nodes (the frame after the creation of the node grid)

**Now i want to use the node grid basically to check if the target node and the start node share the same node cluster. But here is the thing: i can't assign the needed index to the nodes as i expected.**

I've been trying adapting code from this post, but didn't quite make it. Now i have this one, which i think could achieve something but still gets me a invalid operation exception:

```
public const int UNWALKABLE_ISLAND = 999;

public static void SetIslands(ref WorldGrid _worldGrid) {
    int width = _worldGrid.nodeGrid.GetLength(0);
    int height = _worldGrid.nodeGrid.GetLength(1);

    bool[,] visited = new bool[width, height];

    int clusterCount = 0;

    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++)
        {
            if (visited[x, y]) { continue; } else {
                List<Node> cluster = new List<Node>() {
                    _worldGrid.nodeGrid[x, y]
                };

                foreach (var node in cluster) {
                    if (node.isWalkable)
                    {
                        visited[node.X, node.Y] = true;
                        node.SetIslandIndex(clusterCount);
                        cluster.AddRange(_worldGrid.GetNeighbours8D(node));
                    }
                    else
                    {
                        cluster.Remove(node);
                    }
                }

                clusterCount++;
            }
        }
    }
}

```

The error:

> InvalidOperationException: Collection was modified; enumeration operation may not execute. System.ThrowHelper.ThrowInvalidOperationException (System.ExceptionResource resource) (at\<437ba245d8404787b9fbab9b439ac908\>:0) System.Collections.Generic.List`1+Enumerator[T].MoveNextRare() (at<437ba245d8404787b9fbab9b439ac908>:0) System.Collections.Generic.List`1+Enumerator\[T\].MoveNext() (at\<437ba245d8404787b9fbab9b439ac908\>:0) Pathfinding.SetIslands (WorldGrid& \_worldGrid) (at Assets/Pathfinding.cs: 25) WorldGrid.CreateNodeGrid() (at Assets/WorldGrid:80) WorldGrid+d\_12.MoveNext() (at Assets/WorldGrid.cs:42) UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, Sustem.IntPtr returnValueAddress) (at\<437ba245d8404787b9fbab9b439ac908\>:0) UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

My node class contains an int that should hold the cluster index, which will be using for the request check. (the code its based from this youtube video)

Right now i'm trying to understand the spectral clustering stuff, i've been told it could help.

I hope you can help an animator in need with some pointers.

Cheers :3

\*Oh!, I also tried reading the nav agent path end coordinate for comparison, but it ended up becoming a huge mess for me.

# Answer
> 1 votes
Woot!

I manage to set up island indexes by flood filling the nodes, in different manner as i was attempting. Here is the code for further reference:

```
private static int clusterIndex = 0;
private static bool[,] visited;

public static void FloodIslands()
{
    int width = WorldGrid.Instance.nodeGrid.GetLength(0);
    int height = WorldGrid.Instance.nodeGrid.GetLength(1);
    visited = new bool[width, height];

    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++)
        {
            if (visited[x, y] || !WorldGrid.Instance.nodeGrid[x,y].isWalkable && !visited[x, y]) { continue; }
            else {
                SearchCluster(x, y, width, height, clusterIndex);
                clusterIndex++;
            }
        }
    }
}

private static void SearchCluster(int _x, int _y, int _width, int _height, int _desiredIndex) {
    if (_x < 0 || _y < 0 || _x >= _width || _y >= _height ||
        WorldGrid.Instance.nodeGrid[_x, _y].isWalkable == false ||
        WorldGrid.Instance.nodeGrid[_x,_y].IslandIndex == _desiredIndex) {
        return;
    }

    Node node = WorldGrid.Instance.nodeGrid[_x, _y];

    node.SetIslandIndex(_desiredIndex);
    visited[node.X, node.Y] = true;

    SearchCluster(_x + 1, _y, _width, _height, _desiredIndex);
    SearchCluster(_x - 1, _y, _width, _height, _desiredIndex);
    SearchCluster(_x, _y + 1, _width, _height, _desiredIndex);
    SearchCluster(_x, _y - 1, _width, _height, _desiredIndex);
}

```

This way i didn't had to deal with the wierd collection exceptions.

\*DMGregory thank you so much for the tip, even though i couldn't make it work around the list, it did push me to look for alternatives, until i hit this reference (a youtube video from Nick White).

---
Tags: unity, path-finding, grid, rts, navmesh
---


# Question
Title: How to create customizable character mesh?
Imagine a character that can equip different game items like helmets, gloves, shoes, etc. Each different item have its own mesh, bone rig and animations.

What is the best way to create such a system using Unity3d?

# Answer
> 1 votes
You usually approach this by making the item a child of the skeletal node it should remain "fixed" to.

Eg for a rigged human skeleton, you'd make the helmet a child of the neck/head bone, a sword might be attached to the wrist or the pelvis, depending on whether it's drawn or sheathed.

More broadly, you need to implement a system to track which items attach to which bones and parent them as needed to add/remove items.

More complex items (eg a tabard) might require multiple attachment points, or a custom shader depending on what you're trying to achieve.

# Answer
> 1 votes
Even vaguely professional 3d modeling programs support hierarchical objects, and Unity can import them as hierarchies of gameObjects which can be activated and deactivated separately.

So when the number and the level of detail of your different character options are low enough to allow it, then it can be an option to have all the different customization option in the same character model file in form of different sub-objects. So your character model includes 5 different shirt objects all attached to the same armature, but you only activate one at a time.

This has the advantage that you can very easily try out different customization combinations in your modeling programs. This allows you to see if your animations work well with every combination while you are making them. You don't have to switch between Unity and Blender (or whatever else you prefer) all the time to test if it's all aligned correctly.

One disadvantage of this approach can be performance and memory usage. Both your modeling program and Unity have to load all the customization options at once, including those the player does not use right now. But this might not become an issue unless you go for an AAA level of detail. Another disadvantage is that it makes collaboration harder, because there is just one character model file. When you want to have multiple artists creating different customization items independently, then you really want a solution where each item comes in its own file.

# Answer
> 0 votes
Disclaimer: this is a very complicated and lengthy process that will require many different skill sets.

This tutorial series from Sebastian Lague will cover this topic from making your models in blender to importing them into unity: https://m.youtube.com/playlist?list=PLFt\_AvWsXl0f4c56CbvYi038zmCmoZ4CQ

The basics is that you will have extra objects to represent the clothing of your character. These objects will be weight painted to match the skeleton of the model. They may also contain shape keys that deform the original body mesh to help prevent it from clipping through tight clothing.

I haven't done anything on the unity side, so you will have to watch the videos for how all of that fits into unity.

---
Tags: unity
---