# Question
Title: Confused about calculation of steering force
I'm reading *Programming Game AI by Example, by Mat Buckland*. What I don't understand there is why the individual behaviors return a vector representing change in velocity, but the combined result is treated as a force vector.

Here's the excerpt from the update function:

```
  Vector2D SteeringForce = m_pSteering->Calculate();

  //Acceleration = Force/Mass
  Vector2D acceleration = SteeringForce / m_dMass;

  //update velocity
  m_vVelocity += acceleration * time_elapsed;

  //make sure vehicle does not exceed maximum velocity
  m_vVelocity.Truncate(m_dMaxSpeed);

  //update the position
  m_vPos += m_vVelocity * time_elapsed;

```

And `m_pSteering->Calculate()` returns the weighted sum of different steering "forces", like `Seek`

```
Vector2D SteeringBehavior::Seek(Vector2D TargetPos)
{
  Vector2D DesiredVelocity = Vec2DNormalize(TargetPos - m_pVehicle->Pos())
                            * m_pVehicle->MaxSpeed();

  return (DesiredVelocity - m_pVehicle->Velocity());
}

```

So, how come steering functions like `Seek` just return change in velocity and don't take mass into account, but still get used as force?

Here's the source code

# Answer
> 1 votes
The guy who wrote the original steering behaviors stuff was a little sloppy about accelerations versus forces. They differ, of course, only by a factor of the agent’s mass. In many multi-agent steering-behavior based systems mass is ignored, or set to one, which makes accelerations and forces equivalent. You tend to spend a lot of time tweaking with the strength and weighting of the steering forces, and how they get combined, so the units of mass (or non-unit values) can often be ignored. The more you care about the actual physics, the more you care about realistic values of mass, force, and acceleration.

---
Tags: physics, steering-behaviors
---


title: Pause updating but keep rendering

text:
# Question
Title: Pause updating but keep rendering
I am creating an implementation of Snakes and ladders and I run into some issues.The game is updating too fast and I want to limit the framerate kinda,or make a pause so that the move is actually visible.I tried using `Thread.sleep()` but that created issues of its own.Have you solved any similar problems that could point me to the right direction? I have to point out that run method is in an `abstract` class and my actual game `extends` this `abstract class`

This is the game loop :

```
public void run() {
    init();
    this.requestFocus();
    long lastTime = System.nanoTime();
    double amountOfTicks = 60.0;
    double ns = 1000000000 / amountOfTicks;
    double delta = 0;
    long timer = System.currentTimeMillis();
    int updates = 0;
    int frames = 0;
    while (running) {
      long now = System.nanoTime();
      delta = delta + (now - lastTime) / ns;
      lastTime = now;
      while (delta >= 1) {
        update();
        updates++;
        delta--;
      }
      render();
      frames++;
      if (System.currentTimeMillis() - timer > 1000) {
        timer = timer + 1000;
        if (this.FPSLOG)
          System.out.println("FPS: " + frames + " " + "Ticks: " + updates);
        frames = 0;
        updates = 0;
      }
    }
    stop();
  }

```

The render method :

```
private void render() {
    BufferStrategy bs = this.getBufferStrategy();
    if (bs == null) {
      this.createBufferStrategy(3);
      return;
    }
    Graphics g = bs.getDrawGraphics();
    g.setColor(background);
    g.fillRect(0, 0, getWidth(), getHeight());
    draw(g);
    g.dispose();
    bs.show();
  }

```

The game implementation of those methods:

```
@Override
    public void init() {
        setBackground(Color.black);
        board = new Board();
        player = new Player(Color.cyan,board.getTiles()[0]);
        dice = new Random();
    }

    @Override
    public void draw(Graphics g) {
        board.draw(g);
        player.draw(g);
    }

    @Override
    public void update() {
        for (int i = 0; i < dice.nextInt(7)+1; i++) {
            player.move();
        }
    }

```

```
public void move(){
        this.currentTile = this.currentTile.getNext() == null ? this.currentTile : this.currentTile.getNext();
        this.xPos = this.currentTile.getxPos();
        this.yPos = this.currentTile.getyPos();
    }

```

# Answer
The variable `double amountOfTicks = 60.0;` seems to be what's controlling your update rate. You might want to reduce that, this will update your logic less often, while keeping the same render rate.

Also, there is an issue with the `update()` function: each time you call the `dice.nextInt(7)` method, you generate a new value, changing the upper bound of your loop every iteration. I'm not sure this is what you expect. Also, you move your player many times per frame, which does not help your situation (all the loop iterations are performed in the same frame).

```
// The iterations of this loop
for (int i = 0; i < dice.nextInt(7)+1; i++) {
    player.move();
}

// will look like this:
i = 0; dice.nextInt(7)+1 = 8; i < number? true
i = 1; dice.nextInt(7)+1 = 5; i < number? true
i = 2; dice.nextInt(7)+1 = 4; i < number? true
i = 3; dice.nextInt(7)+1 = 2; i < number? false

```

It is very unlikely that `i` will ever reach 7.

I suggest you add a new `movesLeftThisTurn` variable to your player, as well as a `famesTillNextRoll` variable. Once you roll the dice, you stick the value in `movesLeftThisTurn`, and you decrement it by one each frame that you move. Once it gets to 0, set the other variable to 5, and decrease it by one each frame. Once it gets to 0, roll the dice for movesLeftThisTurn and start over again.

Here is something like what I have in mind:

```
public void update() {
    if (player.movesLeftThisTurn > 0) {
        player.move();
        player.movesLeftThisTurn -= 1;

        if (player.movesLeftThisTurn == 0)
          player.famesTillNextRoll = 5; // This will pause the player at the current tile for 5 frames
    }
    else {
        if (player.famesTillNextRoll > 0)
            player.famesTillNextRoll -= 1; // Do nothing...

        if (player.famesTillNextRoll == 0)
            player.movesLeftThisTurn = dice.nextInt(7) + 1;
    }
}

```
> 1 votes

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


# Question
Title: Way to look up a chain of touching objects (power connections)
I'm having a bit of a logic problem. I have blocks that connect together for power and so when a block comes into contact with a block that is powered, it also becomes powered. It also keeps a list of connected blocks and checks that it's getting power from at least one block.

There are "source" blocks in the scene as well which are always powered and that serves as the starting point.

All of this works fine, unless we get a break in the middle. In that case, even though they aren't connected to a source block anymore the two blocks are connected to eachother and so they stay in the "connected" state.

My question is similar to this question but different in that my objects can attach in any orientation and have any number of connections. In this case, a sort of pathing would work since wire systems aren't going to have more than 10 or 15 connections total and only 1 wire system active at any time.

Here is the code if anyone is interested. Thanks in advance.

```
public class Conductor : MonoBehaviour
{

public bool isElectrified;
public bool isPowerSource;
public Material inactiveMaterial;
public Material activeMaterial;

private List<Conductor> _conductors;
private Renderer _renderer;

//====
//Unity Functions
//====
void Start()
{
    SetupPrivateVariables();
    CheckPowerSource();
}

void Update()
{
    ProcessConductors();
}

void OnCollisionEnter(Collision collision)
{
    ProcessNewCollision(collision, true);
}

void OnCollisionExit(Collision collision)
{
    ProcessNewCollision(collision, false);
}

//====
//Private Functions
//====
private void ProcessConductors()
{
    if(isPowerSource)
    {
        return;
    }

    bool connectedConductorPower = false;

    foreach (Conductor c in _conductors)
    {
        if (c.isElectrified)
        {
            connectedConductorPower = true;
        }
    }

    if(connectedConductorPower)
    {
        _renderer.material = activeMaterial;
    }
    else
    {
        _renderer.material = inactiveMaterial;
    }

    isElectrified = connectedConductorPower;
}

private void CheckPowerSource()
{
    if (isPowerSource)
    {
        isElectrified = true;
        _renderer.material = activeMaterial;
    }
}

private void SetupPrivateVariables()
{
    _renderer = this.GetComponent<Renderer>();
}

private void ProcessNewCollision(Collision collision, bool doAdd)
{
    if (isPowerSource == false)
    {
        Conductor otherConductor = collision.collider.gameObject.GetComponent<Conductor>();

        if (otherConductor != null)
        {
            if (doAdd)
            {
                _conductors.Add(otherConductor);
            }
            else
            {
                _conductors.Remove(otherConductor);
            }
        }
    }
}

```

}

Edit: I just found this question, which is similar but I'm not sure how it would handle a disconnect.

Edit 2: I ended up going with the accepted answer and built a "pulse" into the system. Basically power sources pulse down the chain and each object passes the pulse onto the objects they are connected to. If an object doesn't receive a pulse, then it shuts off since it knows it doesn't have power. This system isn't foolproof, and for large networks would slow down the framerate but my networks aren't very large and only a small handful of networks per scene. I went with this system for the accuracy it gives and flexibility. I can have any number of power sources and the network can spider out and loopback on itself without issue.

# Answer
It looks like you're not considering the connection state of everything in the chain, meaning that when you process conductor A, which is connected only to B, *B may have not yet been updated* \- meaning that B.isElectrified may still be true, even when its only connection is A.

You could make the check recursive:

```
public bool isElectrified {
    get {
        return isPowerSource || AnyConnectionIsPowered(null);
    }
}

private bool AnyConnectionIsPowered(Conductor ignored) {
    foreach(Conductor c in _conductors) {
        if(c == ignored) { continue; }
        if(c.isPowerSource || c.AnyConnectionIsPowered(this)) { return true; }
    }
    return false;
}

```

You could make all of your conductors update based on a pulse sent out by power sources, passing the pulse along to their connections:

```
private void ProcessConductors() {
    if(isPowerSource) {
        foreach (Conductor c in _conductors) {
            c.Pulse();
        }
        return;
    }
    ...
    isElectrified = false;
}

private void Pulse() {
    isElectrified = true;
    foreach(Conductor c in _conductors) {
        c.Pulse();
    }
}

```

These are just a couple of suggestions. **The most important thing to consider is that you *must* know the state of everything attached to a Conductor before you can accurately determine that Conductor's state.**
> 1 votes

---
Tags: unity, c#, logic, fuzzy-logic
---


# Question
Title: How to detect when the player has filled a shape?
In my game, the player is presented with a plane containing obstacles (orange / blue) and regions of empty space (white).

The player moves their green cube around the empty space, which instantiates a trail of green cubes behind it, painting the path they've travelled.

I need to detect when the player has painted all of the empty space, so that they can proceed to the next level.

Initial state of the board:

When the player has painted all of the empty space:

Currently I store my instantiated paint objects in a list.

But I don't know how to check that the objects in this list cover all of the empty space. How can I do that?

```
public float speed = 10f;
private RaycastHit hit;
public GameObject paintcube;
float maxdistance = 0.51f;
bool moves;

private void FixedUpdate()
{
    Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 3, Color.green);
    if (Physics.Raycast(transform.position,transform.TransformDirection(Vector3.forward), out hit, maxdistance/*,layerMask*/))
    {
         if (hit.collider.gameObject.tag == "myobstacle")
         {
             moves = false;
         }
         if(moves)
         {
             movepaint();
         }
     }
}

public void movepaint()
{
     if (moves)
     {
         MyList.Add( Instantiate<GameObject>(paintcube, position, transform.rotation) );
     }
}

```

# Answer
> 1 votes
You should discretize your space into a grid, and then determine how many of those squares are "covered" by something. I'd recommend making a GridArea class like so

```
public class GridArea : MonoBehaviour
{
    public float width; // Width in world space of the grid
    public float height; // Height in world space of the grid
    public int rows; // Number of rows in the grid
    public int columns; // Number of columns in the grid

    public float cellWidth { get { return width / columns; } }
    public float cellHeight { get { return height / rows; } }

    public Vector2 GetWorldPosition(int x, int y) {
        // Find the center of cell 0,0
        Vector2 bottomLeft = transform.position - new Vector2(width / 2, height / 2);
        bottomLeft += new Vector2(cellWidth, cellHeight);
        return bottomLeft + new Vector2(cellWidth * x, cellHeight * y);
    }
}

```

This class will break up your play area into small squares. To determine coverage you can go through each square and check if it is "covered". I would also advise adding an OnDrawGizmos function to help visualize the grid. So if you determine what % of the squares are covered, you get a rough estimate of what % of the map is covered. If you let your walls "cover" squares, then the only non covered is the play area. If player is above some threshold (say 95%) then they pass. The reason I chose the variables for the class that I did, is so you can keep the width/height of the play area fixed, and change the number of rows/columns to make it more accurate. The smaller the squares, the closer to the correct coverage you will measure. This is basically simple calculus. As the size of the squares approaches 0, your coverage measure will approach the actual value.

How you determine coverage is up to you. It could be as simple checking if the center of a grid cell is covered. You could check 4 points on the square and see if 2 or more are covered. There's lots of solutions you could try. Keep in mind performance throughout all of this. You could progressively measure coverage. Instead of always recomputing every square, start with the squares your level covers baked in. Then every time the player paints, update the squares that the paint affected, and recompute the %. Caching values will make things more performant and you can end up with a very effective solution.

Additionally I'd encourage that you don't instantiate squares as your painting method. You can look into decals, write a custom shader, paint to the texture, etc. Instantiation is heavy and should be avoided if you can for something like this that could end up with many many things being instantiated.

---
Tags: unity, c#, physics, 3d, raycasting
---


title: How do I make an object destructible?

text:
# Question
Title: How do I make an object destructible?
How do I make one of my objects break into random pieces? I've tried Add-Ons, Blender, and a few other things that I can't remember of the top of my head.

# Answer
You don't necessarily have to make the object itself destructible. Instead, you can create a number of separate models of "pieces" of your object.

If you have the object blowing up, then you can draw an explosion effect, remove/hide the original object, and then spawn the various pieces being thrown out randomly. Each is a separate and unique new object.

If the object is going to break in a more natural way, then you can do a variation of the same idea, but have the pieces all spawn basically in their original location if the object was assembled. Assuming you've got physics active, the pieces will then fall and tumble as they would normally.
> 1 votes

# Answer
What you are looking to do is called Fracture Meshes. Unreal has these built in but Unity does not. You'll probably want to fork up some cash as doing this manually is quite the task. A quick outline of the theory to give you an idea of why you might just want a library for this:

A material experiences stress and you can determine this via propagating forces of elements (triangles). Each triangle can experience a stress and pass that stress to a neighboring element. Stress can be broken up into two parts, tensile and compressive. Compressive implies objects pushing into eachother, tensile involves objects pulling apart. You need to compute the tensile stress at each point where the object CAN break (whether it's every vertex, or you split your mesh into pre-fractured pieces and just check those chunks). Then if your tensile stress is greater than the tensile strength of the material, split the mesh and cause a fracture. The math behind this is not fun, and you can fake a FAIR amount if it. For example, stress is proportional to force, so you could have some very faked system where you measure the distance from the force impact point and the further the distance the less that part of the material feels that force. This would be a HUGE estimate but could yield some results.

Here's a resource that covers the basics (if you can call them that) and extends upon them for perfectly fractured meshes. This is far overkill for a video game, but DOES introduce basic concepts

\[Zhu Bridson Greif\] Simulating Rigid Body Fracture with Surface Meshes
> 0 votes

---
Tags: unity, gameobject
---


# Question
Title: Interactive ways to answer a yes or no question in a VR game?
Currently, I am creating a VR game with a simple AI that at certain points ask for yes or no answers. Considering the player is free to walk around, I need a sort of spawn in and out kind of solution. I would really like this to be interactive and engaging. So far, I'm thinking to animate a "terminal" from the floor with a green and a red button on it and the user simple pushes down on one with their hand. I don't really want to use a 2D UI or a controller button press for this. Are there any other potential ways to handle this situation while keeping the interactivity there?

# Answer
If you want to go with the terminal solution, you could just track controller position. The best part of VR is that you can translate motion and use the space as part of your design - even something as simple as a head nod/shake or pointing to a word could also work.
> 1 votes

---
Tags: game-design, virtual-reality
---


# Question
Title: How can I get old Minecraft style terrain biome selection?
I'm using this post as a reference for what I'm doing.

The real thing of interest is this:

As you can see, this is a Whittaker diagram, with temperature and rain considerations.

So would this be the algorithm he uses?

```
def rain(x,z):
    return some_fbm_perlin_noise(x,z)
def temp(x,z):
    return some_fbm_perlin_noise(x,z)
def biome_at_point(x,z):
    return diagram_at_point(rain(x,z),temp(x,z))

```

The issue with this is that if I assume the fbm perlin noise to be in the range \[0,1\] for both of them, then this algorithm only covers the bottom left half of the diagram. What is the top right half?

And also, perlin noise tends to make "short forays" into extreme (\[0.9,1.0\]) values, so the smaller, rarer biomes would have little tiny dots scattered around the map. An example would be the tundra: the tundra is very rare, and when it happens it probably only happens for a small area. But what actually happens in Minecraft is that the smaller, rarer biomes are very rarely come across, but they still have a normal size.

I've tried something like this:

```
def rain(x,z):
    return hash(nearest_voronoi_point(x,z))
def temp(x,z):
    return hash(nearest_voronoi_point(x,z))

```

But this runs into the triangle problem, and a new one: the hash function, by definition, is incoherent, which means that it could put a desert next to a snowy mountain, because there are no constraints.

How does can I fill in the final triangle and not half tiny biomes everywhere, while maintaining biome coherency?

# Answer
> What is the top right half?

That part is omitted because under normal Earth environments, it's not observed to happen. Consider the following:

Note that in the coldest (polar) regions, the precipitation is minimal - it has been forced out of the air currents prior to arrival.

> How does can I fill in the final triangle...

The short answer is that you either should not because it represents conditions that shouldn't occur. *If* for the purposes of implementation you must fill it, I recommend filling it with some sort of reserved sentinel value (like a biome with purple trees) so that it if does occur, it's immediately obvious that something went wrong.

> And also, Perlin noise tends to make "short forays" into extreme (\[0.9,1.0\]) values, so the smaller, rarer biomes would have little tiny dots scattered around the map. An example would be the tundra: the tundra is very rare, and when it happens it probably only happens for a small area. But what actually happens in Minecraft is that the smaller, rarer biomes are very rarely come across, but they still have a normal size.

This is correct. There are two ways I know of to deal with this. On solution is to perform histogram equalization; basically you feed the noise output into another function that attempts to "flatten it out". While straight forward I've not had great success with this approach, probably because it incorrectly assumes that Perlin noise is a correct model for temperature distribution.

In my experience, a better approach is to use Perlin noise to skew the expected values for a region. On a planet with Earth like conditions, the polar regions are cold & the equatorial regions are hot. But there's also some bit of variety. To model this, normalize your Perlin noise to some acceptable temperature swing range, say +- 20 degree and then use that skew the expected temperature of a region hotter or colder. Here's an illustration that also takes elevation into consideration (since extreme elevations are cold):

Note: that image is from this excellent write up on procedural generation which covers this idea in greater depth.

> it could put a desert next to a snowy mountain, *because there are no constraints*

Your observation is correct. By itself, a Whittaker diagram cannot produce biome distributions & adjacencies that match Earth based expectations because it doesn't model enough of the feature constraints. Taken another way, the Wittaker diagram **only** describes that when X temperature combines with Y precipitation Z biome region forms. It does not describe why or how any two combinations of X & Y would be brought together. To model these constraints, you need to use additional models / techniques such as those previously mentioned.
> 2 votes

---
Tags: procedural-generation, terrain, minecraft-modding
---


# Question
Title: How to guarantee that player fits rooms of a cave created by Cellular Automata?
I've implemented a cellular automata algorithm to generate a cave for my game and now I need my player object, which occupies 3x3 tiles in total, to be able to pass between the rooms.

The problem is that some of the rooms automatically created by cellular automata do not have the necessary width/height for the object to pass (example: a 2 x 3 tiles corridor).

How can I transform the result from the cellular automata so that I guarantee that the player is able to pass in any of the rooms? The idea is that this can be done in real time so that I can do an endless game.

This was done in GDScript but any examples in any other language, like C# for Unity, are welcome.

**Update**

As said in the comments, I could make a map where each cell would correspond to a 3x3 on the final map but, my problem is that I need the 1x1 tiles because my player should lose a life when hitting the walls (and that way I can create some kind of "spikes" based on the walls).

Given that, how can I add 1x1 tiles to the map created from the 3x3 and still guarantee that the player fits the cave's "corridors"?

**Update 2**

The only rules I currently have for CA are:

* If total neighbour walls \> 4, the cell becomes a wall
* If total neighbour walls \< 4, the cell becomes empty
* Else, remains as it is

The total number of iterations for the CA is 2

**Solution**

I was able to do this the way that **DMGregory** said:

* First I run the CA after building the map as I did before in order to add the "empty space adjacent to wall" cells (now on called **EmptyNextToWall**) to the map
* Then I run the CA with the following rules, until none of them are verified (it did not pass 5 iterations on my scenarios):
    + If my current cell is **EmptyNextToWall** and has more than 4 EmptyNextToWall adjacent to it, make it an **Empty** cell
    + If my current cell is **EmptyNextToWall** and the adjacent diagonals are a Wall and a EmptyNextToWall, make it an **Empty** cell
    + If my current cell is **EmptyNextToWall** and there's no Empty cells around it, make it an **Empty** cell
    + If my current cell is a **Wall** and there's at least one adjacent Empty cell, make it an **EmptyNextToWall**
    + If my current cell is **EmptyNextToWall** and there's no adjacent Walls, make it an **Empty** cell

# Answer
> 0 votes
A (binary) cellular automaton can't "see" features larger than its kernel size / neighborhood.

If we consider the case of "a passage too small for a 3x3 character to fit," that could be a wall, followed by two open spaces, then another wall — ie. it's a feature that's 4 tiles wide.

So if you're using a cellular automaton with a 3x3 kernel / neighborhood, then your cell update logic can't detect the difference between this case and a wall next to unlimited open space. It can't see all the way from one wall to the opposite wall over a 2+ tile gap to know that it's too narrow and choose to fill it in / carve it wider as a result.

So, one option is to widen your kernel. A 5x5 kernel will let you detect passages 3 tiles wide with a wall on either side, and carve out/fill in spaces narrower than this.

The downside is that the automaton gets a little more complex: needing more rules to handle the greater set of variations in its neighbourhood, and more taps/samples per cell to evaluate the next state.

---

Another potential option is to move beyond the binary, by adding more cell values. Then each cell could store one of:

* `0`: "wall"
* `1`: "empty space adjacent to wall"
* `2`: "empty space touching only empty space"

This is effectively a simplified distance field. The `2` values form a mask of locations your 3x3 character's center point could occupy as it navigates the map, and the `1` values form a "shoulder" outlining the walls.

Now even a CA with a 3x3 neighborhood can detect the difference between a 3-wide passage:

```
[ 0   1   2 ] 1   0
  0 [ 1   2   1 ] 0
  0   1 [ 2   1   0 ]

```

and a 2-wide passage:

```
[ 0   1   1 ] 0   0
  0 [ 1   1   0 ] 0
  0   1 [ 1   0   0 ]

```

(Here using square brackets to denote the left & right edge of the kernel as it scans across a feature)

Again the trade-off here is complexity: your cell storage needs more bits, and your cellular automaton rules need more cases to handle the various permutations of open cells adjacent/not adjacent to walls. You also need to ensure your rules maintain (or eventually re-establish) the invariant that no `2`s are found adjacent to a `0`.

# Answer
> 1 votes
After generating the terrain, remove every block that's a border (adjacent to an "air" tile),this will make sure that even 1 wide gaps become walkable.

---
Tags: unity, c#, procedural-generation, godot
---


# Question
Title: Unity NavMesh pathfinding using Job System
I'm trying to write a system where I can run each enemy's NavMesh pathfinding in parallel, using Job System.

The problem I'm having is that I can't pass the NavMesh agent argument as it's a reference type.

> InvalidOperationException: PathfindJob.agent is not a value type. Job structs may not contain any reference types.

I'm probably approaching this problem in a completely wrong way, but this is all I've come up with.

**Here's the current Enemy code**

```
using System.ComponentModel;
using Managers;
using Unity.Collections;
using Unity.Jobs;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Jobs;

namespace Characters
{
    [RequireComponent(typeof(Rigidbody))]
    public class Enemy : MonoBehaviour
    {
        [Header("Stats"), SerializeField] private int _health = 100;
        [SerializeField] private int _damage = 20;
        [SerializeField] private float _aggroRadius = 10f;

        private Rigidbody _body;
        private NavMeshAgent _agent;
        private Transform _target;

        private void Awake()
        {
            _body = GetComponent<Rigidbody>();
            _agent = GetComponent<NavMeshAgent>();
            _target = PlayerManager.GetInstance().GetPlayer();
        }

        private void OnDrawGizmosSelected()
        {
            Gizmos.color = Color.blue;
            Gizmos.DrawWireSphere(transform.position, _aggroRadius);
        }
    }

    public struct PathfindJob : IJobParallelForTransform
    {
        public Vector3 TargetPosition;
        public NavMeshAgent Agent;
        public float AggroRadius;

        public void Execute(int index, TransformAccess transform)
        {
            var distance = Vector3.Distance(TargetPosition, transform.position);

            if (distance < AggroRadius)
                Agent.SetDestination(TargetPosition);
        }
    }
}

```

I'm scheduling the job from the GameManager class.

# Answer
> 0 votes
So, IIRC the only thing that you are doing in parallel with this is calculating the distance and setting the target. The actual Agent calculations happen in a different thread within the NavMesh system. All you are doing is (re)setting the NavMesh agent target over and over again - basically just passing in a Vector3 over and over.

What you (presumably) want is NavMesh actually be implemented in ECS, which is something entirely different. You could absolutely implement your own A\* system in ECS as an exercise, but I suspect that won't get you closer to making a game.

Here is a video that does a good job showing the limits/capabilities of NavMesh agents without ECS.

https://www.youtube.com/watch?v=G9Otw12OUvE

There does appear to be some value to ECS + NavMesh by forcing query calculation. I found this GitHub repo: https://github.com/zulfajuniadi/unity-ecs-navmesh

Good luck!

# Answer
> 0 votes
Currently Jobs are pretty limited in terms of thread-safety. There is no guarantee your NavMeshAgent can be accessed in a thread-safe manner at all. The actual limitation is that only value types and special objects such as NativeArrays are allowed to be processed inside of jobs as of now.

You might want to dig deeper into the sources and look for a NavMeshQuery if I recall correctly.

Alternatively you could write a job that would tag all agents that should start navigating somewhere else and use a hybrid system to fetch those tagged entities and execute the `SetDestination` method with the data from the tag component.

---

Edit: Keep in mind that the newest ECS package and Job/Burst infractructure is bleeding edge technology and considered not production ready. I am not quite sure about the rules and stance of StackExchange. Does the community allow discussions of tools/packages that are highly in flux? Any information shared might be obsolete pretty quick.

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


# Question
Title: Handling different aspect ratios on a 2D dodging game
I've been making a game where the player is on the ground and has to dodge objects falling to the ground. Since I'm using libGDX (But the question still applies to any other language/framework), The game will have to handle both desktop and mobile apps.

I'm trying to make the game fit vertically into any aspect ratio while making it fair, but this is my first time trying to deal with this, and I'm looking for a good way to do this. My game has 3 main regions: The game, the data (Health/coins), and the GUI (Pause button). Here are my ideas so far:

Horizontal: Game in the center with everything else on the sides

Vertical: Game on the bottom with data on top

Everything else: No room for GUI on sides/bottom, GUI on top of game

I've seen other questions similar to this, but none of them cover a game similar to this type.

# Answer
> 0 votes
To maintain consistency, I would keep the same relative areas in each aspect ratio and in the vertical layout, put the data in a short row along the bottom and the GUI in a short row on top. This would mirror the left, center, right arrangement of your horizontal layout.

This would allow you to keep the same area for your game. And then your layouts can be chosen dynamically. I was just trying to solve a similar problem in my website with a 3 column or row layout of thumbnails, a large image, and text. By the way the solution was to make the body or surrounding div tag `display:flex;` and `flex-flow:row nowrap;`

---
Tags: 2d, libgdx, gui, ui-design, aspect-ratio
---


# Question
Title: Can't get the current animation state name (hash or .IsName) to work
I have some hard times trying to get the current animation state name in Unity, to perform specific actions while I'm in a certain state. I want to know when I'm the "ThoughtsStill" state, I only have the default layer (Base Layer):

To do this, here is what I tried:

```
AnimatorStateInfo curr_state = _animator.GetCurrentAnimatorStateInfo(0);
if (curr_state.shortNameHash == Animator.StringToHash("ThoughtsStill"))
{
    Debug.Log("I'm in ThoughtsStill state").
}

```

which is not working.

I also tried with `IsName()` method but it is not working too (both tried to compare "Base Layer.ThoughtsStill" and "ThoughtsStill").

I'm certain that I'm going in this ThoughtsStill state but I don't know why I can't get it.

Do you guys have any ideas or leads?

Thanks !

# Answer
> 2 votes
I can confirm that you do need to include the space in the full name, so `"Base Layer.ThoughtsStill"` is the correct name to use and I always use `fullPathHash` instead of `shortNameHash`. Also, you might want to look into State Machine Behaviours: https://docs.unity3d.com/ScriptReference/StateMachineBehaviour.html

Using State Machine Behaviours it's much easier to catch when a state starts/updates/exists and catch it exactly the moment it triggers. So my recommendation would be to:

1) Cache the generated hash code

```
stateHashCached = Animator.StringToHash("Base Layer.ThoughtsStill"))

```

2) Implement a StateMachineBehaviour, attach it to your animator's Base Layer and listen for `OnStateEnter`.

3) Do your compare inside the `OnStateEnter` like this:

```
if (stateHashCached ==  curr_state.fullPathHash)

```

# Answer
> 0 votes
You should try debugging by printing out the hashed name of the current state and print out the hashed string. Just read from the console and see the difference. If they are different you might not be at all going through that state. Printing them out is always the best thing to do in those situations.

You might have added an additional space or made a typo somewhere.

If they are not equal, try testing with other names and see when they become equal. That way you will be able to discover which states you are going through. You might not be going through that state at all.

Also try using nameHash instead of shortNameHash and then just use Base Layer.ThoughtsStill as you said you tried with isName method.

Or, Unity maybe doesn't want you to type "Base Layer.ThoughtsStill", but it maybe wants you to type "BaseLayer.ThoughtsStill" without a space. I'm not sure about that but just try it out.

Also NEVER convert your string to hash every single time in a loop. Just make a readonly variable at the top of the class and use it every time because this is expensive.

# Answer
> 0 votes
We can get the current playing clip name in the layer using following code

```
private Animator animator = GetComponent<Animator>();
private AnimatorClipInfo[] clipInfo;

public string GetCurrentClipName(){
    clipInfo = animator.GetCurrentAnimatorClipInfo(0);
    return clipInfo[0].clip.name;
}

```

Note : This code is tested in unity version 2018.3 so I am not sure if this works on previous version or not.

---
Tags: unity, animation-states
---


title: What's the best way to index my object?

text:
# Question
Title: What's the best way to index my object?
Obviously, lists automatically create their own index. So basically I wouldn't need this function at all. But I figured it was safer in case my list index ever changed (e.g. adding a new item at the beginning of the list, would shift the index numbers for all the other list items).

```
public EmpireAgentView ShowEmpireView(int eIndex)
{

    foreach (EmpireAgentView e in EmpireViews)
    {
        if (e.EmpireIndex == eIndex)
        {
            Debug.Log("Showing Empire for Agent: " + e.AgentName);
            return e;
        }
    }

    Debug.LogError("No EmpireAgentView Found for that empire: " + eIndex);
    return new EmpireAgentView(9999);
}

```

So in this case, I added the property "EmpireIndex" to the EmpireAgentView object. So now, whenever I need to access a specific EmpireAgentView from the EmpireViews list, I would use ShowEmpireView(1) instead of EmpireViews\[1\].

Each EmpireAgentView object has unique information about the same Agent object. For example, where the Agent is currently located. If we have 4 empires, than there will be 4 EmpireAgentView objects in the Agent class. Each empire has their own idea of where the Agent is currently located, so I need to be able to access the specific empires data on this agent. Right now, I assign a simple int called EmpireIndex to each EmpireAgentView, so that I can make sure I got the right view for the right empire. If i simply used EmpireViews\[3\], and that list rearranged itself somehow, (like adding an EmpireAgentView object to the beginning of the list, presumably) than all that information would be mixed up for the empires.

Is that the best way of doing that? is there a better way of finding it? Or am I being TOO careful, and just need to not add new EmpireView's to the beginning of the list? (I'm new to C#, is there anything else that would change the index of a list item?)

# Answer
When using a list, your way would be the best way to find the correct view within the list. It ensures that the correct view is found, no matter what index it happens to have in the list. This also elminates any problems that could appear, if an agent was put at the wrong index from the beginning.

The list index can be changed via multible operations. Generally it is pretty uncommon to add items in the beginnig of a list when used like this. I would worry more about entries being removed, as that would shift all following items.

If you end up with a lot of Empires, your lookup time would also start to rise, since in worst case, you would have to go through the whole list to find a view. To prevent this and get a constant lookup time, I would suggest using a Dictonary instead, with an int as the key, and the view as the value. Read more here C# Dictonary vs List lookup time

By using a dictonary, the lookup would be as simple as:

```
public EmpireAgentView ShowEmpireView(int eIndex)
{
    if(EmpireViews.ContainsKey(eIndex)){
        EmpireAgentView e = EmpireViews[eIndex];
        Debug.Log("Showing Empire for Agent: " + e.AgentName);
        return e;
    }

    Debug.LogError("No EmpireAgentView Found for that empire: " + eIndex);
    return new EmpireAgentView(9999);
}

```
> 1 votes

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


# Question
Title: How can I avoid the precision loss when recentering objects on open terrain?
For a better context this question is related to this one:

What's the largest "relative" level I can make using float?

When the player is moving too far away from the center, all the scene and objects are moved in the opposite direction, in order to bring the center closer to the player and avoid float precision issues.

Recentering all objects makes me doubt a little, since it might still accumulate error since it's an addition. I also don't think I can tell a physics engine to just teleport all its object without causing weird behavior.

# Answer
Addition can lead to a loss of precision when *increasing* in magnitude.

eg:

$$(1 - 2^{-24}) + (2^{-23}) = 1 + 2^{-24} ≈ 1 \text{(nearest float)}$$

Here we can represent numbers in intervals of \\$2^{-24}\\$ in the range 0.5–1, but the addition bumps us out of that range and into the range 1–2, where we can represent only intervals of \\$2^{-23}\\$, so we're forced to round the result.

Bur when we *reduce* the absolute magnitude of the number, as we do when re-centering, we do not lose available precision in this way. Because of the way floating point keeps more precision closer to zero, reducing a number's absolute magnitude will put it into a range that has at least as much available precision, if not more, than it had previously.

You could get rounding differences if your offset value is not representable in the magnitude range you're starting from — so the result of the subtraction is not exactly representable either and requires rounding even though the precision available does not decrease — but this is easily avoidable by choosing a recentering interval that is itself a representable float. Something simple like a power of two works well here.

So:

1. Establish a minimum precision you want to maintain
2. Consult the table in the answer you linked to find the range at which you lose that precision
3. Step back by a power of two from that limit

(or more if you want to keep some buffer for chains of lossy operations elsewhere in your game)
4. Pick the next lower power of two as your recentering interval

Now you will lose no bits of precision below your chosen minimum in any of your relative positions when you recenter.
> 1 votes

---
Tags: opengl, physics, floating-point, open-world
---


title: Pygame Collide Rect

text:
# Question
Title: Pygame Collide Rect
Currently making a maze game. Maze is drawn, everything is drawn with pygame.draw.rect. I have tried using pygame.coliderect() to check for colisions, but it isn't working. The current error message I keep receiving says that my player rectangle (drawn with a class called Sprite) has no attribute 'colliderect'

The code below shows how I am currently drawing the maze and character, and how I am attempting to call colliderect. Please explain to me what it is I am doing wrong or why this code isn't working.

```
# Hit variable to tell if the player is touching the wall#
hit = False
#Draw command for moving box set to Sprite#
class Sprite:
    def __init__(self,x,y,width,height):

        self.x=x

        self.y=y

        self.width=15

        self.height=15
#Used to draw the character to the screen
    def render(self):
        pygame.draw.rect(screen,YELLOW,(self.x,self.y,self.width,self.height))
sprite1 = Sprite(30,40,15,15)

moveX,moveY=0,0
#Create the Maze
class Maze: #Maze class to make maze creation and editing easier
    def __init__(self):
       self.W = 20 #Sets the width of the map
       self.H = 10 # Sets the heigth of the map
#Create a series of 1s and 0s to indicate where there is and isn't a wall.
#0 means nothing is there or the space is 0pen (pun intended)
#1 means something is there or no 1 shall pass.
       self.maze = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
                     1,0,0,1,0,0,1,1,0,0,0,1,0,0,1,0,0,1,0,1,
                     1,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,1,1,
                     1,1,0,1,1,1,1,1,1,0,0,1,0,1,0,1,0,0,1,1,
                     1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,1,0,0,1,1,
                     1,0,0,1,0,1,1,1,1,0,0,0,0,1,0,1,0,0,0,1,
                     1,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,1,
                     1,1,1,0,1,1,0,1,1,0,0,0,1,1,1,1,1,1,0,1,
                     1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,
                     0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1]

    def draw(self):
        bx = 0 #Used to loop horizontally through the 1s and 0s as the game draws
        by = 0 #Used to loope vertically through the 1s and 0s as the game draws
        self.surface = screen
        self.color = BLUE
        for i in range(0, self.W*self.H):
            if self.maze[ bx + (by*self.W) ] == 1:
                pygame.draw.rect(self.surface, self.color, ( bx * 25, by * 25, 25, 25))

            bx = bx + 1
            if bx > self.W-1:
                bx = 0
                by = by + 1
maze = Maze()
## check if the player is still in the maze##
    if sprite1.colliderect(maze):
        hit = True
    else:
        hit = False
##reverse player's movement if they hit the wall##
    if hit == True:
        moveX *= -1
        moveY *= -1

# --- Drawing code should go here
    screen.fill(BLACK)
    # First, clear the screen to black. Don't put other drawing commands
    # above this, or they will be erased with this command.
    maze.draw()
    sprite1.x += moveX
    sprite1.y += moveY
    sprite1.render()
    # --- Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

```

# Answer
So I think the main thing that you've confused here is rendering & game logic. Rendering a rectangle to the screen doesn't mean that collision checks will be performed against it. Instead, you need to specify a logic object for that which Pygame can use for collision detection. By default, no external class has the properties that are required for `colliderect` to work.

So, you want to add a `pygame.Rect` to your player class and make sure it's up-to-date. One way would be to get rid of the separate X, Y, width and height values and just use a rect instead. Or you could add a method that returns a rectangle representing the player sprite.

```
def get_rect(self):
    return pygame.Rect(self.x, self.y, self.width, self.height)

```

Now, you want to either call `sprite1.get_rect().colliderect(a_rect)` or `sprite1.rect.colliderect(a_rect)` depending on which approach you take.

This is also an issue with your `Maze` class. The simple and naive way to do this would be to iterate over all grid positions inside your maze and check collisions against all those tiles.

```
bx = 0
by = 0
for i in range(0, self.W * self.H):
    if self.maze[ bx + (by * self.W) ] == 1:

        rect = pygame.Rect(bx * 25, by * 25, 25, 25)

        if rect.colliderect(sprite1.get_rect()):
            pass  # Collision!

        bx = bx + 1
        if bx > self.W-1:
            bx = 0
            by = by + 1

```

You probably want to look into only checking the grid items that the player is overlapping, but that's a different topic.

So, to sum it all up, your issue is that drawing something doesn't make the thing you drew collidable. You need `pygame.Rect` objects for that.
> 2 votes

# Answer
N.Nugget, you are calling colliderect as `sprite1`. You will have to put it like this:

`if pygame.sprite.collide_rect(sprite1, maze):
 hit = True
 else:
 hit = False`

I hope it serves you well.
> 0 votes

---
Tags: collision-detection, python, pygame
---


# Question
Title: Audio Clip not working on Collision when destroying an object
So I made a game where you shoot a laser and if it hits the enemy it makes an explosion sound and destroys the enemy. The only thing is whenever I try to get the audio to play it doesn't which I assume is caused by the enemy being destroyed. I have tried to use the Play() methods and PlayOneShot() methods but they both don't seem to help me out.

This is my current code:

```
public AudioClip explosion;
public AudioSource explosionAudioSource;

public void OnTriggerEnter2D(Collider2D other)
    {

    void Start() {
    explosionAudioSource = GetComponent<AudioSource>();
    }
        if (this.tag == "Enemy" && other.tag == "Laser")
        {
            explosionAudioSource.PlayOneShot(explosion);
            Destroy(other.gameObject);
            Instantiate(enemyExplosion, new Vector3(transform.position.x, transform.position.y, transform.position.z), Quaternion.identity);
            Destroy(this.gameObject);
            uiManager.UpdateScore();
        }
```

Thanks!

# Answer
> 1 votes
I was able to fix my problem by instantiating a prefab with the audio source onto it and have it play on awake when the object was instantiated it would play the sound perfectly.

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


# Question
Title: How do you prepare for out of memory conditions?
This can be easy for games with well defined scope, but the question is about sandbox games, where the player is allowed to create and build *anything*.

Possible techniques:

* Use memory pools with upper limit.
* Delete objects that are no longer needed periodically.
* Allocate extra amount of memory at the beginning so it can be freed later as a recovery mechanism. I would say around 2-4 MBs.

This is more likely to happen in **mobile/console platforms** where memory is *usually* limited unlike your 16 GB PC. I am assuming you have full control over memory allocation/deallocation and no garbage collection involved. That's why am tagging this as C++.

Please note that I am not talking about *Effective C++ Item 7 "Be prepared for out-of-memory conditions"*, even though it's relevant, I would like to see an answer more related to game development, where you usually have more control over what's happening.

To summarize the question , **how do you prepare for out of memory conditions for sandbox games, when you are targeting a platform with limited memory console/mobile ?**

# Answer
> 16 votes
Generally, you don't handle out-of-memory. The only sane option in software as large and complex as a game is to just crash/assert/terminate in your memory allocator as soon as possible (especially in debug builds). Out-of-memory conditions are tested for and handled in some core system software or server software in some cases but not usually elsewhere.

When you have an upper memory cap you instead just ensure that you never need more than that amount of memory. You can keep a maximum number of allowed NPCs at a time, for instance, and simply stop spawning new non-essential NPCs once that cap is hit. For essential NPCs you can either have them replace non-essential ones or have a separate pool/cap for essential NPCs that your designers know to design around (e.g. if you can only have 3 essential NPCsa, the designers will not put more than 3 in an area/chunk - good tools will help designers do this properly and testing is essential of course).

A really good streaming system is also important especially for sandbox games. You don't need to keep all NPCs and items in memory. As you move through chunks of the world new chunks will be streamed in and old chunks streamed out. These will generally include NPCs and items as well as terrain. Design and engineering caps on item limits need to be set with this system in mind, knowing that at most X old chunks will be kept around and pro-actively loaded Y new chunks will be loaded, so the game needs to have space to keep all the data of X+Y+1 chunks in memory.

Some games do attempt to handle out-of-memory situations with a two-pass approach. Keeping in mind that most games have a lot of technically unnecessary cached data (say, the old chunks mentioned above) and a memory allocation might do something like:

```
allocate(bytes):
  if can_allocate(bytes):
    return internal_allocate(bytes)
  else:
    warning(LOW_MEMORY)
    tell_systems_to_dump_caches()

    if can_allocate(bytes):
      return internal_allocate(bytes)
    else:
      fatal_error(OUT_OF_MEMORY)

```

This is a last-stop measure to deal with unexpected situations in release but during debugging and testing you should probably just immediately crash. You don't want to have to rely on this kind of stuff (especially because dumping the caches may have some serious performance consequences).

You might also consider dumping high-res copies of some data, for instance you might dump the higher-resolution mipmap levels of textures if you are running low on GPU memory (or any memory in a shared-memory architecture). This usually requires a lot of architectural work to make worth it, though.

Note that some very unlimited sandbox games can be rather easily just crashed, even on PC (remember that the common 32-bit apps have a limit of 2-3GB of address space even if you have a PC with 128GB of RAM; a 64-bit OS and hardware allows more 32-bit apps to run simultaneously but can't do anything to make a 32-bit binary have a larger address space). In the end, you either have a very flexible game world that will need unbounded memory space to run in every case or you have a very limited and controlled world that always works perfectly in bounded memory (or something somewhere in between).

# Answer
> 5 votes
The application is usually tested on the targeted platform with the worst case scenarios and you will always be prepared for the platform you are targeted. Ideally the application should never crash, but other than optimization for specific devices, there are little choices when you face low memory warning.

The best practice is to have preallocated pools and the game uses from the very beginning all the needed memory. If your game has a maximum of 100 units than have a pool for 100 units and that's it. If 100 units exceeds the mem requirements for one targeted device then you can optimize the unit to use less memory or change the design to a maximum of 90 unit. There should be no case where you can build unlimited things , there should always be a limit. It would be very bad for a sandbox game to use `new` for each instance because you can never predict the mem usage and a crash is a lot worst than a limitation.

Also the the game design should always have in mind the lowest targeted devices because if you base your design with "unlimited" things in it then it will be a lot harder to solve the memory problems or change the design later on.

# Answer
> 1 votes
Well, you can allocate about 16 MiB (just to be 100% sure) at startup or even in `.bss` at compile time, and use a "safe allocator", with a signature like `inline __attribute__((force_inline)) void* alloc(size_t size)` (`__attribute__((force_inline))` is a GCC/`mingw-w64` attribute that forces inlining of critical code sections even if optimizations are disabled, even though they should be enabled for games) instead of `malloc` that tries `void* result = malloc(size)` and if it fails, drop caches, free the spare memory (or tell other code to use the `.bss` thing but that's out of scope for this answer) and flush unsaved data (save the world to the disk, if you use a Minecraft-like concept of chunks, call something like `saveAllModifiedChunks()`). Then, if `malloc(16777216)` (allocating these 16 MiB again) fails (again, replace with analog for `.bss`), terminate the game and show `MessageBox(NULL, "*game name* couldn't continue because of lack of free memory, but your world was safely saved. Try closing background applications and restarting the game", "*Game name*: out of memory", MB_ICONERROR)` or a platform specific alternative. Putting it all together:

```
__attribute__((force_inline)) void* alloc(size_t size) {
    void* result = malloc(size); // Attempt to allocate normally
    if (!result) { // If the allocation failed...
        if (!reserveMemory) std::_Exit(); // If alloc() was called from forceFullSave() or reportOutOfMemory() and we again can't allocate, just quit, something is stealing all our memory. If we used the .bss approach, this wouldn't've been necessary.
        free(reserveMemory); // Global variable, pointer to the reserve 16 MiB allocated on startup
        forceFullSave(); // Saves the game
        reportOutOfMemory(); // Platform specific error message box code
        std::_Exit(); // Close silently
    } else return result;
}

```

You can use a similar solution with `std::set_new_handler(myHandler)` where `myHandler` is `void myHandler(void)` that's called when `new` fails:

```
void newerrhandler() {
    if (!reserveMemory) std::_Exit(); // If new was called from forceFullSave() or reportOutOfMemory() and we again can't allocate, just quit, something is stealing all our memory. If we used the .bss approach, this wouldn't've been necessary.
    free(reserveMemory); // Global variable, pointer to the reserve 16 MiB allocated on startup
    forceFullSave(); // Saves the game
    reportOutOfMemory(); // Platform specific error message box code
    std::_Exit(); // Close silently
}

// In main ()...
std::set_new_handler(newerrhandler);

```

---
Tags: c++, optimization, memory-efficiency, memory
---


# Question
Title: Inverse transformation matrix for checking whether a point is inside a rect
I'm trying to determine which nodes in my scene graph contain a given point in global coordinate space, using the inverse of the node's global transformation matrices.

Here's a simplified version of the Node (real version does dirty checks and caches matrix etc).

```
class Node {
  parent: Node;

  width: number;
  height: number;

  translation: Vec2;
  rotation: number;
  scale: number;

  // Get the transformation matrix required to draw this node onscreen
  get matrix() {
    let mat = mat2d.clone(this.parent.matrix);
    mat2d.translate(mat, mat, this.translation);
    mat2d.rotate(mat, mat, this.rotation);
    mat2d.scale(mat, mat, [this.scale, this.scale]);
    this.matrix = mat;
  }

  // Check if point is inside this node's rect
  contains(x: number, y: number) {
    let point = this.toLocalPoint(x, y);

    return (
      point.x >= this.translation.x &&
      point.y >= this.translation.y &&
      point.x <= this.translation.x + this.width &&
      point.y <= this.translation.y + this.height
    );
  }

  // Convert a point in global space to local space
  toLocalPoint(x: number, y: number) {
    let inverse = mat2d.create();
    mat2d.invert(inverse, this.matrix);

    let point = vec2.fromValues([x, y]);
    vec2.transformMat2d(point, point, inverse);

    return point;
  }

}

```

This is working fine for the renderer. Here's an example of how that looks for reference.

```
for (let node of nodes) {
  renderer.push(node.matrix);
  renderer.draw(node.texture);
  renderer.pop();
}

```

The `Node#contains` method has some problems. It seems to adjust correctly to detect rotation and scale changes, but as soon as there's a translation applied to a node, the inverse matrix gives the wrong results.

Here's an example that shows a test of whether the mouse cursor is inside a node.

* The cyan node is at the origin, given a scale, and rotation.
* The magenta node has the same scale and rotation, but it has also been translated along the X axis.

There are points off to the right that are registering as inside the node though.

I'm fairly sure that this means that the separate steps of the matrix transform are being applied in the wrong order, but I'm not sure how to apply the inverse matrix in any other way (without decomposing it into the 3 individual components of the transform and applying them in the reverse order that the `Node#matrix` getter does).

Have I misunderstood how the inverse matrix works here?

# Answer
The typical order of your matrix composition is scale then rotation then translation. As matrices are not communitive, the order obviously matters.

I'm going to assume (seeing that I have no experience with the library you are using) that yours is in the correct order. If it isn't, then I would guess swapping your scale and translation will make it work.

The inversion of the matrix is basically going to return you to where your object origin was, so your understanding of the concepts is correct. You do not need to decompose the matrix into its separate steps for inverting.
> 0 votes

---
Tags: matrix, scene-graph
---


# Question
Title: Godot 3: How to add images without creating scenes?
To add images, as far as I know you create a sprite in godot, but I don't want to do that, I'd like to do it pro grammatically using arrays, the reason is I'm creating a card game and I don't want to add 52 scenes and then attach 52 sprites.

Isn't there a smarter way to do it? I haven't found anything. What I'm doing now is I have a card scene and then I inherit from it the other cards scenes and attach sprites to them and add them to a 2d array but I'd like another way of doing that

# Answer
> 2 votes
Put your cards in a folder and set them names which follow a logic, like: card\_0, card\_1, card\_2, and so on. As you can see, you can use a loop from 0 to 52 and using the method

```
load(your-path + number)

```

you can retrieve all cards.

I think you mean by a scene that you create a scene which handle the logic for a card. If this is the case, you need to instantiate the scene and call a method you defined, in order to pass the path of your card and load it.

Good luck!

# Answer
> 1 votes
I used the sprite sheet found at https://www.emanueleferonato.com/2017/03/04/html5-deck-of-cards-management/ .

You can create a single Card scene with a single sprite. The sprite is set up as animation (4 Vframes by 13 Hframes), even though the animation won't actually play continuously.

Instantiate 52 instances of the Card scene, setting each instance's frame in a loop:

```
var deck = []
var c = load("res://Card.tscn")
for i in range(52):
    var n = c.instance()
    n.position.x = i * 30
    n.position.y = 200
    n.get_node("Sprite").frame = i  # <==== this is the trick
    deck.append(n)
    add_child(n)

```

Result: https://www.wookilar.com/img/cardswave.gif

---
Tags: godot
---


# Question
Title: How to stop the ship before falling into whirlpool?
I am programming a game in Unity with C#

1. I have a ship which I needs to move towards the whirlpool (target).
2. The ship has to be stopped before entering the whirlpool.

I need advice as to how to implement my `distToWhirlpool` and `distToStopPoint`

Here is the assignment I'm trying to solve:

> In this task, control the movement of the hero ship around the lake and stop within a defined distance of a whirlpool.
>
> **Task Outline**
>
> Control of the ship’s movement is achieved by commanding the activation of forward and rotational thrusters and/or providing a target point given the information available on the environment. Control is required to ensure that the hero ship can move safely around the map without colliding with objects that would damage or destroy it. To demonstrate control you must accelerate your ship to a prescribed speed and maintain this speed for about 2 seconds. As the hero ship moves, the interface will give it its position in the lake and its distance from the lake’s centre. To complete the task the hero ship must move to a whirlpool and stop within a defined distance from it without being sucked in to the whirlpool.

Here is the code I have so far:

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

public class AI : MonoBehaviour {

    public struct Velocity2 // Structure of velocity
    {
        public float forward;   // Forward velocity of object in m/s
        public float right;     // Velocity to the right of object in m/s
    }

    [System.Serializable]
    public struct Position2 // Structure of a position
    {
        public float north;     // meters north from centre of lake
        public float east;      // Meters east from centre of lake
    }

    public struct HeroStatus    // Structure of information on the Hero's status
    {
        public Velocity2 velocity;      // Velocity of the Hero in m/s - - not changeable
        public Position2 position;      // Position of the Hero - not changeable
        public float angleCW;           // Orientation of Hero in degrees ClockWise from North - not changeable
        public float shield;            // Shield energy available, range 0 - 1 - not changeable
        public float Hull;              // Hull integrity, range 0 - 1 - not changeable
        public bool shieldActive;       // True when the shield is on - not changeable
        public float distFromCentre;    // Hero distance from the centre of the lake - can be used to avoid lake edges - not changeable
        public float maxForwardSpeed;   // This reports the maximum forward speed of the Hero in m/s - not changeable
        public float maxRotationSpeed;  // This reports the maximum rotational speed of the Hero in degrees/sec - not changeable
        public bool task;               // True if Hero is in Task Mode, else Hero is in Game Mode - not changeable
        public int level;               // In Task mode this is the task number, in game mode this is the level number - not changeable
        public int maxLives;            // The maximum lives available  - not changeable
        public int livesLeft;           // The number of lives left in the game. In Tasks it is the number of tries left for the task. - not changeable
        public float taskTimeMax;       // The amount of time a task has to complete the task - not changeable
        public float taskTimeLeft;      // During tasks this is the time remaining to complete the task. - not changeable
        public float stopDistToWhirlpool;   //Dist to stop from Whirlpool in Task 1 - not changeable
        public float whirlpoolDiameter; // Diameter of a whirlpool
        public bool inMenu;             // True when the Game or Task is in a menu  - not changeable
        public bool useAI;              // True when AI mode is active
        public bool useForwardThrust;   // True when forwardThrust and not forwardSpeed is use for forward/reverse motion
        public float maxForwardThrust;  // Maximum forward thrust available
        public bool useRotateThrust;   // True when rotateThrust and not forwardSpeed is use for forward/reverse motion
        public float maxRotateThrust;  // Maximum rotate thrust available
    }

    public HeroStatus heroStatus;       // Hero's status - updated every frame - not changeable

    public Position2[] drones;          // Array of all drones - updated every frame
    public Position2[] whirlpools;      // Array of all Whirlpools - updated every frame
    public Position2[] shieldPowerups;  // Array of all Shield power ups - updated every frame
    public Position2[] hullPowerups;    // Array of all Hull Power ups - updated every frame

    public bool useTarget = true;   // If true, the target variable is used as a position to move toward,
                                    // If False, only forwardSpeed/Thrust and rotationSpeed/Thrust is used to move the Hero

    public Position2 target;        // This sets the position the Hero should move toward - Uses 'forwardSpeed/Thrust' and 'rotationSpeed/Thrust' parameters to move

    public float forwardSpeed = 0;  // This sets the desired forward speed of the Hero in m/s - Used when useThrust is false
    public float rotationSpeed = 0; // This sets the desired rotational speed of the Hero in Degrees/sec
    public float forwardThrust = 0; // Thrust used to drive Hero- Used when useThrust is True
    public float rotateThrust = 0;  // Thrust used to rotate Hero- Used when useThrust is True

    public bool turnOnShield;   // When set to true turns on the Hero's shield - If the Shield is out of energy it will not turn on

    public bool logData = false;    // Set to true to start a data log file and reset to false to close the file.
    public string logDataString = "";// Once the data log file is open, the contents of this string will be write to the data log file.
                                     // When the data file is first opened, this string will be writen to it as the first line of date.
                                     // So Use it to set column heading and put commas between each heading.
                                     // Also put commas bewteen data to create a Comma Seperated Variable (CSV) file for excel.
    public bool resetDataRunTime = false;   // Set this to true to reset the datalogging run time that is reported in the data log to zero.
                                            // It will be reset to false automatically.
    public string debugString = ""; // The contents of this string will be writen to the screen. Toggle it on and off with the I key.

    // **************************************Do Not Modify the variables above ************************************************************

    //***************************************Place your variables below********************************************************************
    public float thrustScale = 0.001f;
    public float stopDist = 55f;
    public float velScale = 4.2f;

    // Used to initialise at the start of a Game Level or Task
    public void StartTaskOrLevel()  // This is called at the start of each Task or game level
    {
        forwardThrust = 0f; // Initialise motion to zero
        rotationSpeed = 0f;
    }

    // Used to update Hero during a task or Game Level.
    public void TaskOrLevelUpdate() // This is called 50 times per second during a Task or game level but not when a menu is displayed.
    {
        if (heroStatus.task)
        {                   // Do Tasks
            switch (heroStatus.level)
            {
                case 1:
                    task1();
                    break;
                case 2:
                    task2();
                    break;
                case 3:
                    break;
                case 4:
                    break;
                case 5:
                    break;
            }
        } else
        {                   // Do Game

        }
    }

    // Used to close anything at the end of a Game Level or Task
    public void EndTaskOrLevel()  // This is called at the end of each Task or game level
    {

    }

    public void task1()
    {
        float deltaNorth, deltaEast, distToWhirlpool, distToStopPoint;
        float desiredVel;

        deltaNorth = whirlpools[0].north - heroStatus.position.north;
        deltaEast = whirlpools[0].east - heroStatus.position.east;
        distToWhirlpool = Mathf.Sqrt(Mathf.Pow(deltaNorth, 2) + Mathf.Pow(deltaEast, 2));
        distToStopPoint = distToWhirlpool - heroStatus.stopDistToWhirlpool;

        target = whirlpools[0];
        useTarget = true;

        desiredVel = distToStopPoint * velScale;
        if (distToStopPoint < stopDist)
        {
            forwardThrust = heroStatus.maxForwardThrust * -desiredVel * thrustScale;
        }
        else
        {
            forwardThrust = heroStatus.maxForwardThrust;
        }
        rotationSpeed = heroStatus.maxRotationSpeed;
    }

    public void task2()
    {

    }
}

```

# Answer
> 0 votes
I am not 100% sure what you mean by "north and east" as coordinates, can you please give an example?

But I can help you with some pseudocode: So part one would be to find the actual goal of your ship, which is "before the whirlpool". You can count it like this

```
vector3 direction = whirlpool.position - ship.position; //gives you direction
direction = direction - direction.normalize() * distanceToWhirlPool;

```

distanceToWhirlPool is how far from it you want the ship to stop.

then, (probably in the ship's update function) you would do:

```
this.rotation = Lerp.(this.rotation, rotationToWhirlpool); //rotating towards the whirlpool, you can use other ways
this.move(this.forward * shipSpeed * Time.deltaTime);

```

Do you have any questions? Is anything not clear?

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


# Question
Title: How to Destroy an Instance of a Prefab Without Removing the Prefab?
I'm making a simple runner game where obstacles spawn off in the distance and move towards the player. I want to remove them after they're invisible to the player.

I made an `Obstacle` prefab and a `SpawnObstacles.cs` script, which I added to an empty game object. In it, I call

`Instantiate(obstaclePrefab, xLocation, yLocation, zLocation, Quaternion.identity);`

a set number of times per second.

In the `Update()` method of the obstacle prefab, I have

`if (transform.position.z < -20){
 GameObject.Destroy(gameObject);
}`

so each obstacle will destroy itself automatically.

When I run the game, I get a:

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

error on the `Instantiate` call in `SpawnObstacles.cs`

Before the game starts:

As the game is running:

How can I have a single instance of a prefab destroy itself without destroying the entire prefab? I think I need the obstacles to be inside the `Obstacle` Prefab. Perhaps I could loop through all obstacles and delete the ones invisible to the player?

# Answer
Your SpawnObstacles script is referencing a gameObject in the scene, rather than an actual prefab. To create a prefab, drag and drop your Obstacles object to your assets folder. Then make sure that your SpawnObstacles script is referencing that prefab, rather than the gameObject itself.
> 1 votes

---
Tags: unity, game-design, spawning
---


title: Player is instantly teleported back

text:
# Question
Title: Player is instantly teleported back
I built a teleporter that changes a players position and rotation. He is instantly teleported back. Why?

I'm using the standard FPS Controller.

# Answer
> 2 votes
After hours of descending into madness, i found a comment on a youtube video that mentioned, that **CharacterController** has a bug that causes this problem when using **Move()** and similar methods.

**Fix:** use **Physics.SyncTransforms()** before doing that or set the **Auto Sync Transforms** option in the settings.

Credits to the youtube-comment i could not find anymore.

---
Tags: unity
---


# Question
Title: tvOS game launch image shows on simulator but not on device
I’ve set up a launch image in XCode and it does show up in the simulator, but on the Apple TV it just displays a blurry gray background. The image is the correct size and doesn’t have any transparency.

I have tried full clean and delete the app from the device – neither has worked.

# Answer
After multiple deletes from the device, clean and device and XCode restarts, it magically started working, though not always 100% reliably. Seems to be "one of those things".
> 1 votes

---
Tags: spritekit, xcode, swift, apple-tv
---


title: Character moving without control

text:
# Question
Title: Character moving without control
i've been developing a third person adventure game on Unity with a grappling hook and i found a problem that i don't understand and it's driving me mad. Basically, if the player character collides strong with another object it won't stop moving without my control. Can you help me? Here's a gameplay video (the bug starts on 00:20): https://www.youtube.com/watch?v=2XAw-nIMSvQ&feature=youtu.be

Here's a screenshot of the inspector of the player character and the object that i hooked.

Here's the character controller code:

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

public class ThirdPersonCharacterControl : MonoBehaviour
{
    public float Speed;
    //
    public Rigidbody rb;
    //

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        PlayerMovement();
    }

    void PlayerMovement()
    {
        float hor = Input.GetAxis("Horizontal");
        float ver = Input.GetAxis("Vertical");
        Vector3 playerMovement = new Vector3(hor, 0f, ver) * Speed * Time.deltaTime;
        transform.Translate(playerMovement, Space.Self);
        //Debug.Log("Movimento");
    }

    ///detetor de colisões
    void OnCollisionEnter (Collision col)
    {
        if(col.gameObject.tag == "collidable")
        {
            Debug.Log("Tocou");
        }
    }
    ///
}

```

Here's the camera controller:

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

public class ThirdPersonCameraControl : MonoBehaviour
{
    float rotationSpeed = 1;
    public Transform Target, Player;
    float mouseX, mouseY;
    //aqui meto os obstructions (onde podes fazer grappling hook)
    public Transform Obstruction1;
    public Transform Obstruction2;
    public Transform Obstruction3;
    ///
    float zoomSpeed = 2f;

    void Start()
    {
        Obstruction1 = Target;
        Obstruction2 = Target;
        Obstruction3 = Target;
        Cursor.visible = false;
        Cursor.lockState = CursorLockMode.Locked;

    }

    private void LateUpdate()
    {
        CamControl();
      //  ViewObstructed();
    }

    void CamControl()
    {
        mouseX += Input.GetAxis("Mouse X") * rotationSpeed;
        mouseY -= Input.GetAxis("Mouse Y") * rotationSpeed;
        mouseY = Mathf.Clamp(mouseY, -35, 60);

        transform.LookAt(Target);

        if (Input.GetKey(KeyCode.LeftShift))
        {
            Target.rotation = Quaternion.Euler(mouseY, mouseX, 0);
        }
        else
        {
            Target.rotation = Quaternion.Euler(mouseY, mouseX, 0);
            Player.rotation = Quaternion.Euler(0, mouseX, 0);
        }
    }
}

```

Here's the grappling hook code:

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

public class GrapplingHook : MonoBehaviour
{
    public GameObject hook;
    public GameObject hookHolder;

    public float hookTravelSpeed;
    public float playerTravelSpeed;

    public bool jumping;

    public static bool fired;
    public bool hooked;
    public GameObject hookedObj1;

    public float maxDistance;
    private float currentDistance;

    public bool grounded;
    public Rigidbody rb;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        //firing the hook
        if (Input.GetMouseButtonDown(1)/*Input.GetKeyDown(KeyCode.E)*/ && fired == false)
        {
            fired = true;
        }

        if (fired)
        {
            LineRenderer rope = hook.GetComponent<LineRenderer>();
            rope.SetVertexCount(2);
            rope.SetPosition(0, hookHolder.transform.position);
            rope.SetPosition(1, hook.transform.position);
        }

        if (fired == true && hooked == false)
        {
            hook.transform.Translate(Vector3.forward * Time.deltaTime * hookTravelSpeed);
            currentDistance = Vector3.Distance(transform.position, hook.transform.position);

            if (currentDistance >= maxDistance)
            {
                ReturnHook();
            }
        }

        if (hooked == true && fired == true)
        {
            hook.transform.parent = hookedObj1.transform;
            transform.position = Vector3.MoveTowards(transform.position,
            hook.transform.position, Time.deltaTime * playerTravelSpeed);
            float distanceToHook = Vector3.Distance(transform.position, hook.transform.position);

            this.GetComponent<Rigidbody>().useGravity = false;

            if (distanceToHook < 1)
            {
                if (grounded == false)
                {
                    this.transform.Translate(Vector3.forward * Time.deltaTime * 13f);
                    this.transform.Translate(Vector3.up * Time.deltaTime * 18f);
                }

                StartCoroutine("Climb");

            }
        }
        else
        {
            hook.transform.parent = hookHolder.transform;
            this.GetComponent<Rigidbody>().useGravity = true;
        }
        CheckIfGround();
        PlayerJump();

    }

    IEnumerator Climb()
    {
        yield return new WaitForSeconds(0.1f);
        rb.AddForce(new Vector3(0, 3, 0), ForceMode.Impulse);
        ReturnHook();
    }

    void ReturnHook()
    {
        hook.transform.rotation = hookHolder.transform.rotation;
        hook.transform.position = hookHolder.transform.position;
        fired = false;
        hooked = false;

        LineRenderer rope = hook.GetComponent<LineRenderer>();
        rope.SetVertexCount(0);
    }

    public void CheckIfGround()
    {
        RaycastHit hit;
        float distance = 1.1f;
        Vector3 dir = new Vector3(0, -1, 0);

        if (rb.velocity.y <= 0.1 && Physics.Raycast(transform.position, dir, out hit, distance))
        {
            grounded = true;
            jumping = false;

            //Debug.Log("Grounded");
        }
        else
        {

            grounded = false;
        }
    }
    void PlayerJump()
    {

        if (Input.GetKeyDown(KeyCode.Space) && grounded == true)
        {
            rb.AddForce(new Vector3(0, 20, 0), ForceMode.Impulse);
            jumping = true;
            //print("jumping");
        }
        else if (Input.GetKey(KeyCode.Space) && grounded == false && rb.velocity.y < -1)
        {
            this.GetComponent<Rigidbody>().useGravity = false;
        }
    }

}

```

And the hook detector:

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

public class HookDetector : MonoBehaviour
{
    public GameObject player;

   void OnTriggerEnter(Collider other)
   {
        if(other.tag == "Hookable")
        {
        player.GetComponent<GrapplingHook>().hooked = true;
        player.GetComponent<GrapplingHook>().hookedObj1 = other.gameObject;
        //Debug.Log("Tocou");
        }
   }
}

```

# Answer
Your character has a Rigidbody. That Rigidbody is dynamic (its `isKinematic` box is unchecked).

That means that every fixed timestep, the physics engine will integrate its motion using the Rigidbody's `velocity` property.

Because all of your player control is accomplished with `transform.Translate`, you're teleporting your character around without influencing the `velocity` of its Rigidbody. So the physics engine's idea of how your object is moving is completely disconnected from your idea of how the object is moving.

This is a common mistake that can lead to all kinds of problems like...

* Judder & broken interpolation
* Unrealistic collisions
* Objects getting wedged into or tunneling through one another
* Residual velocity moving objects in unwanted ways

That last point is the issue you're experiencing. Because you never zero-out the velocity when your character is supposed to be stationary, any leftover velocity the object had from recent collisions/etc. will keep nudging it around. `transform.Translate({0,0,0})` just says "don't add any *additional* movement through the Transform in this line," not "stop all movement from other sources like physics"

The best thing you can do, if you want to control a dynamic Rigidbody, is to do so with the physics engine, using `velocity` or `AddForce`. This keeps the motion in the control of the physics engine, so you don't create the bugs described above, and ensures that your script's idea of how the object is moving matches the physics engine's idea.

So for example, your main ground control script could look like this (do it in FixedUpdate to avoid adding a frame of latency to your game):

```
Rigidbody body;

void PlayerMovement()
{
    float hor = Input.GetAxis("Horizontal");
    float ver = Input.GetAxis("Vertical");

    // No need for deltaTime here;
    // the physics engine will integrate over the timestep for us.
    Vector3 targetVelocity = new Vector3(hor, 0f, ver) * Speed;

    // Retain body's vertical velocity to keep jumping/falling normal.
    targetVelocty.y = body.velocity.y;

    // Instead of setting directly, you can accelerate toward this target
    // to play nicer with multiple scripts manipulating the same object.
    body.velocity = targetVelocity;
}

```

See a more detailed example of incorporating acceleration here.
> 1 votes

---
Tags: unity, c#, collision-detection, physics, rigidbody
---


# Question
Title: How do the systems find the entities they should operate on in Entity-Component-System pattern?
I have read many articles about ECS patterns. Many of them are clear on what the entity and components are but don't really talk about the system because it "varies" or just use plain English to describe the behavior like "it finds the entities the system should work on", but how exactly that happens?

Let's say we have an `Entity` class which holds the all the components it needs (`Transform, Texture, and Rigidbody`). Now I have one system called `RenderingSystem` that uses Texture and Transform to render the entity to the scene. Then how would this RenderingSystem efficiently find all the Entities that need to be drawn on the scene?

# Answer
There are a couple of ways, and they will depend on the implementation of the rest of your system. Here are a few of those I've seen.

You could *manually* tell the system(s) that a new component of a specific type has been added or removed to an entity. The system then goes visit the entity, and checks if there are other components that would make this entity interesting, in which case, it would add the entity to (or remove it from) its "list of entities to work on".

Another option is use events to achieve the same thing: when a component is added to an entity, an event that contains the id of the entity and the type of the component is raised. The systems interested in the component type listen to the event, and react to it in the same way as when done manually. This approach could be a bit easier to work with, as the developers focus on the system instead of the systems and components.

Another way I've seen is to store the components in arrays, each component type having its own array, and the index being the ID of the entity. This makes it so that the Entity and each component has the same identifier. When an 'update' has to be performed, the system just goes through the arrays of the components it's interested in, and if all the arrays have a component, it assumes that they belong to the same entity and act upon it. Implementing this requires another level of indirection between the id of the component and where it's actually stored to not waste too much space. (I believe it's something like that that is being done in EnTT.)

I've also seen theories about components stored in an SQL database. Each component type has its own table, and a `SELECT` fetches all the components that belong to the same entity. These seemed used on *large* games (MMOs).

Keep in mind that an ECS is a means to an end, not an end in itself. The advantages of an ECS over the 'traditional' hierarchy are efficiency and *ease of use*. If you decide to use an ECS to make your architecture easier to use and simpler to evolve, you can sacrifice a bit of the efficiency for the first couple of iterations of your architecture.
> 2 votes

# Answer
First of you should have a way to list all your entities. A simple list, a scene graph with only releveant entities or something completely different.

Now, one simple way to know if an entity got a certain component is to have a component flag for every entity. Whenever you create an entity or modify the components (only add and delete components from that entity), you set a flag.

For example, in c++ you could use a simple bitflag. IN this example you got 5 components, your components `Transform, Texture, and Rigidbody` could be the first, second and third component, `Position` fourth and `Sounds` the fifth.
So if you used a `char` as a bitflag and the char for entity X looked like this

```
//char flag  = "00000011"

```

Then your entity would have a `Transfort` and a `Texture` component.

The advantage of bitflags is, that you can easily check them and change them, as they are only binary operations.

```
char flagRenderingSystem = oxo3 // "00000011"
                                //char flagEntity "00001011"
if(flagEntity & flagRenderingSystem == flagRenderingSystem) (
   renderThisEntity(); //"00001011" & "00000011" = "00000011"
}

```

Best part of it, you can save this as a list of entitys that needs to get rendered. Only if an Entity changes, its flag has to be reevaluated.
> 1 votes

---
Tags: architecture, entity-component-system
---


title: How UV channels work in Unity?

text:
# Question
Title: How UV channels work in Unity?
So this **Graph Shader** is using **UV0** channel:

As far as I know, **UV layout** in a 3d model file (e.g. **fbx**) is stored inside the model itself, is that right?

But the picture above implies that a model can contain **multiple UV channels** inside of itself. **Is that true?**

# Answer
> 2 votes
UV channels in Unity work more or less the same way they do in other software. A cursory search turns up...

There's nothing particularly special happening here. A mesh can contain more than one set of texture coordinates, just like it can contain more than one set of vertex colours, normals, or tangent vectors. They're just arrays of data, and we can choose what we want to put in them or how we want to use them.

This is commonly used if you want one texture/effect to map over the object in one way (say, the object's own albedo colour map), and then want to layer a second set of texture data or effects over it, without being bound to the albedo texture's unwrap.

For example, you might use mirroring or shared UV layouts on the first texture to take advantage of repeated detail on the object & save space in its albedo texture, but you don't want those seams & repeats to show up in an overlaid mud splat texture that's re-used between multiple models.

Lightmapping is one common case. In Unity, when you bake a lightmap, it will use the second UV channel to store each vertex's texture coordinates in the baked lightmap texture. That way you can get unique lighting information on each face of every mesh, at consistent/controllable scale, even if the primary UVs of your objects share texture areas between faces or have some faces much larger/smaller than their proportional share of the UV space.

---
Tags: unity
---