# Question
Title: Adding consistent wandering/patrolling code to my enemy script
I have been looking everywhere for a patrolling/wandering code/system for my slender-esque game. However, I am having trouble finding anything or even implementing anything and haven't been able to find answers anywhere (potentially due to not asking the right questions online).

I did originally find one script that somewhat worked but it kind of broke on me (it would not switch out of the "wandering" state after a few edits that I made to it).

My question is what would be the recommended code to input?

here is my code:

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

public class StalkerAI : MonoBehaviour
{

   public playerinventory Playerinventory; //for difficulty scaling

public NavMeshAgent agent;
public Transform Player;

public float walk; //speed for enemy to go
public float run;

void Start()
{
    agent = GetComponent<NavMeshAgent>();

    walk = 3 + Playerinventory.NumbOfClues;
    run = 5 + Playerinventory.NumbOfClues;
}
// Update is called once per frame
void Update()
{
    float distValC = 5.0f;
    float dist = Vector3.Distance(agent.transform.position, Player.position);

    if (dist <= distValC)
    {
        agent.speed = run;
        agent.SetDestination(Player.position);
    }
    else
    {
        agent.speed = walk;
        agent.SetDestination(agent.transform.position);

    }
}

```

}

# Answer
It depends a lot on what you want the wandering to look like. You could start with a simple wandering AI and than iterate to make it feel more natural and improve gameplay. There are many ways to do this. You could start with following approach.

## Define States

There are two states, Wandering and Hunting. For Wandering state, which is the default state:

* Define an array of waypoint marker objects (which are just transforms)
* Set the agent's destination to the first marker
* When the agent has reached it's destination, wait for a random amount of seconds, before setting the destination to the next waypoint
* Once the last marker was reached, start over with the first (for a circle) or go backwards the same way you came

If the player is in sight switch to Hunting state, as long as the player is within a certain radius (should be bigger than distValC, because now the enemy is already focused on the player). For the Hunting state the code in your if-branch seems fine, unless you also want to add attacks etc.

The code could look something like this:

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

public class Enemy : MonoBehaviour
{
    public int numbOfClues; //for difficulty scaling

    [HideInInspector]
    public NavMeshAgent agent;

    public Transform Player;

    public float walk; //speed for enemy to go
    public float run;

    public Transform[] waypointMarkers;

    int waypointIndex = 0;
    float waypointWaitTime = 0.0f;
    bool isHunting = false;
    public float gainSightDistance = 12.0f;
    public float loseSightDistance = 18.0f;

    void Start()
    {
        agent = GetComponent<NavMeshAgent>();

        walk = 3 + numbOfClues;
        run = 5 + numbOfClues;
    }

    void Update()
    {
        if (isHunting)
        {
            Hunt();
        }
        else
        {
            Wander();
        }
    }

    void Hunt()
    {
        float dist = Vector3.Distance(agent.transform.position, Player.position);

        // hunting state's exit condition
        if (dist > loseSightDistance)
        {
            // If player is out too far, enter wandering state ...
            isHunting = false;
            // ... but first wait a few seconds before
            waypointWaitTime = Random.Range(2.0f, 4.0f);
            agent.speed = 0.0f;
            return;
        }

        agent.speed = run;
        agent.SetDestination(Player.position);

    }

    void Wander()
    {
        float dist = Vector3.Distance(agent.transform.position, Player.position);

        // wandering state's exit condition
        if (dist <= gainSightDistance)
        {
            // enter hunting state
            isHunting = true;
            return;
        }

        if (agent.remainingDistance < agent.stoppingDistance)
        {
            // When destination is reached,
            waypointIndex = (waypointIndex + 1) % waypointMarkers.Length;
            agent.SetDestination(waypointMarkers[waypointIndex].position);
            // Set a random wait time from 3 to 7 seconds and stop agent movement
            waypointWaitTime = Random.Range(2.0f, 4.0f);
            agent.speed = 0.0f;
        }
        else
        {
            if (waypointWaitTime > 0.0f)
            {
                // Reduce countdoun until 0 ...
                waypointWaitTime -= Time.deltaTime;
            }
            else
            {
                // ... then walk towards the next waypoint marker
                agent.speed = walk;
                agent.SetDestination(waypointMarkers[waypointIndex].position);
            }
        }
    }
}

```

Note: numbOfClues is here just a simple int that doesn't change. You will need to replace it with the actual value. I also changed some of your variable's names, to make clearer what they are. Also, make sure that the waypoints are actually reachable. This might not be the case, if the height difference between your agent and the marker is too big. So the marker and the agent should be on the same height and your agent's stopping distance should be slightly above 0.

## Line of Sight

Additionally you could check, whether the player is actually being seen by the enemy by using a raycast to check whether the line of sight is blocked and limiting the angle of the enemy's view (i.e. set a max angle between the direction the enemy is facing and the direction from enemy to player). Then only go into Hunting state, if the enemy sees the player.

## Further ideas

You could define a set of markers and then, once the current destination is reached, choose the next destination randomly from this set. You could also completely randomize the destination, so that a random position on the map ist picked. But this will give you less control. Alternatively you could pick a random position within a certain radius of the enemy's current position.
> 0 votes

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


# Question
Title: Why does running an animation in the Godot editor affect game state?
There is an animation on an enemy in the demo project "Platformer 2D (Raycasting)". If you run the destroy animation in the editor, it will mess with how the enemies behave in game. Here is the animation:

If you run all the way through (leaving the keyframe position at the end of destroy), then hit "Play", the enemies will all no longer exist. If you leave the keyframe position at the beginning, it will still affect which collision\_layer the enemy is on, making it so they no longer collide with anything.

**How and why is this happening? And how does one make it stop?**

# Answer
More info here: https://github.com/godotengine/godot-proposals/issues/3829

It turns out that animations in earlier versions of Godot just changed the settings, with no way to fall back to what they were. For this reason, people would make "RESET" tracks which would reset everything. It was kind of a hassle, so the automatic creation of them was introduced, but it does not retro-actively affect projects.

My issue was running an older project, and it's issue was that it didn't have a RESET track.
> 1 votes

---
Tags: animation, godot
---


# Question
Title: How to encode homogeneous transformations on the root node of a gltf
Let us say we have a gltf asset. Let us say we want to apply an arbitrary linear transformation to the root node.

We will say that the root node has a rotation, translation and scaling components. For simplicity let us say the transformation is swapping the y and z components but the final goal is to encode any arbitrary linear transformation T.

We could try doing T(translation), T(rotation), T(scale).

In the example of swapping, let us say the translation of the root node was 0, the rotation the identity and the scaling 1 so we have:

trans = (0, 0, 0); rot=(1, 0, 0, 0); scale=(1, 1, 1);

Well if we apply our transformation to these components, we literally get the exact same components back, so we did nothing. But we wanted to encode the transformation that swaps the z and y axes. So what do I do? How do I modify the triplet at the root node so that when it is applied it executes the swap?

# Answer
> 1 votes
An exchange of two axes is a mirror operation. So you'll need to choose an axis on which to reflect the object using its scale triplet, then change the rotation to compensate.

Let's say we mirror the object on the x axis: `newScale = (-1, 1, 1) * scale`. Now a unit vector that had been pointing toward +x points toward -x, and one that had been pointing toward +z or +y still point to those directions.

We next want to rotate this object so the formerly +x, now -x vector points to +x, the +z vector points to +x, and the +y vector points to +z. (to get the expected outcome of our x/z swap). That's a 180 degree rotation about the line y = z, or as a quaternion: `newRot = (0, 1.0f/sqrt(2), 1.0f/sqrt(2), 0) * rot`.

(Here using XYZW component order according to the glTF spec)

But we could just as easily choose to treat this as a mirror in the y axis instead. Then we'd get: `newScale = (1, -1, 1) * scale`, and unit vectors in the +x and +z directions would stay put, while a unit vector in the +y direction gets mapped to -y. To turn these around, we'd want a +90 degree rotation around the -x axis: `newRot = (-1.0f/sqrt(2), 0, 0, 1.0f/sqrt(2)) * rot`.

Or, to round things out, we could treat it as a mirror in the z axis: `newScale = (1, 1, -1) * scale`. +x and +y are preserved, and +z maps to -z. So then we'd want to rotate +90 degrees around the +x axis to fix this up: `newRot = (1.0f/sqrt(2), 0, 0, 1.0f/sqrt(2)) * rot`.

Of course, the trouble here is that mirroring your object flips the winding of all your triangles. So you may need to detect if your new transformation includes an odd number of sign flips or axis exchanges (negative determinant when expressed as a matrix), and if so, swizzle your indices as you load them to get back to the desired winding.

---

In general, if you can decompose your target transformation into a translation `t`, rotation `r`, and scale `s`, then you can apply...

```
newScale = scale * (inverse(rot) * s)

newRot = r * rot;

newTrans = trans + t;

```

But as noted in the comments, not every affine transformation can be represented this way. Those that include non-uniform scaling along axes diagonal to the root node's coordinate axes, or shearing transformations, can't be exactly represented as a sequence of axis -aligned scale, rotation, and translation (in that order).

---
Tags: mathematics, animation, quaternion, linear-algebra
---


title: Defining path for tower defense game

text:
# Question
Title: Defining path for tower defense game
I'm currently developing a tower defense game as a part of a group project in school. This game will be programmed in C++ using SFML. We are having trouble with finding a good way to define the path our enemies will take. Our maps are generated from a .txt-file:

In the .txt-file, ! is the start, = is the path, # is a wall, and ? is the end. This results in a grid like this:

Our plan is to add the coordinates of every path-grid as nodes to a linked list. The enemies would then have to follow the nodes in the list. So far we have tried to add the nodes to a linked list while generating the map. The map is generated by reading the .txt-file line-by-line (left-to-right and top-to-bottom).

```
if (file.is_open()) {
while(getline(file, line)) {
  for (auto &ch : line) {
    if (ch == '!') {
      tiles_.push_back(
        std::make_shared<GameCell>("assets/road.png", y, x, true, false, true));
    } else if (ch == '#') {
      tiles_.push_back(
        std::make_shared<GameCell>("assets/grass.png", y, x, false, false, false));
    } else if (ch == '?') {
      tiles_.push_back(
        std::make_shared<GameCell>("assets/road.png", y, x, true, true, false));
    } else if (ch == '=') {
      tiles_.push_back(
        std::make_shared<GameCell>("assets/road.png", y, x, true, false, false));
    }
    y += 100;

  }
  x += 100;
  y = 0;
}
file.close();
}

```

The problem with this is that it only works if the path goes right and down. If the path goes left or up the nodes end up in the wrong order in the linked list.

How can we order the nodes the right way? Or are there better ways of doing this?

# Answer
> 1 votes
This is quite simple once you have already loaded the file into memory: Start from the start tile. Then look for a road tile next to it. Then look for a road tile next to that (other than the one you just came from). Then look for a road tile next to that (other than the one you just came from). Then look for a road tile next to that (other than the one you just came from). Etc. When you get to the finish tile, you are done.

"Look for a tile next to" can just mean checking the tiles up, down, left and right of the current tile.

This means your program needs to have the ability to look up the tile at a specific location and find whether it is a road or not. You can implement this with a 2D array of tiles. Or - as you already have - a 1D array where you can calculate the index based on X and Y.

If your game has multiple paths, a more complicated algorithm is needed - but your game does not have multiple paths.

# Answer
> 0 votes
User253751's answer is good for the example you've given but in a more advanced map it'll break easily. The problem with that idea is that if you have 2 paths joining together doesn't matter where, The enemy will have to choose either one or the other, and it'll have to know which direction is the end. Now this sounds easy and all "just have it go the direction the end is in" but its not that simple. There could be situations in which the paths wont be in the direction making that map broken. As a programmer you have to make sure that no matter what, your program wont break.

Totally the easiest way would be to revamp the way you enter your map into the program. have a csv type data structure with numbers telling you the next directions

0 for wall 1 for up 2 down 3 left 4 right 5 start 6 finish

then you just put those numbers in. if not wall then tile. numbers correspond to next tiles. easy directions without any algorithm business. File to read would look something like this for your example:

```
52;2;2;2;3;0;0;0
0;0;0;0;3;0;0;0
0;0;0;0;2;2;3;0
0;0;0;0;0;0;3;0
0;0;0;0;0;0;3;0
0;0;0;0;0;0;6;0

```

Really easy to implement and read. You read every digit for every tile. if has 5 then tile is start. if has 6 then is end. the rest are direction digits for the nexts vector. This way you can also easily implement splits by just putting more than one direction digit next to each other. each number is each tile here: 52 is start tile direction right. The nexts vector is a vector in each tile that acts a bit like your linked list showing you the next tiles from that tile you're on in a way of showing the direction to go to from there. Enemies can pick randomly from any of the tiles in that next tile to go to.

OR if you want to do something harder:

I suggest a little different approach:

* have a 2 dimensional array (a matrix) which will store each tile
* have the tiles have an array of 'nexts'
* the nexts will only store next path tiles
* the vector of nexts will be the direction in which to move
* you load in the walls and tiles into the vector normally via if # emplace back tile with value or desc "wall" if not #, then path etc etc
* now you need to know the direction in which to go. Let each tile have variable 'visited' which will be bool value.
* in loop go from start to finish adding next tile to vector of nexts of previous tile. Set current tiles' visited to true.
* for split path add both next tiles to that tile and for every of those nexts recursively continue same program.
* when 2 paths join happens program will think its a split. let it continue,
* when the above join as 'split' happens, it continues UNTIL it goes back to the actual split before. if the actual split before's next is the tile you're on A.K.A. if you're going in the opposite direction than the split says, recursively back track your steps to the joing that was understood as a split and end that loop. ending that loop and returning those visited bool values back to zero will enable the previous split to continue to the join. I'll try to explain with pictures:

Single path:

On the picture above, On each tile it checks the tiles next to it. If its tile AND its not visited, next for current tile is that next tile. Repeat. No problems here. Will always work

Split/join/advanced: For each split, it recursively does the same thing as for single...

split 1 path 1 split 2 path 1:

split 1 path 1 split 2 path 2

split 1 path 2 split 2 path 1

split 1 path 2 split 2 path 2

So above i showed you every possible turn it could do. By themselves they dont do much but if you stack them, they give you the paths.

so first the first image is done, Its fine cool and all. Then the second is done on top of the first. But the first split has nexts vector as up AND down. Since we are going up and the first split is visited and has opposite direction, WE CANCEL and revert back to second split from which we came from and we stop that iteration of recursion. We're left with image 1 again. Then since we exhausted every recursive next in the second split, the recursion rolls back to previous split to complete it's next's. Image 3 is tried. image 3 fails because that tile above the second split has already been visited and has opposing direction already too. if it was already visited, we stop that iteration of recursion. Image 4 is tried. Same idea as image 3. we get to split that has been already visited so we break and stop there. No more recursions left so we finish the recursive loop completely. We're left with the path for any amount of splits and joins.

This might not be the best option and with bigger and really complex maps it might not fully 100% work but with some tweaks on that level of difficulty i think it will be fine.

---
Tags: c++, path-finding, sfml, tower-defense
---


# Question
Title: How to increase difficulty of a catching game
I'm developing a game where products fall from the sky, and you need to catch them. A bomb also falls, and if you catch it, you die.

I have 3 different products with 3 different scores.

I want the game to get harder as time passes, but if I start incrementing the amount of bombs appearing, there comes a point where only bombs appear.

How can I increase the difficulty of this game without falling into a state with only bombs?

# Answer
* First of all, punish the player for missing multiple objects in a row, so they can not just ignore objects that seem difficult to catch.
* Increase the falling speed and frequency, so the player needs to react faster.
* Come up with more interesting falling patterns. Like objects which fall at an angle or in a curve. This increases the cognitive load for the player.
> 2 votes

# Answer
You can define the chance to spawn an object and a chance to spawn a bomb into a percentage. As the game progresses you can increase the percentage for bomb spawn while decreasing the percentage for object spawn. This way you will be able to control your gameflow without worrying about not spawnning objects and being able to cap the percentage of bomb spawn. I don't know how to implement the system in code, you're going to have to figure it out yourself, but a good place to start is an article on lootboxes, as they deal with percentages. Link for the first article: https://medium.com/@guilhermegm/unity-simple-loot-system-d181220e6542/.
> 1 votes

# Answer
You can use a weighted random. That means that you assign a weight to each possibility… Then to compute the probability of one of them, you divide its weight by the sum of all weights.

*See How do I create a weighted collection and then pick a random element from it?.*

Thus, you would be able to make one possibility (e.g. generating a bomb) more likely by increasing its weight, without reducing the weight of the others. This way their probability would never reaches zero.

---

By the way, a pretty old trick to increase difficulty is to make the game go faster.

---

**Addendum**: An alternative to increase the difficulty by making bad things more frequent, is to increase the difficulty by making good things less frequent. For example, if you introduce power-ups, you can make them progressively less frequent. Some power-up ideas:

* Reduce speed
* Invulnerability from bombs
* Score multiplier
> 0 votes

# Answer
How about instead of increasing the number of bombs, try changing the bomb size. Larger bombs would occupy more space to make it harder to dodge and smaller bombs would take less space but fall quicker This way players would need to decide whether timing their movement to catch a product or ignoring a product covered with a bomb, would be better. You can do this by simply offsetting the sprite, collision size, and falling speed.
Make sure to place a minimum and maximum range when doing this.
> 0 votes

---
Tags: game-design, algorithm, godot, difficulty
---


# Question
Title: How do I move an object along its local axis?
I am new to computer graphics and am trying to make a simple little game where I can move a cube around with the keyboard. I have it so you can rotate the cube with the arrow keys, and I wanted to make it move forward, back, left and right based on which way it was rotated. I saw a similar question on here posted in 2012 (Translate along local axis).I tried to do what they suggested, and it only works when the x, y, and z rotations are 0. If my cube is rotated, it seems to move in a circle. I am not sure if I misunderstood or if I implemented it wrong.

these are my rotation matrices. the x is the x rotation in degrees converted to radians, and so on for y and z.

```
xrot_mat = [[1,0,0,0],[0,np.cos(x*CONVERT),np.sin(x*CONVERT),0],[0,-np.sin(x*CONVERT),np.cos(x*CONVERT),0],[0,0,0,1]]
xrot_mat = np.array(xrot_mat)

yrot_mat = [[np.cos(y*CONVERT),0,-np.sin(y*CONVERT),0],[0,1,0,0],[np.sin(y*CONVERT),0,np.cos(y*CONVERT),0],[0,0,0,1]]
yrot_mat = np.array(yrot_mat)

zrot_mat = [[np.cos(z*CONVERT),np.sin(z*CONVERT),0,0],[-np.sin(z*CONVERT),np.cos(z*CONVERT),0,0],[0,0,1,0],[0,0,0,1]]
zrot_mat = np.array(zrot_mat)

```

I multiplied the x by the y and the answer of that by z (left to right order: x,y,z).

I then multiplied

`ztrans_mat = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,1,1]] ztrans_mat = np.array(ztrans_mat)`

by the product of those 3 matrices, with ztrans\_mat on the left of the rotation matrix.

Finally, I multiplied

```
pos= Gf.Vec3d(position.Get())
fourd= Gf.Vec4d(pos[0],pos[1],pos[2],1)

```

with fourd (the cubes x, y, and z coordinate) on the left of the rotation matrix multiplied by the translation matrix.

Sorry to make this so long, I just tried to give as much information as possible. I am stuck and starting to get a little frustrated, since I feel so close yet so far.

If you need any clarification or any additional information, please let me know. Thank you in advance for any help you can give me!

# Answer
> 1 votes
If I understand correctly, you are transforming the position vector by the rotation matrix. Which would explain the mentioned circular motion.

Instead you want to transform the un-rotated movement vector (e.g. a vector in the direction the cube would move if it weren't rotated) by the rotation matrix. Which gives you the movement vector you would add to the position vector.

*It is also possible to extract a direction vector from the rotation matrix, then scale it according the distance you want, which gives you a movement vector. See Translating an object along its heading.*

# Answer
> 0 votes
Or you could just use basic maths. Calculate the local axis using formula y=ax+B Use two static points on the object. Do two lines. Calculate a and B. And then you have lokal axis. Every move you make the object do will have movement on X and formula for movement on y axis.

# Answer
> 0 votes
Your rotation matrix tells you which world axes are the object's local axes. You can directly read these vectors from the matrix without any processing:

If you want to see which world direction is the object's local X direction, just read it directly from the first column of the matrix. The second column tells you the Y direction, and the third column tells you the Z direction. You can also see how the translation is the "local nothing direction".

(note: I think this is right, but I always get matrix order confused, so it might actually be the first row)

---
Tags: 3d, rotation, python, transformation
---


# Question
Title: Manually trying to start AR Core XR Loader, but its Subsystems won't start?
I'm trying to implement that in **one scene** I start the **Google Cardboard XR Loader**, and in the **other scene** I start the **AR Core/AR Kit XR Loader**.

This is how I start the loader required for the scene:

```
 var init = XRLoaderToBeLoaded.Initialize();
 var start = XRLoaderToBeLoaded.Start();
 //  (and deinit+stop them when leaving the scene)

```

Both XR Loaders are **initialized and started successfully**, they return **true**.

With **Google Cardboard everything works fine**.

With **AR Core** I make the **AR Session active** after the XR Loader is fully started (I even tried waiting 5 seconds), but it says basically that **no AR Subsystems are available**.

> No active UnityEngine.XR.ARSubsystems.XRCameraSubsystem is available. Please ensure that a valid loader configuration exists in the XR project settings.
>
> No active UnityEngine.XR.ARSubsystems.XRSessionSubsystem is available. Please ensure that a valid loader configuration exists in the XR project settings.
>
> No active UnityEngine.XR.ARSubsystems.XRPlaneSubsystem is available. Please ensure that a valid loader configuration exists in the XR project settings.
>
> No active UnityEngine.XR.ARSubsystems.XRRaycastSubsystem is available. Please ensure that a valid loader configuration exists in the XR project settings.
>
> No active UnityEngine.XR.ARSubsystems.XRAnchorSubsystem is available. Please ensure that a valid loader configuration exists in the XR project settings.
>
> No active UnityEngine.XR.XRInputSubsystem is available. Please ensure that a valid loader configuration exists in the XR project settings.

This is the stacktrace for these errors:

```
UnityEngine.XR.ARFoundation.SubsystemLifecycleManager`3:GetActiveSubsystemInstance()
UnityEngine.XR.ARFoundation.SubsystemLifecycleManager`3:EnsureSubsystemInstanceSet()
UnityEngine.XR.ARFoundation.SubsystemLifecycleManager`3:OnEnable()

```

It seems that for some reason **XRLoader.Start() doesn't start (all?) the Subsystems it needs**.

I tried starting them with `XRGeneralSettings.Instance.Manager.StartSubsystems();` and it indeed **started the subsystems**! Now AR works as well!

But the problem is that this method always starts the **subsystems of the first loader in the loader list.**

So when I enter **Google Cardboard VR... AR Core subsystems start up!**

Which doesn't seem to cause any obvious issues right now, but it's better to be cautious: they shouldn't be running in VR for sure.

Any idea how could I solve this issue in a nice way? Is this a design flaw in the XR Management Kit? Am I misunderstanding something? Thanks in advance!

# Answer
> 0 votes
**Turns out that there is a bug in the package itself.**

Previously it seemed straightforward to just

* 1. **Reorder the list** of `activeLoaders` in the Manager so that my desired loader is the first element in the list.
* 2. Thus **I can use the methods of** `XRGeneralSettings.Instance.Manager` to manage the lifecycle of the chosen loader because it always use the **first loader** in the `activeLoaders` list:
    + `InitializeLoader()`,
    + `StartSubsystems()`,
    + `StopSubsystems()`
    + and `DeinitalizeLoader()`.

This is how I reordered the list, but `TrySetLoaders(`) always **failed to reorder the list**, it returned false.

```
private bool MoveLoaderToFrontOfLoaderList(XRLoader loader)
{
    var reorderedLoaders = new List<XRLoader>(Manager.activeLoaders);
    reorderedLoaders.Remove(loader);
    reorderedLoaders.Insert(0, loader);
    return Manager.TrySetLoaders(reorderedLoaders);
}

```

**Turns out the package has a bug:**

* **currently m\_RegisteredLoaders is never populated.**
* While `TryAddLoader()` (thus `TrySetLoaders()` as well) checks whether the **loader is registered or not**.
* This means that **runtime modification of the active loaders is not possible** right now.

Here's a class which fixes this issue by populating `m_RegisteredLoaders`:

```
public static class XRGeneralSettingsFix
{
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
    private static void UpdateRegisteredLoadersList()
    {
        var xrSettingsManager = XRGeneralSettings.Instance.Manager;
        var bindings = BindingFlags.Instance | BindingFlags.NonPublic;

        var registeredLoadersField = xrSettingsManager.GetType().GetField("m_RegisteredLoaders", bindings);
        var registeredLoaders = registeredLoadersField.GetValue(xrSettingsManager) as HashSet<XRLoader>;

        if (registeredLoaders.Count == 0)
        {
            foreach (var activeLoader in xrSettingsManager.activeLoaders)
            {
                registeredLoaders.Add(activeLoader);
            }
        }
    }
}

```

**Sources and the issues themselves:**

---
Tags: unity, mobile, virtual-reality, augmented-reality
---


# Question
Title: How to make a Minecraft like world round?
I'm interested in making a Minecraft-like voxel world that's spherical.

Idea is that there is a sphere which consists of cubes like in Minecraft but they are on the surface of it. The player can go around the world and come back to their starting point.

How can I build something like this?

# Answer
> 1 votes
After 9 years I found nicer solution.

Since the world do not need to be ideal we can a bit "cheat" by allowing some error from ideal cube. Jordan Peck has proposed solution like this:

If we take just a splice of this solution we can create spherical worlds without "space folding".

Demo and more videos can be found here: Jordan Peck home page

# Answer
> 2 votes
You can't represent a sphere by cubes in a nice way. There is always going to be a distortion.

The 'best'/easiest way would probably be a cubemap approach. Check out this page for an interesting discussion about it. The image about halfway down of a cube and sphere shows the distortion of the squares. It is quite large.

If you are not constrained to cubes, then this question recieved a lot of useful information regarding spherical representatons. Triangles or hexagons are a slightly better fit than cubes.

# Answer
> 0 votes
If the player won't be able to ever see it as a sphere (eg. by going to high altitude), you can fake it. Make 'normal' voxel world, but wrap it at the borders. Trying to load chunk \[-1, 5\]? Return \[MAX\_CHUNK, 5\]. Want to visit \[MAX\_CHUNK+1, 5\]? Oh, you mean \[0, 5\].

This way you won't get nice "hills rising from above the horizon as you get closer" effect, but it can be seen by the player as a normal draw distance limitation. You also will not be able to dig a tunnel through the core of the planet. On the other side, programming it is pretty straightforward and it should work as fast as normal voxel world.

You can add shader warping the models as if the world was a sphere, but observed curvature might not match world's size.

---
Tags: 3d, geometry, voxels, sphere, planet
---


# Question
Title: Climate/weather model for turn-based game
I am looking for a model to simulate weather patterns over long time periods on a tilemap.

The basic idea is to have 3 tile types:

* mountains
* land
* water

Over the course of game, the climate of land and mountain tiles should change (desert/grass/snow...) The players should be able to influence climate of tiles by building canals, dams, removing mountains, etc.

For this I need model to calculate weather patterns, especially determine tiles on which it will rain.

The current idea is that rain should depend on height of the tile, proximity of mountains/lakes/rivers/shielding of ocean by mountains...

Also I would like to achieve a behaviour, when rivers can dry up/lower the amount of water they have. For example, if rivers were to originate in mountain tiles with snow, then changing the mountain tile climate would result in drying up of the river.

I understand that it is unfeasible to solve differential equations in a game, therefore I am looking for a simple model that would let me fake realistic climate behaviour.

As you can probably see, I don't have crystal clear concept of what I want to achieve, just the basic outline.

Therefore, I would appreciate any ideas of how to solve similar problems.

# Answer
You could approach this with a cellular automaton.

Each of your tiles would have a series of attributes. For example humidity, wind, height, rainfall… And so on.

Then you are going to make iterations. *You would have to tweak how often. It could be one per turn, one each few turns, or even multiple per turn.* And each iteration you update those attributes according to rules based on the surrounding tiles. For example, rainfall increases if there are tiles with higher elevation around. You can make the rules as complex as you need. This also depends on how weather should interact with other mechanics of the game, so feel free to deviate from realism.

You would also have to define some minimum and maximum for the attributes, and clamp the values to that.

Similarly, you could define that when an attribute is goes from certain range to another, the tile should change.

---

You might even make the tiles change probabilistically. For example, if the humidity goes below certain threshold the tile has a 50% chance of drying up that iteration, otherwise you clamp the humidity above the threshold.

Another modification you can do is defining rules based on the distance to a tile of certain type.

And yet another one is that attributes could not be scalars. For example, wind could be a vector, and then you use the dot product to see how much wind a tile gets form an adjacent one. You can do something similar with water flow.

---

Also, you could change the resolution of your simulation. For example, define blocks of eight by eight tiles, and treat them as a single unit… A chunk. And it is the chunk which has attributes, that update according rules based on surrounding chunks. You might even do a broad simulation with chunks and some attributes and a finer one with tiles and other attributes. And interleave iterations of one and the other.

If you need the chunk attributes for the tile simulation, the simpler solution is to use the value form the chunk the tile belongs to. But if you want it to be smooth, then base it on the a weighted average of the attributes of nearby chunks (including the chunk the tile belongs to) where the weight falls off as the tile is further away from their center… Which also means… chunks don't have to be a regular tiling! You could come up with rules to decide where to place them… But that is probably making it more complicated that it needs to be.

---

By the way, who says you have to do the iterations for all tiles at once? You can do odd tiles one iteration and even tiles the next, and so on. Which might be useful if iterations are too slow.
> 1 votes

---
Tags: game-design, terrain, simulations, turn-based, 4x
---


# Question
Title: NullReference exception with a singleton input manager
I've been using the new input system to simulate touch in my game, it works perfectly but only with the input manager(which is a singleton for the ease of use), when I add the PlayerMover script it returns me nullReference. The error appears in two scripts at the same time. The input manager is in the scene.

InputManager script(with default execution order of -1):

```
public class InputManager : Singleton<InputManager>
{
    private PlayerInput _playerInput;
    public Action<Vector2> _OnScreenTouched;
    private void Awake()
    {
        _playerInput = new PlayerInput();
    }
    private void OnEnable()
    {
        _playerInput.Enable();
    }
    private void OnDisable()
    {
        _playerInput.Disable();
    }
    private void Start()
    {
        _playerInput.Player.Turn.performed += ctx => ScreenTouched(ctx);

    }
    private void ScreenTouched(InputAction.CallbackContext context)
    {
        _OnScreenTouched?.Invoke(_playerInput.Player.Turn.ReadValue<Vector2>());

    }
}

```

Singleton class:

```
public class Singleton<T> : MonoBehaviour where T : Component
{
    private static T _instance;
    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                var objs = FindObjectOfType(typeof(T)) as T[];
                if (objs.Length > 0)
                    _instance = objs[0];
                if (objs.Length > 1)
                    Debug.LogError("There is more than one" + typeof(T).Name + "in the scene.");
                if(_instance == null)
                {
                    GameObject obj = new GameObject();
                    obj.hideFlags = HideFlags.HideAndDontSave;
                    _instance = obj.AddComponent<T>();
                }
            }
            return _instance;
        }
    }
}
public class SingletonPersistent<T> : MonoBehaviour where T : Component
{
    public static T Instance { get; private set; }
    public virtual void Awake()
    {
        if (Instance == null)
        {
            Instance = this as T;
            DontDestroyOnLoad(this);
        }
        else
        {
            Destroy(gameObject);
        }

    }
}

```

PlayerMovement script:

```
public class PlayerMovement : MonoBehaviour, IMovable
{
    [SerializeField] private float _movementAmmount;
    private InputManager _inputManager;
    private Camera _camera;

    private void Awake()
    {
        _inputManager = InputManager.Instance;
        _camera = Camera.main;
    }
    private void OnEnable()
    {
        _inputManager._OnScreenTouched += Move;
    }
    private void OnDisable()
    {
        _inputManager._OnScreenTouched -= Move;
    }

    public void Move(Vector2 screenPosition)
    {
        if (screenPosition.x <= Screen.width / 2)
        {
            transform.position -= new Vector3(_movementAmmount,0,_camera.nearClipPlane);
        }
        if (screenPosition.x > Screen.width / 2)
        {
            transform.position += new Vector3(_movementAmmount, 0, _camera.nearClipPlane);
        }
    }
}

```

Interface for PlayerMovement:

```
public interface IMovable
{
    void Move(Vector2 screenPosition);
}

```

# Answer
> 1 votes
It appears I made a typo, thank you @Zibelas for pointing that out.

Instead of using `FindObjectsOfType` I used `FindObjectOfType`.

`FindObjectsOfType` returned the array, while `FindObjectOfType` returned a single object. Trying to cast that single object `T` to an array with `as T[]` caused `objs` to be set to `null`.

---
Tags: unity, c#, design-patterns
---


title: Unreal Engine Movie Render Queue Plugin

text:
# Question
Title: Unreal Engine Movie Render Queue Plugin
I am developing a plugin to stylize videos and images rendered through Movie Render Queue. What I want to do now is capture the image processed by Movie Render Queue at runtime and stylize the images one by one and encode it into a movie. Which C++ API can be used to capture the images from Movie Render Queue at runtime (while rendering) not on disk?

# Answer
> 0 votes
To capture images from a rendering program like Movie Render Queue at runtime, you can use a C++ API such as OpenCV. OpenCV is a popular, open-source library for computer vision tasks, and it includes a range of functions for capturing, processing, and encoding images and video.

Here is an example of how you could use OpenCV to capture an image from Movie Render Queue and stylize it:

```
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main() {
  // Initialize a capture object to grab frames from Movie Render Queue
  VideoCapture capture(0);

  // Check if the capture object was initialized successfully
  if (!capture.isOpened()) {
    cout << "Failed to initialize capture" << endl;
    return -1;
  }

  // Create a window to display the stylized images
  namedWindow("Stylized", WINDOW_AUTOSIZE);

  // Loop until the capture is stopped
  while (true) {
    // Grab a frame from the capture
    Mat frame;
    capture >> frame;

    // Check if the frame was grabbed successfully
    if (frame.empty()) {
      cout << "Failed to grab frame" << endl;
      break;
    }

    // Stylize the frame here...

    // Display the stylized frame
    imshow("Stylized", frame);

    // Wait for a key press to continue
    int key = waitKey(1);
    if (key != -1) {
      break;
    }
  }

  return 0;
}
```

In this example, the VideoCapture object is initialized with a capture index of 0 to grab frames from the default video input (e.g. the webcam). You can specify a different index or a file path to capture from a specific video source.

The capture \>\> frame line grabs a frame from the capture, and the imshow() function displays the frame in a window. The waitKey() function is used to pause the program until a key is pressed, which allows you to view the stylized frames one by one.

You can use the various functions in the OpenCV library to stylize the frames as you wish, and then use the VideoWriter class to encode the stylized frames into a movie file. For more information and examples, you can refer to the OpenCV documentation: https://docs.opencv.org/master/

---
Tags: unreal-4, unreal, plugin
---


# Question
Title: Rotating a Unity Texture2D 90/180 degrees without using GetPixels32 or SetPixels32? (To avoid heap fragmentation)
I have a script which is loading a photo from `path` into a texture (`photoThumbT2D`), then rotating it:

```
                byte[] byteArray = File.ReadAllBytes(path);

                UnityEngine.Object.Destroy(photoThumbT2D);
                photoThumbT2D = new Texture2D(0, 0);
                photoThumbT2D.LoadImage(byteArray);
                RotateImage(photoThumbT2D, -90);

```

Where the RotateImage function is adapted from here as:

```
public static void RotateImage(Texture2D originTexture, float angle) {
        int width = originTexture.width;
        int height = originTexture.height;
        float halfHeight = height * 0.5f;
        float halfWidth = width * 0.5f;

        Color32[] originPixels = originTexture.GetPixels32();
        Color32[] rotatedPixels = originTexture.GetPixels32();

        int oldX;
        int oldY;

        float phi = Mathf.Deg2Rad * angle;
        float cosPhi = Mathf.Cos(phi);
        float sinPhi = Mathf.Sin(phi);

        for (int newY = 0; newY < height; newY++) {
            for (int newX = 0; newX < width; newX++) {
                rotatedPixels[newY * width + newX] = new Color32(0, 0, 0, 0);
                int newXNormToCenter = newX - width / 2;
                int newYNormToCenter = newY - height / 2;
                oldX = (int)(cosPhi * newXNormToCenter + sinPhi * newYNormToCenter + halfWidth);
                oldY = (int)(-sinPhi * newXNormToCenter + cosPhi * newYNormToCenter + halfHeight);
                bool InsideImageBounds = (oldX > -1) && (oldX < width) && (oldY > -1) && (oldY < height);

                if (InsideImageBounds) {
                    rotatedPixels[newY * width + newX] = originPixels[oldY * width + oldX];
                }
            }
        }

        originTexture.Reinitialize(width, height);
        originTexture.SetPixels32(rotatedPixels);
        originTexture.Apply();

    }

```

However, this application of `RotateImage` is leading to what I believe is a heap fragmentation problem where the more times it runs the more memory usage piles up in the profiler. This is discussed here.

In my case, it manifests in Android only (no problem in Editor) as a steady increase in GC Used Memory (Tracked Memory, In Use) until the app crashes:

In the Memory Profiler I get a new chunk of Managed Heap created for every time it runs until everything crashes (here there about 13 identical blue chunks created):

Apparently the only solution is to use `NativeArray<Color32> nativeArray = texture2D.GetRawTextureData<Color32>();` and work with that, but since the NativeArray is a direct representation of the Texture data, I'm not sure if it's possible mathematically to rotate it without making a new copy to work from. And if you make a new array copy of the actual color data, you will get the same heap problems as with GetPixels32 and SetPixels32.

Any thoughts or solutions?

---

# Addendum

Unfortunately, DMGregory, I learned from your method but I am still having trouble with your solution.

***MEMORY ACCUMULATION***

I have tested, and even just the code:

```
        photoThumbT2D = Resources.Load<Texture2D>("bigphoto");
        photoThumbnailVE.style.backgroundImage = photoThumbT2D;

        buttonClickedEvent += delegate {
            Debug.Log("RUN CLICK");

            var texels = photoThumbT2D.GetRawTextureData<Color32>();
            var texelsCopy = System.Buffers.ArrayPool<Color32>.Shared.Rent(texels.Length);
            //Unity.Collections.NativeArray<Color32>.Copy(texels, texelsCopy, texels.Length);
            System.Buffers.ArrayPool<Color32>.Shared.Return(texelsCopy);
};

```

Continues to trigger memory accumulation in Unity for Android in the same manner as the OP code. Thus in even this manner the Rent and Return functions are leading to memory accumulation.

Can you think of any reason this would not be happening? I have Incremental GC collection turned on in Android. I can't make any sense of it. Might it be because it's being run as a delegate or the parent object running it was created by a coroutine (which should be long gone)?

**I have tested further and this can be solved instead by using a static List to store the duplicate data in but I would love to know why any other method is causing this problem.**

# Answer
Two tricks we can use to get the `RotateImage` method down to zero allocations (in steady state):

* We'll use `GetRawTextureData<T>` to get a view into the texture's existing CPU-side memory buffer, to edit it directly without creating a new array to call `SetPixels` with.
* We'll use `System.Buffers.ArrayPool` to borrow and return a reusable array to store the old data. This can get recycled for future calls, rather than being claimed as garbage and recreated anew.

```
public static void RotateImage(Texture2D tex, float angleDegrees)
{
    int width = tex.width;
    int height = tex.height;
    float halfHeight = height * 0.5f;
    float halfWidth = width * 0.5f;

    var texels = tex.GetRawTextureData<Color32>();
    var copy = System.Buffers.ArrayPool<Color32>.Shared.Rent(texels.Length);
    Unity.Collections.NativeArray<Color32>.Copy(texels, copy, texels.Length);

    float phi = Mathf.Deg2Rad * angleDegrees;
    float cosPhi = Mathf.Cos(phi);
    float sinPhi = Mathf.Sin(phi);

    int address = 0;
    for (int newY = 0; newY < height; newY++)
    {
        for (int newX = 0; newX < width; newX++)
        {
            float cX = newX - halfWidth;
            float cY = newY - halfHeight;
            int oldX = Mathf.RoundToInt(cosPhi * cX + sinPhi * cY + halfWidth);
            int oldY = Mathf.RoundToInt(-sinPhi * cX + cosPhi * cY + halfHeight);
            bool InsideImageBounds = (oldX > -1) & (oldX < width)
                                   & (oldY > -1) & (oldY < height);

            texels[address++] = InsideImageBounds ? copy[oldY * width + oldX] : default;
        }
    }

    // No need to reinitialize or SetPixels - data is already in-place.
    tex.Apply(true);

    System.Buffers.ArrayPool<Color32>.Shared.Return(copy);
}

```

You'll still see an allocation the first time you call this, or when you call it with a larger image than you've used before. That's from the `ArrayPool` allocating a new array for the requested size. But repeat calls will be able to re-use the array from the pool and so you won't see continually increasing memory use or fragmentation.

If `ArrayPool` isn't working as desired on mobile (maybe it's emulated as just `new` to avoid reserving large blocks of RAM on modest phones), you can get a similar effect by reusing your own persistent `static List<Color32> tempCopy;`, growing it as needed.
> 3 votes

---
Tags: unity, textures, memory
---


# Question
Title: Using GetRawTextureData<Color32>() in Unity with non RGBA32 textures?
I am trying to manipulate a Texture2D using `GetRawTextureData<Color32>()` as this does not require extra memory to be allocated like `GetPixels32()` does.

However, I can't make sense of the data it is providing or how to use it.

`GetRawTextureData<Color32>()` is directly compatible with RGBA32 Textures as per: "RGBA32 texture format data layout exactly matches Color32 struct" at this page.

But if a Texture2D is loaded from a JPG byte Array and it has an RBG24 format, the output it provides is nonsense:

```
        var texelsReal = texture.GetPixels32();
        var texelsColor32 = texture.GetRawTextureData<Color32>();
        var texelsColor = texture.GetRawTextureData<Color>();

        for (int i = 0; i < 200; i++) {
            Debug.Log("TEXEL REAL: " + texelsReal[i] + " || TEXEL COLOR32: " + texelsColor32[i] + " TEXEL COLOR: " + texelsColor[i] + " || texture format " + texture.format);
        }

```

This will output something like:

```
TEXEL REAL: RGBA(120, 146, 233, 255) || TEXEL COLOR32: RGBA(225, 146, 190, 174) || TEXEL COLOR: RGBA(0.003, 0.000, 0.000, 183.106) ||Texture Format RGB24

```

Only the `GetPixels32()` version is actually legitimate and the others are total nonsense.

I need `GetRawTextureData<T>` to contain real data, as I want to then reallocate pixels by shifting them around using it as per this thread.

But when I try that currently, I get garbled nonsense because I'm moving around nonsense from one place to another and it then seems to apply that nonsense at the end and ruin the photo.

I tried converting the texture like this:

```
Texture2D copyTex = new Texture2D(photoThumbT2D.width, photoThumbT2D.height, TextureFormat.RGBA32, false);
bool succeeded = Graphics.ConvertTexture(photoThumbT2D, copyTex);
Debug.Log(" CONVERT SUCCESS " + succeeded + " FORMAT " + copyTex.format + " ORIG " + photoThumbT2D.format);
copyTex.Apply(true); //breaks it for unknown reasons...
photoThumbT2D = copyTex;

```

But this just creates a grey texture. I was instructed in the other thread to use a struct like:

`public struct RGB24 { public byte r, g, b }`

Then presumably:

`var texels = texture.GetRawTextureData<RBG24>();`

But this gives me an error saying no implicit conversion is possible. I don't know how to solve that if I can.

Any solutions? Thanks.

# Answer
Just make your method generic on the texel data type:

```
static void RotateImage<T>(Texture2D tex, float angleDegrees) where T:struct {
    int width = tex.width;
    int height = tex.height;
    float halfHeight = height * 0.5f;
    float halfWidth = width * 0.5f;

    var texels = tex.GetRawTextureData<T>();
    var copy = System.Buffers.ArrayPool<T>.Shared.Rent(texels.Length);
    Unity.Collections.NativeArray<T>.Copy(texels, copy, texels.Length);

    int oldX;
    int oldY;

    float phi = Mathf.Deg2Rad * angleDegrees;
    float cosPhi = Mathf.Cos(phi);
    float sinPhi = Mathf.Sin(phi);

    int address = 0;
    for (int newY = 0; newY < height; newY++)
    {
        for (int newX = 0; newX < width; newX++)
        {
            float cX = newX - halfWidth;
            float cY = newY - halfHeight;
            oldX = Mathf.RoundToInt(cosPhi * cX + sinPhi * cY + halfWidth);
            oldY = Mathf.RoundToInt(-sinPhi * cX + cosPhi * cY + halfHeight);
            bool InsideImageBounds = (oldX > -1) & (oldX < width) & (oldY > -1) & (oldY < height);

            texels[address++] = InsideImageBounds ? copy[oldY * width + oldX] : default;
        }
    }
    tex.Apply(true);

    System.Buffers.ArrayPool<T>.Shared.Return(copy);
}

```

Then choose what underlying type to use to match the number of bytes in your texture format (a few examples shown, but not exhaustive):

```
public static void RotateImage(Texture2D tex, float angleDegrees)
{
    switch (tex.format) {
        // 1 byte per texel.
        case TextureFormat.Alpha8:
            RotateImage<byte>(tex, angleDegrees);
            break;

        // 2 bytes per texel.
        case TextureFormat.ARGB4444:
        case TextureFormat.R16:
            RotateImage<ushort>(tex, angleDegrees);
            break;

        // 3 bytes per texel.
        case TextureFormat.RGB24:
            RotateImage<(byte, byte, byte)>(tex, angleDegrees);
            break;

        // 4 bytes per texel.
        case TextureFormat.ARGB32:
        case TextureFormat.RGBA32:
            RotateImage<Color32>(tex, angleDegrees);
            break;

        // 4 floats = 16 bytes per texel.
        case TextureFormat.RGBAFloat:
            RotateImage<Color>(tex, angleDegrees);
            break;

        // TODO: Other formats, as needed.
        default:
            Debug.Log($"Unsupported texture format: {tex.format}");
            break;
    }
}

```

I've been quick and dirty here, lumping together formats that use "similar enough" data layouts, in terms of the byte stride between texels. This is good enough if you just want to copy the whole texel value from one place to another, but can land you in trouble if you want to inspect individual component values. For instance, if your image is in ARGB format, casting it to `Color32` will put its alpha value in the `.r` component, red in the `.g`, green in the `.b`, and blue in the `.a`.

If that matters to you, you can define your own structs with the needed layouts:

```
public struct Color32ARGB {
    public byte a;
    public byte r;
    public byte g;
    public byte b;
}

public struct Color24RGB {
    public byte r;
    public byte g;
    public byte b;
}

```

...etc., and use those.

---

Or, you can just use bytes for everything:

```
public static int BytesPerTexel(TextureFormat format)
{
        switch (tex.format) {
        // 1 byte per texel.
        case TextureFormat.Alpha8:
            return 1;

        // 2 bytes per texel.
        case TextureFormat.ARGB4444:
        case TextureFormat.R16:
            return 2;

        // 3 bytes per texel.
        case TextureFormat.RGB24:
            return 3;

        // 4 bytes per texel.
        case TextureFormat.ARGB32:
        case TextureFormat.RGBA32:
            return 4;

        // 4 floats = 16 bytes per texel.
        case TextureFormat.RGBAFloat:
            return 16;

        // TODO: Other formats, as needed.
        default:
            Debug.Log($"Unsupported texture format: {tex.format}");
            return -1;
    }
}

```

```
static void RotateImage(Texture2D tex, float angleDegrees) {

    int bytesPerTexel = BytesPerTexel(tex.format);
    int width = tex.width;
    int height = tex.height;
    float halfHeight = height * 0.5f;
    float halfWidth = width * 0.5f;

    var texels = tex.GetRawTextureData<byte>();
    var copy = System.Buffers.ArrayPool<byte>.Shared.Rent(texels.Length);
    Unity.Collections.NativeArray<byte>.Copy(texels, copy, texels.Length);

    int oldX;
    int oldY;

    float phi = Mathf.Deg2Rad * angleDegrees;
    float cosPhi = Mathf.Cos(phi);
    float sinPhi = Mathf.Sin(phi);

    int address = 0;
    for (int newY = 0; newY < height; newY++)
    {
        for (int newX = 0; newX < width; newX++)
        {
            float cX = newX - halfWidth;
            float cY = newY - halfHeight;
            oldX = Mathf.RoundToInt(cosPhi * cX + sinPhi * cY + halfWidth);
            oldY = Mathf.RoundToInt(-sinPhi * cX + cosPhi * cY + halfHeight);
            bool InsideImageBounds = (oldX > -1) & (oldX < width) & (oldY > -1) & (oldY < height);

            if (InsideImageBounds) {
                int from = oldY * width + oldX;
                for (int i = 0; i < bytesPerTexel; i++)
                    texels[address++] = copy[from++];
            } else {
                for (int i = 0; i < bytesPerTexel; i++)
                    texels[address++] = default;
            }
        }
    }
    tex.Apply(true);

    System.Buffers.ArrayPool<byte>.Shared.Return(copy);
}

```
> 0 votes

---
Tags: unity, textures, graphics
---


title: Handling infinite combos

text:
# Question
Title: Handling infinite combos
I'm working on a game where entities can be affected by 'statuses' that can have an effect in response to any entity event (lost\_life, turn\_began...).

I'm searching for good ways of handling this kind of combo, where an entity have both statuses:
"On taking damage, heal 1"
"On healing, take 1 damage"

Until now, ways i thinked of include:

* Only allow automatic responses to direct actions (So a status won't trigger another):
*Not acceptable as it limit too much the game design.*
* Pay attention while game-designing to not have circular interactions:
*Not acceptable as I want an open modding interface.*
* Detect when a loop occurs programmatically:
*Seems impossible as the loop can theorically be infinitely large.*
* Having a maximum amount of nested resolving statuses:
*Actually my best guess.*

I searched informations about that online, but couldn't find more relevant information than the rules of physical card games as Magic or Yu-Gi-Oh. These could be useful, but I didn't found anything about their implementation in the related videogames.

Do you know any technique to handle this kind of behavior ? Or any resource on the subject ?

Thanks.

Edit: I should have mentionned that my game is turn based, and statuses are called sequentially, hence all happening in the same frame.

# Answer
> 2 votes
The first thing that comes to mind is limiting an status to only resolve once per turn. Which would be by setting a flag as Romen suggested in comments.

---

One option to relax that it is to limit each status to resolve once *per cause*.

For example, with statuses:

* "On taking damage, heal 1"
* "On healing, take 1 damage"

When the entity takes damage from an attack, this happens:

* It takes damage from attack
* On taking damage, heal 1 (because of attack)
* On healing, take 1 damage (because status "On taking damage, heal 1")
* On taking damage, heal 1 (because status "On healing, take 1 damage")

The status "On healing, take 1 damage" won't trigger again, because it did already trigger from the "On taking damage, heal 1" status.

---

Another option to relax the rule is to say that you can have an status an integer number of times. In which case you could go from a flag to a counter.

This would also be useful if you stack statuses instead of allowing duplicates… Yet, consider making the status take the size of the stack as input to compute the effect.

---

I would still consider having a maximum of statuses resolved per turn, just to make sure a turn does not take too long to resolve (user experience).

---

By the way, when you have multiple statuses with their precondition satisfied, you need to pick which one to resolve. I would start with FIFO (a queue), so older status resolves first. However, might introduce priorities (a priority queue), so the oldest status of the higher priority resolves first.

---
Tags: game-design, architecture
---


# Question
Title: Determine End-to-End Latency on Laptop or PC
I'm working on a project to determine the end-to-end latency of a cloud gaming system (i.e., XCloud) on a MacBook.

I believe I have half of the process completed so far:

1. A Javascript web app that logs every single time a user presses a button on their gamepad using the Mozilla GamePad API. The timestamp is calculated as milliseconds in Unix epoch time from the client's end.
2. The server-side of the web app which places each button input and its timestamp into a database so that they can be used at a later time for latency analysis.

Using this, I am able to accurately determine each time I press a button on my gamepad along with the button itself. Now, I would like to figure out the exact time the corresponding frame(s) are displayed onto my screen.

As far as I understand, it seems like the generally accepted approach to determine on-screen changes from gamepad inputs is to set up a high-speed camera and capture the actual frames changing on the display. However, I'd like to use a method that can be automated more easily and takes advantage of the actual hardware on my laptop.

Is there a different approach to this? One that might take advantage of my frame buffer or can determine pixel change on my screen? To anyone who is knowledgeable of this or has done something similar before, can you point me in a better direction? I've done quite a bit of research to solve this problem, but I can't find anything online that somewhat fits my needs.

Thank you to anyone who is reading this!

# Answer
Just comparing time stamps on different devices is not enough to measure network latency, because device clocks are not synchronized within the precision that you care about. These are not precisely-calibrated atomic clocks, they're simple oscillators like the one in your microwave that gradually goes out of sync with the one on your stove or coffee maker. The reason network-connected devices track time better is that they're routinely nudged toward agreement with time servers using Network Time Protocol. As the article states, "NTP can usually maintain time to within tens of milliseconds over the public Internet" - tens of milliseconds is several frames of latency over- or under-estimated if you use this method.

To eliminate synchronization error, you'd want to measure a full round-trip from device A, replied to by device B, and received and processed on device A again. Then you can compare two timestamps measured against A's clock, so there's no synchronization error to deal with. You can divide the total round-trip time by two to estimate one-way latency.

As for the other sources of latency, the reason that high-speed cameras are the preferred option is that they give us a ground truth measurement of the complete end-to-end process, from the mechanical actuation of the button or stick to the emission of visible photons from the screen.

Any system that reads its start and end points from somewhere else in the chain potentially misses some sources of latency:

* Starting your clock when your game loop detects input? What if that input had been buffered in a queue in the device driver for some time before that moment?
* Using screen captures of the system frame buffer? What if this is queued in a longer swap chain, and those bits aren't actually being sent to the display yet? Or what about the delays introduced by the display device's processing and hardware response rates?

So, while you can estimate latency with other methods, it won't give you a true, accurate value that includes all possible sources of latency.
> 0 votes

# Answer
One way to do this without using a high-speed camera is to use a screen capture software that can capture the screen at a high frame rate and record the timestamp for each frame.

To measure the latency between button presses and on-screen changes, you can then use the timestamps from your gamepad input logs and the screen capture software to calculate the time difference between the button press and the corresponding on-screen change.

One example of a screen capture software that can capture the screen at a high frame rate and record timestamps for each frame is OBS Studio. This software allows you to set the frame rate at which the screen is captured and provides a timestamp for each frame in the captured video.

To use OBS Studio to measure the latency between button presses and on-screen changes, you can follow these steps:

* Install OBS Studio on your MacBook and set it up to capture the screen at a high frame rate (e.g., 60 frames per second).
* Start the screen capture in OBS Studio and open the cloud gaming application on your MacBook.
* Use your gamepad to interact with the cloud gaming application and log the timestamps for each button press using the Mozilla GamePad API.
* When you have collected a sufficient number of button press timestamps and screen capture frames, use the timestamps from the gamepad input logs and the screen capture video to calculate the time difference between each button press and the corresponding on-screen change.
> -1 votes

---
Tags: pixel, frame-buffer, gamepad, latency, automated-testing
---


# Question
Title: Structuring a Scriptable Object so that it has a List or an Array of 2 other Scriptable Objects
I created three Scriptable Objects for my Unity word game:

1. FeemData - This is to hold information on letters
2. NeemData - This is to hold information on pronunciation
3. SuperNeemData - This is to hold #1 and #2 together in a single Scriptable Object.

Here's the C# code for the SuperNeemData SO:

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

[CreateAssetMenu(fileName = "New SuperNeemData", menuName = "Super Neem Data", order = 51)]

public class SuperNeemData : ScriptableObject
{
    [SerializeField]
    public FeemData actualFeem;

    [SerializeField]
    public NeemData superNeem;

}

```

So far, so good. But then I created a LevelData, which is meant to hold an arbitrary number of SuperNeemDatas:

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

[CreateAssetMenu(fileName = "New LevelData", menuName = "Level Data", order = 51)]

public class LevelData : ScriptableObject
{
    [SerializeField]
    public List<SuperNeemData> SuperNeemForThisLevel;

}

```

When I go to the Inspector allows me to view and change the SuperNeemDatas in there, like this:

This works OK, but it's not the best workflow. In order to create a SuperNeemData, first I have to go into a separate folder and generate a SuperNeemData Scriptable Object and then drag the FeemData into there... and then drag a NeemData into there... and then go back to LevelData and drag the SuperNeemData Scriptable Object into there.

The whole process takes a lot of extra time and clicks. I'm hoping to change things so that I can drag FeemData and NeemData Scriptable Objects directly into the LevelData Scriptable Object.

In short (I think), I would like the LevelData Scriptable Object to have a List of an Array (with two items: first one is a FeemData and second one is a NeemData). Then if I am understanding things correctly, I could drag a FeemData So and a NeemData SO directly into the LevelData SO... a much easier workflow.

Any advice on how to structure a Scriptable Object so that it has a List of an Array of 2 other Scriptable Objects? Thank you!

# Answer
Hmmm, I'm not sure getting the exact behaviour you want is possible. The thing is that Scriptable Objects, like other UnityEngine.Object, are serialized as references. That is, the information that gets serialized is a reference to the SO, rather than the SO itself, and thus the SO needs to already exist somewhere else. That's why we have this whole drag-the-object-into-a-box business, that is how you handle the references.

Now, a potentially really easy option is to make SuperNeemData not be a scriptable object at all, just a plain old C# class. This has some important downsides (there is no way to save instances as assets to share them between scenes, for example), buuut it makes it so that you can create new instances directly in the inspector of your LevelData class. Whether this works well for your project or not, I don't know.

The other, slightly more involved, solution that I can think of is to create a method in your LevelData class (that you could call with a button or something like that) which creates the SuperNeemData instance in your project and adds it to the List. It's still the same workflow, but faster. Trouble is you would need to have a look into creating Custom Editors (although it's way less scary than it sounds, and a good skill to have in general).

You could even combine the two options and have a locally used, serialized, non-SO class to hold the references to both NeemData and FeemData, and then a method that transforms that into a SuperNeemData, instantiates that in your project, and adds the reference to it to your List. But this is my least favourite option, it's kind of messy.

Edit: The idea discussed in the comments:

```
public class SuperNeemData : ScriptableObject
{
    [SerializeField]
    List<AuxNeem> list;

    [System.Serializable]
    public class AuxNeem{
        [SerializeField]
        public FeemData actualFeem;

        [SerializeField]
        public NeemData superNeem;
    }
}

```
> 3 votes

# Answer
It sounds to me like what you need is not actually a new way of structuring your data, but a cleaner way to edit it.

Any time you use Scriptable Objects, you're usually going to find that the best way to input data for them is to use a Custom Editor script. You can make your own little GUI window that allows you to create, reference, and connect Scriptable Objects easy as pie.

There is also, of course, Odin Inspector, a widely used (and fairly cheap) asset on the store that makes custom inspector windows a piece of cake to throw together. If you're not willing to buy an asset for this functionality, though, it's really not as hard as it seems to write your own.

It may seem complicated at first glance, but following a tutorial like this one and looking at the documentation can get you started in no time.

I know this answer is probably long solved, but I hope this helps anyone else looking into a better way to do this sort of thing!
> 2 votes

---
Tags: unity, c#, scriptable-object
---


title: Branchless archetype ECS?

text:
# Question
Title: Branchless archetype ECS?
I lately read an article about branchless programming and how it can effect performance. Since im developing a little archetype based ECS for learning purposes, i wanted to know if theres a way to make it also as branchless as possible.

Typical places for branches are most likely :

* Adding entities ( Archetypes need to check whether its full to allocate new memory... )
* Removing entities ( Archetypes need to check if its small enough to trim memory )
* Query ( If statement to check whether each archetype contains the queried types )
* Get Operations ( Dictionary lookups & possible if statements )

Is there any way to design an archetype ECS without any branches ? Or is this impossible since branches are pretty common for this task ?

# Answer
> 3 votes
As mentioned in the comment above, you can't practically eliminate *all* branches in an ECS written in C#. By the nature of an ECS, you're going to be looping over arrays of components. Every loop has a branch to decide whether to keep looping, and every array access in a managed language like C# has bounds checks to make sure you're not indexing beyond the bounds of the array.

Fortunately in correctly written code, these bounds checks always pass, so they should be predicted correctly by the branch predictor and have practically no cost. There's some evidence I saw recently from examples in Rust that backs that up. Similarly, the branch in a loop can be reliably predicted as "always loop", and it only gets it wrong on the last iteration. (You can reduce this overhead further using `Span<T>` instead of `List<T>`, or fetching a `Span<T>` version just in time)

So, not all branches are equally bad. What you want to avoid are random-looking branches that will frequently mis-predict and cause pipeline stalls.

One of the most common ways to get this is if your arrays of components can contain empty slots from destroyed entities, or entities temporarily disabled. Then every system update needs to have a branch that checks whether this component is valid to act on it before it acts. Since entities can be disabled/destroyed randomly (up to the whims of your game mechanics), those branches can be hard to predict. One good way to solve this, if you can, is to defer entity destruction to the end of a frame, and swap components of destroyed entities to the ends of their respective arrays, keeping living ones densely-packed at the head of the array (and updating ID lookups as necessary in this cleanup step). Then your liveness check just becomes your loop bounds check, and it predicts correctly until the last iteration. This also helps you get optimum cache utilization, since you don't waste precious cache line space on components that will be skipped over.

This is harder if just one component needs to be disabled out of a larger multi-component entity. In that case, you might need to just eat the branch cost (especially if it's a rare occurrence), or look at ways you can make its operation a no-op if you find the branch is a significant performance cost in your profiling. Or you could move the entity to another archetype which has the `Disabled<ComponentType>` component instead of the original `ComponentType`. This can have all the same fields to store the data/state for later re-enabling, but will be ignored by systems looking to update `ComponentType`.

Adding and removing entities should be much less common than iterating them, so this is unlikely to be a major performance sink. In cases where you are adding/removing many entities at once, and your profiling shows a significant cost from all the checks, it's likely you're adding/removing many of the same archetypes. In that case, you can look at batching up these operations. 300 new bullet entities have been requested this frame? I'll do my memory checks and allocations *once* to ensure there's room for 300 more, then bulk-fill that space with certainty that it's there, rather than repeatedly checking and incrementally expanding 300 times.

Queries are ripe for pre-computing. At the start of your game or at the start of a new scene, initialize each system that's going to be active in that scene, and have it register each of the queries it uses. Hand it back an object with a list of matching archetypes (initially empty). Now, each time you spawn a new archetype (not a new entity of an archetype - only do this the first time a new archetype is used), you run through that list of pre-registered queries and check which ones it matches, adding it to the response lists for those queries. Almost all of this work can be done at scene start-up, with zero matching cost per system update, because all the archetypes they need are already listed. Only occasionally will you introduce a new archetype mid-scene, and you only pay its matching cost once.

Your entity lookups could be a single array rather than a dictionary, mapping a sequential ID counter to its current archetype and index in that archetype (updating that book-keeping whenever you do a swap). You can use a free list to fill holes in that array as entities are created and destroyed. A generation number can help you detect when an ID you're holding refers to a now-destroyed entity that's been replaced.

Conditional logic *within* your component updates is a whole different ball game, but now you're outside of what's specific to an ECS, and into regular gamedev challenges.

Just remember: branches are not the greatest evil. You should expend only as much effort avoiding them as your measured profiling data confirms they're causing problems. A pipeline stall sucks, but as long as it's not happening *constantly* you can still get excellent performance.

---
Tags: c#, entity-component-system
---


title: Drawing a line between 2 vectors

text:
# Question
Title: Drawing a line between 2 vectors
I was trying to implement a simple mechanic by drawing a line between the sprite and the mouse, but it's not working that well:

```
extends KinematicBody2D
onready var player = $CollisionShape2D
var pos_two
var pos
func _physics_process(delta):

    var vel = Vector2()
    pos_two = player.get_position()

    pos = get_global_mouse_position()
    look_at(pos)
    if Input.is_action_pressed("movethere"):
        vel = Vector2(400 , 0).rotated(rotation)
    vel = move_and_slide(vel)
func _draw():
    draw_line( pos_two ,pos, Color(255 , 0 , 0))

```

# Answer
*To get it out of the way `Color` takes float in the range from `0.0` to `1.0`.*

---

Given that the code uses `_draw` but not calling `update` I believe that problem was that it was not updating every frame.

*Ah, but you see it move, don't you? I hear you, I'll get back to that.*

To make Godot call `_draw` again you had to add a call to `update` in `_process`.

---

The other issue are the coordinate systems.

* This is local space: `player.get_position()`
* This is global space: `get_global_mouse_position()`
* And this is local space again: `draw_line( pos_two ,pos, Color(255 , 0 , 0))`

*And this is why you see it move. When you rotate the body with `look_at(pos)` the local space changes. Also when you move the body with `move_and_slide`.*

Thus, first of all get the positions in global space:

```
pos_two = get_global_transform().origin
pos = get_global_mouse_position()

```

And second, convert them to local space to use them:

```
draw_line(to_local(pos_two), to_local(pos), Color(255 , 0 , 0))

```

Which gives you this code (I have added type information):

```
extends KinematicBody2D

onready var player:CollisionShape2D = $CollisionShape2D
var pos_two:Vector2
var pos:Vector2

func _physics_process(_delta:float) -> void:
    var vel := Vector2()
    pos_two = get_global_transform().origin
    pos = get_global_mouse_position()
    look_at(pos)
    if Input.is_action_pressed("movethere"):
        vel = Vector2(400 , 0).rotated(rotation)

    vel = move_and_slide(vel)
    update()

func _draw() -> void:
    draw_line(to_local(pos_two), to_local(pos), Color(1.0, 0.0, 0.0))

```

Why don't get the position in local space to begin with? Because you are changing the local space after you get the position and before you draw.

---

Thus, another option is to get the position when you are going to draw.

Do you know what is the position of the body in local space? That is right, it is at the origin. So we only need to figure out the position of the mouse pointer in local space.

The code is like this:

```
extends KinematicBody2D

onready var player:CollisionShape2D = $CollisionShape2D

func _physics_process(_delta:float) -> void:
    var vel := Vector2()
    look_at(get_global_mouse_position())
    if Input.is_action_pressed("movethere"):
        vel = Vector2(400 , 0).rotated(rotation)

    vel = move_and_slide(vel)
    update()

func _draw() -> void:
    draw_line(Vector2.ZERO, to_local(get_global_mouse_position()), Color(1.0, 0.0, 0.0))

```

---

*Yes, I know I'm answering this years later.*
> 0 votes

---
Tags: rendering, godot, gdscript
---


# Question
Title: How do I clear all gameobjects placed on a tilemap?
If I call the following on a tilemap:

```
myTilemap.ClearAllTiles();

```

It clears all tiles placed using the tilemaps built in system. But if I've placed any tiles via the gameobject brush, they don't get cleared.

What are my best options for working with the objects placed relative to a tilemap? Is there any kind of hard connection made between the tilemap and the objects that I can leverage, or are the objects simply placed relative to the map?

Is there any kind of API I should be referencing when working with gameobjects placed "on" / "using" a tilemap?

(Also posted on Unity Answers)

# Answer
> Is there any kind of hard connection made between the tilemap and the objects that I can leverage, or are the objects simply placed relative to the map?

No, the gameobject brush merely leverages the 2D tilemap grid to pick a position and clone (instantiate) a gameobject at that position as a child of the currently selected tilemap. It does not create a Tile asset in your project folder (which is what happens when you paint a 2D sprite using the default brush).

You can select the tilemap in the hierarchy and, in the inspector, you can click on the info dropdown and see that there are no tiles in the tilemap.

> Is there any kind of API I should be referencing when working with gameobjects placed "on" / "using" a tilemap?

You should just use the regular Transform API. So... tilemap.gameObject.transform.blahblah
> 2 votes

---
Tags: unity, tilemap, gameobject
---


# Question
Title: What is ApplyBuiltinRootMotion and how to use it?
The character in my game has humanoid feature. I have unchecked "Apply Root Motion" in Animator component and use scripts for its movements. I want to implement a Ledge Grab Jumping movement.
How can I use "ApplyBuiltinRootMotion" function in this case?
What do I need to know about this function and to make it work really ?

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

```

# Answer
When you have a script on your gameObject that implements `OnAnimatorMove()`, then the root motions of any animations are ignored. That is unfortunately not documented in OnAnimatorMove where you would expect it, but in the documentation of the Animator.applyRootMotion property:

> Root motion is the effect where an object's entire mesh moves away from its starting point but that motion is created by the animation itself rather than by changing the Transform position. Note that applyRootMotion has no effect when the script implements a MonoBehaviour.OnAnimatorMove function.

However, sometimes you have the case that you want to use your own root motion logic only in *some* cases while you have other cases where you want to leave the root motion to the animation clip. In that case, you call `animator.ApplyBuiltinRootMotion()` within OnAnimatorMove to restore the normal behavior. The code in the question is of course rather pointless. It takes over control of root motion by having an implementation of OnAnimatorMove, but then it hands root motion control right back to the animation system by calling `ApplyBuiltinRootMotion()`.But you might have code like this where this method is only executed when you are not in a state where you have an own root motion implementation:

```
 private void OnAnimatorMove()
 {
     if (ourAnimationUsesCustomRootMotion == true) {
        // We are currently handling root motion manually
        transform.position += ourRootMotionVector;
     } else {
        // We don't have custom root motion enabled right now, so let's leave it to the animation system
        _animator.ApplyBuiltinRootMotion();
     }
 }

```
> 2 votes

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


# Question
Title: Can I use normal images to make tiles in Unity?
If I'm not wrong, those are steps to use tiles with Tilemap in Unity

1. Upload sprites to Unity
2. Create a palette.
3. Upload sprites to the palette to create tiles.

I need some static images to use with the Tilemap. No animation. Can I use just any png. images (during the step 1) for that and follow those 3 steps? Or it's necesary to use first some programs to make "sprites" out of those images?

Here I'm trying to put some tiles in 4 cells of the Tilemap. The screenshot with number 10 is what I get with my custom image. It's way bigger than the 4 cells. And the second screenshot - this is what it should look like, it has 4 images, each in its cell. I made it from an image found in a tutorial on YouTube. So I guess the problem is the source image.

# Answer
Go to the import settings of your image asset and change the "pixels per unit" to 10 times the value it has now.

The tilemap does not automatically adjust the size of tile images so they fit into the grid. And just like any Unity component, it works with logical Unity units, not with screen pixels. So you need to make sure the images you use for your tilemap have the correct ratio of pixels per unit.

Alternatively, you can adjust your camera size and grid size so that one unit on the screen is indeed the same as the default PPU of newly imported images (60 pixels).
> 1 votes

---
Tags: unity, sprites, tilemap
---


# Question
Title: Solving obtuse interior corner collisions
I'm having some trouble solving collisions in obtuse interior corners.

In the above image, the black circle is the initial position, the red is the projected movement (straight into the corner), the green is the position after solving the first plane (by moving the circle along the plane normal by the amount of penetration), and the blue the after solving the second. On the left, the right plane is solved first. On the right, the bottom plane is solved first.

The problem is apparent in both images: resolving the collisions results in a gap between the circle and one of the planes when it should ideally rest against both of them.

Square corners will result in a correct solution in a single iteration and acute corners will eventually reach a solution after several iterations, but obtuse angles present this problem. Is there some other method, something I'm missing, or is this just one of this acceptable inaccuracies?

# Answer
> 15 votes
There is an alternate way to think about solving this. You can do a transform by offseting the lines by radius of your circle then the solution is same as intersection of 2 lines.

**Image 1**: You can convert the problem to line intersection testing of lines A and B.

This also makes general intersection testing easy as you do line to pillshape testing. You can even cache the offsets if you wish. This makes it also obvious for collision testing that the ball would probably not hit the corner on a straight move but instead slightly off corner as was pointed pointed out in the comment section. But that may be besides the point.

**Image 2**: the intersection wont be the corner though. But yes it may then slide if its sticky etc.

Anyway weather this is easier, faster or convenient on you or not is another thing. If you make a billiard ball game then it might. Its just that one of offset, line intersection or pill collision is often already written in whatever your using and it comes sometimes handy in constrained environments (like say Adobe Illustrator and Inkscape).

PS: offseting lines is just a vector move rotated 90 degrees from lines direction. (you can also use magnitude of a corss product etc.)

# Answer
> 13 votes
I assume that you want a solution for collisions in general, which also works well for interior corners.

When resolving a collision against one plane, do not move the circle perpendicular to the plane. Instead, move it *back along its path* until it does not collide with the plane. The distance along the path will be

$$d = r \sec \theta = \frac{r}{\cos \theta},$$

where \\$r\\$ is the radius of the circle and \\$\theta\\$ is the angle between the plane normal and the circle.

Then, find the component (projection) of the circle's velocity which is perpendicular to (towards) the plane, subtract that from the total velocity (or a bit more if you want a bounce), and continue simulating the remaining amount of the motion in the current timestep (a sliding along the plane).

This is a simple form of “continuous collision detection” — we can see this process as finding the *time* at which the collision happens. (In fact, you'll need to do that too to figure out how much remaining time there is for the second step. You can compute it from the distance moved back and the velocity.)

When you hit the second plane, you can just do this again, but there's a catch: you'll end up simulating the trajectory as if the ball hit them in succession, and the ball will slide out of the corner slightly (as if it had hit a curve and slid around it) in some direction. This is almost the same as your original gap, except it is in *velocity* rather than *position*, so it might be more acceptable. If you want it to be perfectly stopped, you'll need to include some time or distance threshold for "these two successive collisions were actually at the same moment" and decide that sliding into the second plane just stops the ball instead of letting it slide further.

(Also, in case of acute corner angles, don't iterate this *more* than two steps, or 3 steps in 3D; it won't make further progress and you don't want to get stuck in an infinite loop.)

In any case, this procedure will ensure that the circle *never enters a plane* except slightly, due to floating-point rounding error. You'll still need resolution for in case the circle *does* end up in such intersecting cases, though.

# Answer
> 4 votes
To find the position where the circle is resting against both planes, you could use following approach:

We define the line k which is the bisector of the angle between g and h. Every point on line k has equal distance to g and h, so we know that the sought after point must lie on the line k. To calculate the distance from the corner point to the sought after point, we can use trigonometry. We first construct the right-angled triangle a, b, c:

Since α is a right angle and we already know that β is half the angle between g and h, we can use the trigonometric function

$$sin(\theta) = \frac{opposite}{hypotenuse}$$ $$hypotenuse = \frac{opposite}{sin(\theta)}$$

to determine the hypotenuse. If we fill in our values we get the formula

$$a= \frac{b}{sin(\beta)}$$

By moving from point B along the line k by the amount a we get the sought after position C. This approach works for obtuse angles as well as for acute angles.

# Answer
> 0 votes
I am guessing what you want to simulate is "the ball is moving in a particular direction. If it runs into a barrier, it will slide along the barrier. It will never move against the direction it is moving".

To solve this problem, what I would do is first pretend my two lines I am colliding with are infinitely long. Each line is described as some point \\$p\\$, a unit vector \\$u\\$, and a range of multiples of that unit vector along the line \\$\lambda\\$: \\$p + \lambda u\\$.

The ball's movement would be described as a parameter of \\$t\\$. Lacking any obstruction, the center of the ball would be at position \\$x\_0 + t v\\$ after \\$t\\$ time.

Then I solve for "for what \\$(t, \lambda)\\$-values would my ball cross those infinite lines".

Solving for "I'm (almost) parallel to the line" is one sub-problem. For non-parallel trajectories we can find when the center crosses the line, and then work out by "backtracking" when the circle did.

We can project our ball's velocity along the line with a simple dot product: \\$v . u\\$, and its normal velocity via the cross product \\$v x u\\$. Divide the magnitude of the cross product by the ball's radius to say how long ago (in \\$t\\$ units) that the ball first touched the line. To find the difference between the center collision and the first time the ball crossed it in \\$\lambda\\$, multiply the delta-\\$t\\$ calculated by \\$v . u\\$.

You now have an interval along the infinite line where your ball is within its radius of the line, as well as a time interval when this happens. You actually want a ball-line *segment* intersection, but this is a good start.

If you aren't worried about hitting the ends of the line segments (and if you "know" you are going into a corner like that, this holds), you can skip the line segment problem.

If you are worried, you have to do ball-ball intersections on the end of the line segments, and prune your \\$t\\$ and \\$lambda\\$ values based on that.

Usually you only care about when you first hit the line, as the universe changes when you do. So take the minimum positive t in that interval. (if it is 0, it means either you are touching the line or are overlapping with it).

Starting at that time point \\$t\\$ you will now be restricted to sliding along the line you are touching. Be careful! If you want to model "being shoved along a certain path", simply recursively solving with this new direction will lead to strange bounces. You may, on the other hand, want this -- maybe you want running into a "circular turn-around" could cause your ball to spin around and fly in the other direction.

Assuming you don't want this, you need to treat this as a constraint on your velocity, not a new velocity. This constrained vector (by the line) follows the line (until it longer collides with it). And you compare against all other lines in the universe.

Use the same algorithm to find out what other lines you run into, but when working out your end velocity apply each line as a constraint, not a full redirection; don't take initial velocity, deflect by first constraint, then deflect the result by the 2nd (and 3rd etc) unless you are playing billiards.

Instead you have a velocity vector and a bunch of "you can't go in this direction" constraints.

Given the angle of the balls movement, each constraint will either be on the left or the right (ie, it is hitting the ball on its left side, or its right side, as it moves along). If you have a constraint on both sides your ball stops. If you don't, you only care about the *greatest constraint* active, and you apply it.

This lets you hit a line on your right, then a line that pushes you even further on the right. Only when your left side hits a line do you stop.

To deterimine left vs right, look at the time of collision; the center of the ball and the point on the line the ball's radius touches. Those will form a line of length ball radius that is perpendicular to the vector of travel of the ball, and avoids a numerical rounding error problem (your ball is touching 2 lines almost completely parallel on one side. A floating point error could put them on opposite sides if you aren't careful.)

---
Tags: 2d, movement, collision-resolution, collider
---


# Question
Title: Shortcut to select all children of a game object
I want to click on a game object and select all of its children. How is this possible?

# Answer
I don't believe there is a shortcut, but you can write an editor script to do this if it's really that much of a hassle to shift select a bunch of children

there is an example here: https://answers.unity.com/questions/1773802/how-can-i-select-whole-object-with-its-childrens-i.html

however, the functionality here may need to be fine-tuned, as it recursively grabs all children which you may not want. I am also not confident in the script's ability to select multiple parents and then grab their children.
> 2 votes

# Answer
If you don't mind doing it in the hierarchy, you can just right click the object and click the "Select Children" option.
> 0 votes

# Answer
You can hold `Shift Key` and `left click` on the `first child` and `last child` to select all the children in middle.
> 0 votes

# Answer
Hold shiftKey and select first and last child
> -2 votes

---
Tags: unity
---


# Question
Title: How to redact an event in a prediction/reconciliation networking model
I'm struggling with how to handle a particular situation in a prediction/reconciliation server model.

1. At `t=0`, Player A is firing. Player B is moving into A's line of fire
2. At `t=1`, Player B moves into A's line of fire and gets hurt, reducing health from `100` to `50`
3. At `t=2`, the server receives input from player B for `t=1`. That input confirms that player B moved into the line of fire, so the server responds with a packet for `t=1` indicating that the player's health is now `50`
4. Player B receives this packet, and noting that health dropped, flashes the screen red.
5. The server receives input from Player A for `t=1`, indicating that A *stopped* firing. The server rolls back to `t=1`, re-simulates, and realizes player B did not get hit.
6. The next state sent to B indicates `health=100`.

How do I handle the fact that client B showed a red screen flash *based on information received from the server*, and then later found that they were not in fact hurt?

This sounds a bit like the situation of e.g. Source Games favoring the shooter. However, in this case, even player A did not think they hit player B on their own screen.

Can the server not send a state for `t=1` until it has inputs from *every* player for that frame? That seems like it would cause a single latent player to slow down the experience for everyone else.

# Answer
> 1 votes
> That seems like it would cause a single latent player to slow down the experience for everyone else.

That's correct, it would, which is why you shouldn't do that.

In this case, I'd err on the side of showing feedback as soon as possible (if I might have an instant to save myself from death and get away with a graze, I'd like to know it!) and don't worry about harmless contradictions.

If I see my screen flash red, then a moment later I'd back to full health, yes, that's weird, but it's a nice surprise! And it's much better than all input/feedback from other players taking on extra latency, leading to more bad surprises (like "hey, you're already dead because you started taking damage 5 frames ago and I just got around to telling you).

This type of minor contradiction is common in shooters, where you'll often see a blood splat on a wall from a headshot that it turns out didn't *really* connect, and the character model keeps sprinting away unharmed on the next update. It's weird, but the more important signifier is "the enemy is still up and running" and players will attend to that over a little over-eager feedback.

---
Tags: networking
---