# Question
Title: How might I eliminate asymmetrical gameplay caused by turn order?
I'm designing a turn based game in which players profit from buying, transporting, and selling resources. Each turn, the map has to produce a certain number of resources and different locations, and resource prices have to be updated. Because of this, each round, after every player has taken their turn, the game state has to be updated; resources are consumed/produced, prices in each cell of the map need to be updated, etc. Originally, I was going to have a simple turn order, where each player took their turn, then the map is updated, then the cycle repeats in the same order. However, after a little bit of testing, it became clear that this gave a significant advantage to players who have their turn right after the map is updated. They're able to collect the newly produced resources before any one else has a chance to.

The easiest way I could think of to balance out the gameplay for all players is to randomize the turn order after each round. While this would give everyone a fair chance, I'm worried that this might be too big of a shift away from strategy and towards luck.

How might I eliminate asymmetrical gameplay caused by turn order?

# Answer
Have the players take their turns simultaneously. This also has the added benefit of speeding up the game, because players don't sit idle while waiting for the other players to make their moves. In that case you might want to separate each round into an interactive "planning" phase and an automatic "execution" phase.

During the planning phase, all players give orders, but no orders get executed yet. The other players do not see what orders the other players are giving. Players are free to take back any actions during that phase. When a player is satisfied with their plan, they click on "end turn".

When all players clicked on "end turn", the game goes into an "execution" phase. The orders of the players get executed and the results are resolved. This requires some game design considerations for handling cases where two players make moves which contradict each other, for example two players try to collect the same resource, move onto the same space (which can only hold one of them) or buy the same unique item. There are several ways to resolve such situations. Which one is most interesting depends on your overall game design.

When this just doesn't fit into your game design, do a game-state update before every individual player's turn, and not just when all players have finished. That way every player has the opportunity to snatch a resource which got spawned on the start of their turn.
> 76 votes

# Answer
Do what Power Grid does:

Players take turns in order of *farthest behind* to *furthest ahead* in terms of scoring (in the case of Power Grid, the player who powered the fewest cities that round). This acts as a catch-up mechanic, giving the resource-advantage to the player in last place.

It also means that the player who's in the lead doesn't want to stay in the lead because it gets more expensive. For Power Grid, the "optimal" position is generally 2nd place until the game is nearing its conclusion, but I have seen "from behind" victories as well (that is, where the person in last place manages to out-compete on that last turn, taking the win).

Heck, there isn't even anything that stops the player in front from just not powering all of the cities they can a given turn in order to drop to the back and take the resource advantage, other than the fact that by powering fewer cities, they take less income. But as income is generally a diminishing returns scalar (the first city is $20, the second is $19, etc.) there are points in the game where it is more expensive to power a city than one would make in income for having done so (e.g. that unit of coal cost cost $10 to acquire this turn, but using it to power 1 more city only gets you $8 back). So generally players power as many cities as is worthwhile and the turn order attempts to keep the game close.
> 39 votes

# Answer
> The easiest way I could think of to balance out the gameplay for all players is to randomize the turn order after each round. While this would give everyone a fair chance, I'm worried that this might be too big of a shift away from strategy and towards luck.

Do not randomize, change the turn order in a fixed way. If I play first, next turn I play last; if I play second next turn I play first, and so on..
> 21 votes

# Answer
A good way to do this that I always liked is tying turn order to some resource expenditure. Thus determining turn order becomes part of the gameplay to get skilled at. This allows for some very interesting asymmetric play if done right. You can see this in games like Twilight Imperium or Five Tribes.

**Twilight Imperium** \- Each round starts with players choosing their "roles" such as warfare or trade. **Each role also has a number associated with it which determines turn order**, and **turn order determines the "role" choosing order.** The "roles" have variable strength depending on what they do, with the weakest being lower and strongest higher. The lower the number the earlier you go. In this specific case the lowest number "Initiative" has no effect and simply gives you first turn advantage, while the highest number "Imperial" scores you 2 victory points to help win. Much of the game revolves around trying to grab "Initiative" to guarantee an "Imperial" turn following.

**Five Tribes** \- Each round starts with players paying a certain number of coins. **The most coins payed gets to start the round.** Ties are resolved as a stack and the bidding is done in turn order from the previous round. That forces players to think about how much first turn advantage is really worth in game currency.
> 12 votes

# Answer
One thing to consider would be to do your update at the end/start of each player's turn instead of at the end of the round. That way, every player would have the opportunity to collect freshly spawned resources every turn. You would definitely want to shift the amount that spawns (or inflate costs) to compensate for the influx of new resources.

Alternatively, you could make it so that resource collection occurs at the end of the round instead of during any player's turn. During a round, players would be competing to be the ones controlling the resource production, but would only gain new resources at the end of the round when everything updates. With this approach you may still want to implement a turn order rotation, but it will be less imbalanced within each round.
> 8 votes

# Answer
A **non random** way to do it, its making that to be the **first player is a choice of the players**.

I mean, you can take the stone resource, the peasant or the first player turn token, flag, or any other more roleplaying reason.

Thats the way of games as the **Agricola** boardgame.

The other way of taking that first turn token is like in **Terra Mystica**.

Every player during every round (there are 6) can do an "unlimited" number of actions. One of the actions is stop playing in the current round. The good thing of do it faster than the other player is that it will mark the turn order in the next round. First to end first to play, second to end second to play, ...

Always avoid to be too much random!
> 5 votes

# Answer
The Thue-Morse sequence is the fairest way to share \[turns\] between (two) players:

AB BA BA AB BA AB AB BA BA AB AB BA AB BA BA AB BA AB AB BA AB BA BA AB AB BA BA AB BA AB AB BA BA AB AB BA AB BA BA AB AB BA BA AB BA AB AB BA AB BA BA AB BA AB AB BA BA AB AB BA AB BA BA AB BA AB AB BA AB BA BA AB AB BA BA AB BA AB AB BA AB BA BA AB BA AB AB BA BA AB AB BA AB BA BA AB AB BA BA AB BA AB AB BA BA AB AB BA AB BA BA AB BA AB AB BA AB BA BA AB AB BA BA AB BA AB AB BA ...

To calculate, count the number of bits that are 1 in the binary representation of the turn number (starting at 0):

* If there are an odd number of 1's, it's B
* Otherwise it's A

The sequence is not random, but it doesn't repeat in an intuitive pattern, so you could display the order players will move on the current turn and maybe even next turn(s) so people can strategize.

The Thue-Morse sequence can also be generalized to more than 2 players.

---

Otherwise handicap the player(s) who go earlier. This video explains how to do that: First Move Advantage - How to Balance Turn-Based Games
> 5 votes

# Answer
If both players play on the same map, that might be impossible, since the first player can change what is possible for the second, so you might try to balance it out somehow different. It depends on what is possible:

* many card games go the way of additional resources, like an additional card (MTG) or the coin in Hearthstone. This could be one option to balance it, but might be dangerous to overdo and give the second player an advantage, maybe even based on the meta.
* some boardgames go for an approach, where the first players action ready up some other actions for the next player, that might be more lucrative. In your game, the first player might sell good A to a factory, that then wants good B for the second player. If both players know of this second option, it is more of a strategic use.
* similar to that suggestion before, give the second player more information, like what spawns where next turn. This way he might secure resources for the next turn, if possible. Of course, this is only possible, if your game mechanics support something like this.
* like the others suggested, mix up the turns. But instead of making it random or change turn by turn, make it part of the game itself: maybe the one with the least amount of money or resources goes first. Or, something like "El Grande", where you bet who goes first. But don't make that betting depending on money. If you give 500 from 1000 or from 4000 credits, that's a huge difference and can snowball the game early on. You could rather gamble, how many resources some is allowed to pick, the one with fewer goes first.
> 2 votes

# Answer
I very much prefer the "simultaneous turn-based" approach used by e.g. Sword of the Stars, but if you want to keep a more traditional turn-based structure, one option is to update the map between each player's turn.

For example, let's say you have a lumber mill that produces 2 wood per turn, up to 10 stored. If there's five players competing for the same mill, they each get 2 wood per turn; if there's only one, he gets ten per turn (assuming five players).

There's many ways of how exactly to balance this approach, and it largely depends on what kind of game you're trying to make and what works as fun for you. Say, more players might mean more resources overall (maintaining the same yield per turn per player), or it might mean the same amount of resources (more players -\> less resources per player-turn). The max storage of a resource producer might be the same you had as per-turn production previously, or it could scale with the player count. Allowing even more resource storage while keeping the per-turn yield the same will increase the tactical options. There's endless variations you can play with :)

In either case, there's still a bonus to the first player exploits the resource when its storage is full, but it also means a great trade-off between "should I wait one more turn and hope to get 10 wood, or go in right now to get at least the 8 wood?". When you keep the resource storage scaled with player count (so that two players means 4 wood but five players means 10 wood), the one who last claimed the resources will also be the first one to get maximum yield from the producer, which makes "camping" the producer especially valuable - but anyone who claims the site will disrupt this, and both players "lose" - the original "owner" no longer has maximum yield per-turn, while the new "owner" sacrificed potential yield elsewhere.
> 2 votes

# Answer
I'll throw in how my Colonialism board game deals with this. Player order is set randomly for turn one, and I mean completely randomly: it might be player 1, 3, 2, 4, 5, or it might be 5, 1, 3, 2, 4. At the beginning of each turn (including the first), players may bid in an auction to go first. If you decide to go first, your marker on the turn order track moves to the front, and everyone else moves backward. So if the order is 1, 3, 2, 4, 5 and player 2 pays to go first, it's now 2, 1, 3, 4, 5.

An additional detail is that in the previous example, after player 4 bid to go first, player 2 might pay more than player 4 did, and then the order becomes 2, 4, 1, 3, 5. So player 4 moved forward, but still doesn't get to go first; but he did pay less for that position. This phase of the game happens in reverse turn order, giving advantage to the players who are further forward in the order.

So players only pay to go first if it is worth paying to. Historically, nobody pays to go first on turn one, because it's not an advantage yet. Eventually, the cost of the bid becomes worth the benefit, and people start doing it. My design is letting the value of the advantage determine the cost of getting it. Since order is not necessarily clockwise or counterclockwise, someone who never pays to go first will eventually be going last every turn.
> 2 votes

# Answer
I can a few possibilites :

* If it is a kind of role playing game, it might be possible to implement an attribute (let's stay **initiative**) that determines the turn order. The person who have the most initiative starts first, then the second person etc. Dofus is a game implementing this and it works pretty good.
* If every player has to be equal, then it might be a good solution to choose randomly the first turn order and then to shift by one at each global turn end. For instance player A was the third to play at Turn 1, at Turn 2 he will be second, then first, then last etc.
* Based on what you said about your game, it could be possible to make the players that have the least resources start first the turn to let them have a chance to catch up.
> 1 votes

# Answer
There are 3 approaches I know of that work well:

* One turn per player.
* All players play during the same turn. Use game design to avoid contradicting moves.
* Use a realtime approach. First to click gets the resource.
> 0 votes

# Answer
It might help you to think about how this sort of trading works in the real world.

One approach might be that players need 'agents' on the ground in reasonable proximity to the resources they want in order to be able to exploit them.

For example on your map you could have certain key locations, cities, markets, ports etc etc where players can commit counters representing their agents in order to have access to certain activities. Having an agent in a port might allow a transportation action while cities might give access to mines and factories while markets allow access to agricultural products. This system would force players to plan ahead and commit themselves before they know exactly what resources are available. It might even be possible to establish more remote trading posts on their own initiative. This is a relatively simple way to represent investment in infrastructure ie agents cost money to maintain but give more opportunities.

You could have a mixture of central trading hubs where actions are free and more remote locations where agents are needed.

Another key aspect of real world trading is bidding, if two people want the same thing one of them needs to either get to it first or be prepared to pay more for it.

You could also combine the two, having an agent in a cell gives the player the opportunity to bid for the resources in that cell, all eligible players make an offer and the highest bid by the end of the turn wins.

In this case during one turn players just take turns to take an action they have used up their available actions and order matters much less as action aren't resolved untill the end of the turn.
> 0 votes

# Answer
Try putting the environment into the turn order. That is, rather than having the entire game state update as a specific "end of turn" event, simply include it into the turn flow of the game - i.e. the environment is a "player" that takes actions such as producing resources and changing prices. The important insight here is that the environment can be split into multiple entities that each take their own turns that are interleaved with the other players, each tile and merchant taking the small actions that pertain to their responsibilities.

This could work especially well for price changes, because since not all sales points change their prices at once, resources could legitimately be worth different amounts on different parts of the board. A massive gold shortage on the east side of the board, for instance, might immediately create a price hike, but gold will still sell for cheap on the west side of the board while newsboys are taking their turns to travel there.
> 0 votes

# Answer
Lords of Waterdeep would have a similar problem with the first player to move gaining an advantage, but they solve it by allowing the players to steal the first turn as one of their limited actions in the preceding round.

A player assigns their workers to different locations in a round, one of which takes control of the token which denotes the first turn. If a player already controls that token, they can ensure they keep it by spending a worker to do so before someone steals it.

The tradeoff is that the workers are severely limited, and spending a third/quarter of your workforce every round to keep the first turn is not a viable strategy.
> 0 votes

---
Tags: game-design, balance, turn-based-strategy
---


title: Efficient Dynamic Memory Management

text:
# Question
Title: Efficient Dynamic Memory Management
My world is procedurally generated. As the player moves, chunks behind them are unloaded and chunks in front of them are loaded. Each chunk has a mesh of triangles.

At the moment, I create two VBOs for each chunk (vertices and colours), when the chunk is loaded. Once a mesh is created, it is only edited every few seconds. These buffers are deleted when the chunk is no longer visible.

Am I leaking memory here by constantly creating and destroying buffers?

I've heard somewhere that OpenGL (or WebGL in this case) doesn't do garbage collection until the program quits, due to it being slow. Is this right?

Could I improve this system somehow?

# Answer
deleteBuffer will delete the buffer in WebGL (and OpenGL) but I'm just curious, is there any reason not to just reuse the same buffer just put new data in it? (eg. have a pool of buffers?)
> 4 votes

---
Tags: opengl, webgl, vbo, memory-efficiency, memory
---


# Question
Title: How to link my weapons with their corresponding ammo supply in the Unity Inspector?
In my game I would like to implement a universal ammo and weapon system that would be usable for any kind of weapon. So I declared an ammo class:

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

[System.Serializable]
public class Ammo {

     public int MaxAmmo;
     public int CurrentAmmo;

     public Ammo(int maxAmmo)
     {
         MaxAmmo = maxAmmo;
     }

     public void MaxOutType()
     {
         CurrentAmmo = MaxAmmo;
     }

     public void GetAmmo(int amount)
     {
         CurrentAmmo += amount;
     }

     public void UseAmmo(int numOf)
     {
         CurrentAmmo -= numOf;
     }
 }

```

Then I created a script to hold different Ammo types:

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

public class AmmoSystem : MonoBehaviour
{
    [SerializeField]
    public Ammo Basic = new Ammo(200);
    public Ammo Rockets = new Ammo(50);
    public Ammo AirRockets = new Ammo(75);
    public Ammo Cells = new Ammo(150);
 }

```

To organize my project I decided to make two weapon scripts: one for nonphysical(Raycast) projectiles called `RaycastingWeapon` and an another for physical ones(like a rocket launcher) called `PhysicalProjectileWeapon`

My plan was to create unique weapons using these two scripts from the inspector.

These would use different kinds of ammo but would share the same script with different properties. The essential aspect here is that I would like to be able to select an ammo type from the inspector using a dropdown menu for example.

Is it possible somehow or are there a better way of doing that?

# Answer
> 4 votes
You probably don't actually want your weapon to hold a reference to the instance representing your ammo stock of its type. That makes it very difficult to set up a weapon prefab for a pickup/powerup, or a weapon that can be used by multiple players/NPCs. You'd have to make the weapon a part of the character using it at all times, because it needs this umbilical cord connecting it to its corresponding ammo pouch.

For a real weapon, we don't figure out which ammo it needs by following its pipe to to corresponding ammo box. Instead, the weapon has features on it like a chamber, magazine, or battery slot, that indicate what kind of supply it needs.

We can model this by having the weapon expose an ammo type that it needs, which is matched by an ammo type in our inventory / pickups / etc.

A quick & robust way to create a dropdown in Unity with a fixed set of options like this is to create an enum:

```
public enum AmmoType : int {
    Basic,
    Rockets,
    AirRockets,
    Cells
}

```

Then your weapon class can look like...

```
public class Weapon : MonoBehaviour {

    public AmmoType ammo;
    public int ammoPerShot = 1;

    // Here using dependency injection, so the weapon doesn't need to know where the
    // ammo is coming from - supplying the ammo is the job of whoever is firing it.
    public bool Fire(AmmoInventory ammo) {
       int shotsFired = ammo.Spend(ammoType, ammoPerShot);
       // Do firing effects...

       return shotsFired > 0;
    }
}

```

In the Inspector, the ammo dropdown will look like this:

Next I'll show how we can make an inventory script that automatically updates to changes in your enum if you add, remove, or rearrange ammo types. It looks like this:

We'll make sure it supports things like:

* Reporting the current amount of ammo carried of a given type
* Collecting ammo of a particular type (without exceeding a max)
* Spending ammo of a particular type (without going below zero)

```
public class AmmoInventory : MonoBehaviour {

    [System.Serializable]
    public struct AmmoEntry {
// Include name field for editing convenience only - not needed in-game.
#if UNITY_EDITOR
        [HideInInspector]
        public string name;
#endif
        public int maxCapacity;
        public int stock;
    }

    // Keep a private list of ammo stocks, so we can enforce capacity rules.
    [SerializeField]
    List<AmmoEntry> _inventory = new List<AmmoEntry>();

    // Since our enum is "really" an integer, we can use it
    // as an index to jump straight to the entry we want.
    public int GetStock(AmmoType type) {
        return _inventory[(int)type].stock;
    }

    // Returns amount collected, so you can choose to not consume
    // pickups if you're already full (ie. return value is zero).
    public int Collect(AmmoType type, int amount) {
        AmmoEntry held = _inventory[(int)type];
        int collect = Mathf.Min(amount, held.maxCapacity - held.stock);
        held.stock += collect;
        _inventory[(int)type] = held;
        return collect;
    }

    // Returns the amount actually spent, in case firing a full round
    // would drop us below 0 ammo, you can scale down the last shot.
    // You could also implement a TrySpend that aborts for insufficient ammo.
    public int Spend(AmmoType type, int amount) {
        AmmoEntry held = _inventory[(int)type];
        int spend = Mathf.Min(amount, held.stock);
        held.stock -= spend;
        _inventory[(int)type] = held;
        return spend;
    }

// Ensure our inventory list always matches the enum in the event of code changes.
// You could also use a custom editor to maintain this more efficiently.
#if UNITY_EDITOR
    void Reset() { OnValidate(); }
    void OnValidate() {
        var ammoNames = System.Enum.GetNames(typeof(AmmoType));
        var inventory = new List<AmmoEntry>(ammoNames.Length);
        for(int i = 0; i < ammoNames.Length; i++) {
            var existing = _inventory.Find(
                (entry) => { return entry.name == ammoNames[i]; });
            existing.name = ammoNames[i];
            existing.stock = Mathf.Min(existing.stock, existing.maxCapacity);
            inventory.Add(existing);
        }
        _inventory = inventory;
    }
#endif
}

```

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


# Question
Title: I'm rotating an object on two axes, so why does it keep twisting around the third axis?
I see questions come up quite often that have this underlying issue, but they're all caught up in the particulars of a given feature or tool. Here's an attempt to create a canonical answer we can refer users to when this comes up - with lots of animated examples! :)

---

Let's say we're making a first-person camera. The basic idea is it should yaw to look left & right, and pitch to look up & down. So we write a bit of code like this (using Unity as an example):

```
void Update() {
    float speed = lookSpeed * Time.deltaTime;

    // Yaw around the y axis using the player's horizontal input.
    transform.Rotate(0f, Input.GetAxis("Horizontal") * speed, 0f);

    // Pitch around the x axis using the player's vertical input.
    transform.Rotate(-Input.GetAxis("Vertical") * speed,  0f, 0f);
}

```

or maybe

```
// Construct a quaternion or a matrix representing incremental camera rotation.
Quaternion rotation = Quaternion.Euler(
                        -Input.GetAxis("Vertical") * speed,
                         Input.GetAxis("Horizontal") * speed,
                         0);

// Fold this change into the camera's current rotation.
transform.rotation *= rotation;

```

And it mostly works, but over time the view starts to get crooked. The camera seems to be turning on its roll axis (z) even though we only told it to rotate on the x and y!

This can also happen if we're trying to manipulate an object in front of the camera - say it's a globe we want to turn to look around:

The same problem - after a while the North pole starts to wander away to the left or right. We're giving input on two axes but we're getting this confusing rotation on a third. And it happens whether we apply all our rotations around the object's local axes or the world's global axes.

In many engines you'll also see this in the inspector - rotate the object in the world, and suddenly numbers change on an axis we didn't even touch!

**So, is this an engine bug?** How do we tell the program we don't want it adding extra rotation?

Does it have something to do with Euler angles? Should I use Quaternions or Rotation Matrices or Basis Vectors instead?

# Answer
> 85 votes
**No this isn't an engine bug or an artifact** of a particular rotation representation (those can happen too, but this effect applies to every system that represents rotations, quaternions included).

You've discovered a real fact about how rotation works in three-dimensional space, and it departs from our intuition about other transformations like translation:

When we compose rotations on more than one axis, the result we get isn't just the total/net value we applied to each axis (as we might expect for translation). The order in which we apply the rotations changes the result, as each rotation moves the axes on which the next rotations get applied (if rotating about the object's local axes), or the relationship between the object and the axis (if rotating about the world's axes).

The changing of axis relationships over time can confuse our intuition about what each axis is "supposed" to do. In particular, certain combinations of yaw and pitch rotations give the same result as a roll rotation!

You can verify that each step is rotating correctly about the axis we requested - there's no engine glitch or artifact in our notation interfering with or second-guessing our input - the spherical (or hyperspherical / quaternion) nature of rotation just means our transformations "wrap around" onto each other. They may be orthogonal locally, for small rotations, but as they pile up we find they're not globally orthogonal.

This is most dramatic and clear for 90-degree turns like those above, but the wandering axes creep in over many small rotations too, as demonstrated in the question.

## So, what do we do about it?

If you already have a pitch-yaw rotation system, one of the quickest ways to eliminate unwanted roll is to change one of the rotations to operate on the global or parent transformation axes instead of the object's local axes. That way you can't get cross-contamination between the two - one axis remains absolutely controlled.

Here's the same sequence of pitch-yaw-pitch that became a roll in the example above, but now we apply our yaw around the global Y axis instead of the object's

So we can fix the first-person camera with the mantra "Pitch Locally, Yaw Globally":

```
void Update() {
    float speed = lookSpeed * Time.deltaTime;

    transform.Rotate(0f, Input.GetAxis("Horizontal") * speed, 0f, Space.World);
    transform.Rotate(-Input.GetAxis("Vertical") * speed,  0f, 0f, Space.Self);
}

```

If you're compounding your rotations using multiplication, you'd flip the left/right order of one of the multiplications to get the same effect:

```
// Yaw happens "over" the current rotation, in global coordinates.
Quaternion yaw = Quaternion.Euler(0f, Input.GetAxis("Horizontal") * speed, 0f);
transform.rotation =  yaw * transform.rotation; // yaw on the left.

// Pitch happens "under" the current rotation, in local coordinates.
Quaternion pitch = Quaternion.Euler(-Input.GetAxis("Vertical") * speed, 0f, 0f);
transform.rotation = transform.rotation * pitch; // pitch on the right.

```

(The specific order will depend on the multiplication conventions in your environment, but left = more global / right = more local is a common choice)

This is equivalent to storing up the net total yaw and total pitch you want as float variables, then always applying the net result all at once, constructing a single new orientation quaternion or matrix from these angles alone (provided you keep `totalPitch` clamped):

```
// Construct a new orientation quaternion or matrix from Euler/Tait-Bryan angles.
var newRotation = Quaternion.Euler(totalPitch, totalYaw, 0f);
// Apply it to our object.
transform.rotation = newRotation;

```

or equivalently...

```
// Form a view vector using total pitch & yaw as spherical coordinates.
Vector3 forward = new Vector3(
                    Mathf.cos(totalPitch) * Mathf.sin(totalYaw),
                    Mathf.sin(totalPitch),
                    Mathf.cos(totalPitch) * Mathf.cos(totalYaw));

// Construct an orientation or view matrix pointing in that direction.
var newRotation = Quaternion.LookRotation(forward, new Vector3(0, 1, 0));
// Apply it to our object.
transform.rotation = newRotation;

```

Using this global/local split, the rotations don't have a chance to compound and influence each other, because they're applied to independent sets of axes.

The same idea can help if it's an object in the world that we want to rotate. For an example like the globe, we'd often want to invert it and apply our yaw locally (so it always spins around its poles) and pitch globally (so it tips toward/away from our view, rather than toward/away from Australia, wherever it's pointing...)

## Limitations

This global/local hybrid strategy isn't always the right fix. For example, in a game with 3D flight/swimming, you might want to be able to point straight up / straight down and still have full control. But with this setup you'll hit gimbal lock \- your yaw axis (global up) becomes parallel to your roll axis (local forward), and you have no way to look left or right without twisting.

What you can do instead in cases like this is to use pure local rotations like we started with in the question above (so your controls feel the same no matter where you're looking), which will initially let some roll creep in - but then we correct for it.

For example, we can use local rotations to update our "forward" vector, then use that forward vector together with a reference "up" vector to construct our final orientation. (Using, for example, Unity's Quaternion.LookRotation method, or manually constructing an orthonormal matrix from these vectors) By controlling the up vector, we control the roll or twist.

For the flight/swimming example, you'll want to apply these corrections gradually over time. If it's too abrupt, the view can lurch in a distracting way. Instead, you can use the player's current up vector and hint it toward the vertical, frame-by-frame, until their view levels out. Applying this during a turn can sometimes be less nauseating than twisting the camera while the player's controls are idle.

# Answer
> 2 votes
AFTER 16 hours of parenting and rotation functions lol.

I just wanted to have code have an empty, basically, turning in circles and also front flipping as it turns.

Or in other words, the goal is to rotate yaw and pitch without any effect on roll.

**Here are the few that actually worked in my application**

In Unity:

1. Create an empty. Call it ForYaw.
2. Give that a child empty, called ForPitch.
3. Finally, make a cube and move it to z= 5 (forward). Now we can see what we are trying to avoid, which will be twisting the cube *(accidental "roll" while we yaw and pitch)*.

Now scripting in Visual Studio, do your setup, and end up with this in Update:

```
objectForYaw.Rotate(objectForYaw.up, 1f, Space.World);
    objectForPitch.Rotate(objectForPitch.right, 3f, Space.World);

    //this will work on the pitch object as well
    //objectForPitch.RotateAround
    //    (objectForPitch.position, objectForPitch.right, 3f);

```

Note that it all broke for me when I tried to vary the order of parenting. Or if I change Space.World for the *child pitch* object (the parent Yaw doesn't mind being rotated through Space.Self). Confusing. I could definitely use some clarification on why I had to take a local axis but apply it through world space — why does Space.Self ruin everything?

---
Tags: rotation, geometry, transformation
---


# Question
Title: Voxel tutorial NullReferenceException: Object Reference not set to an instance of an object
I'm working my way through this voxel tutorial in Unity. I'm on part 3, and it's showing me how to create a chunk within the world.

I've copied the code, but I think I am missing something. The error that shows up is:

`NullReferenceException: Object reference not set to an instance of an object
Chunk.UpdateChunk () (at Assets/scripts/Chunk.cs:76)
Chunk.Update () (at Assets/scripts/Chunk.cs:34)`

The offending code is at this line:

```
meshData = blocks[x, y, z].Blockdata(this, x, y, z, meshData);

```

Chunk.cs

```
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(MeshCollider))]

public class Chunk : MonoBehaviour
{

    private Block[,,] blocks = new Block[chunkSize, chunkSize, chunkSize];

    public static int chunkSize = 16;
    public bool update = true;

    MeshFilter filter;
    MeshCollider coll;

    public World world;
    public WorldPos pos;

    void Start()
    {
        filter = gameObject.GetComponent<MeshFilter>();
        coll = gameObject.GetComponent<MeshCollider>();
    }

    //Update is called once per frame
    void Update()
    {
        if (update)
        {
            update = false;
            UpdateChunk();
        }
    }

    public Block GetBlock(int x, int y, int z)
    {
        if (InRange(x) && InRange(y) && InRange(z))
            return blocks[x, y, z];
        return world.GetBlock(pos.x + x, pos.y + y, pos.z + z);
    }

    public static bool InRange(int index)
    {
        if (index < 0 || index >= chunkSize)
            return false;

        return true;
    }

    public void SetBlock(int x, int y, int z, Block block)
    {
        if (InRange(x) && InRange(y) && InRange(z))
        {
            blocks[x, y, z] = block;
        }
        else
        {
            world.SetBlock(pos.x + x, pos.y + y, pos.z + z, block);
        }
    }

    // Updates the chunk based on its contents
    void UpdateChunk()
    {
        MeshData meshData = new MeshData();

        for (int x = 0; x < chunkSize; x++)
        {
            for (int y = 0; y < chunkSize; y++)
            {
                for (int z = 0; z < chunkSize; z++)
                {
                    // **NullReferenceException occurs on this line:**
                    meshData = blocks[x, y, z].Blockdata(this, x, y, z, meshData);
                }
            }
        }

        RenderMesh(meshData);
    }

    // Sends the calculated mesh information
    // to the mesh and collision components
    void RenderMesh(MeshData meshData)
    {
        filter.mesh.Clear();
        filter.mesh.vertices = meshData.vertices.ToArray();
        filter.mesh.triangles = meshData.triangles.ToArray();

        filter.mesh.uv = meshData.uv.ToArray();
        filter.mesh.RecalculateNormals();

        coll.sharedMesh = null;
        Mesh mesh = new Mesh();
        mesh.vertices = meshData.colVertices.ToArray();
        mesh.triangles = meshData.colTriangles.ToArray();
        mesh.RecalculateNormals();

        coll.sharedMesh = mesh;
    }

}

```

However, I think it's maybe not the code that's the problem. Rather, I am missing a step. There is a section of the tutorial that says:

> Let's start with a function to create new chunks, since chunks are game objects we'll need to use the instantiate method with a prefab to create the chunks so create a variable chunkPrefab:
>
> ```
>  public GameObject chunkPrefab;
>
> ```
>
> And also create a prefab of a chunk. Use the chunk object we've been using or create a new one. It just needs to be a game object with the material applied and chunk script which automatically includes the mesh renderer, mesh filter and mesh collide . By the way make sure your mesh collider has convex set to false or your colliders wont work. Make a prefab of it by dragging it from the hierarchy to the project view. Then delete it from the scene and make a new object with the world script on it and set the chunkPrefab variable to the one we just made.

How do I create a `prefab of a chunk`? Do I go to:

**Assets**-\>**Create**-\>**Prefab**

and then assign my `chunk.cs` script to it? Or do I assign my current gameobject to it (which has chunk.cs and the tileset material attached)? Or am I misreading this entirely?

Here is what my scene looks like so far:

Pictures would really help!

# Answer
Click your chunk gameobject and drag it down in your assets directory. You now have a prefab of your chunk object. Drag this prefab into the world script or where it is needed. Delete your chunk gameobject from the hierarchy. That should be it... good luck, this is a good tutorial.
> 1 votes

# Answer
You must make a chunk prefab, remove it from your scene hierarchy, and add a new game object to the scene with the *World.cs* script attached and with the chunk prefab as the value of the world script's variable.
> 0 votes

---
Tags: unity, voxels
---


title: FBO picking in Oculus Rift applications

text:
# Question
Title: FBO picking in Oculus Rift applications
I am writing an Oculus Rift application, I am rendering a very high poly mesh that I wish to be able to perform picking on using the Oculus Touch. Ideally, I want to be able to get the "triangle" id and other information attached to it.

Currently, I am using an OBB Tree and ray casting to perform picking on the CPU, It works **perfectly**, the problem is that even with OBB tree the picking process is slow. I thought I'd perform picking on the GPU by rendering the view (from the point of view of the Oculus Touch) to an FBO using a custom shader that outputs "triangle information" to the buffer and then use `glReadPixels` to read the central pixel data. The problem I am facing is that the Oculus does distortion to my on-screen scene but there is no way to apply it to the off-screen buffer, so there is significant difference between the on-screen buffer and the off-screen buffer.

My question is, Is ray casting the only feasible way to do picking in Oculus Apps or is there a way to perform the faster FBO picking even when the view distorted?

# Answer
> 0 votes
Okay, I found a way to solve this problem. It is less than idle but it reduces the amount of processing done on the CPU by a lot.

My problem is that I cannot just pick the middle pixel from the FBO to get my picked items. So I went for an educated brute-force approach.

I tell my picking shader to `discard` all non-hits (pixels that are outside my Oculus touch pointer) and instead of picking the middle point of the FBO I would just search the whole FBO for hits and if intelligently pick the region to look I can get away with a lot less than doing an Octree search.

The following image show my "solution". On the left is what is rendered to the Oculus, and on the right is the view from the point of view of the right hand touch controller.

---
Tags: opengl, picking, oculus
---


title: LibGdx input data REQUIRED

text:
# Question
Title: LibGdx input data REQUIRED
I am using the code below to ask users for their username.

```
MyTextInputListener listenerz = new MyTextInputListener();
Gdx.input.getTextInput(listenerz, "Create Username", "");

```

I have knowledge in PHP but beginner in Java LibGdx. I know that in HTML there is a **REQUIRED**

```
<input name='username' required />

```

That's why I wanted to know the equivalent coding in LibGdx for the **REQUIRED** input.

# Answer
> 2 votes
If you want to check if the user entered a valid input you could do something like this:

```
if(input == null || input.length() < minLength) {
    //Invalid input. Do something.
    //You might just ask the user for input again until it is valid.
    MyTextInputListener listenerz = new MyTextInputListener();
    Gdx.input.getTextInput(listenerz, "Create Username", "");
}

```

You should also add that code in the canceled() method of the listener:

```
@Override
public void canceled () {
    MyTextInputListener listenerz = new MyTextInputListener();
    Gdx.input.getTextInput(listenerz, "Create Username", "");
}

```

This way the input window will just repeat itself if invalid input is given.

---
Tags: libgdx
---


title: Games Dev Work Experience for Teenager

text:
# Question
Title: Games Dev Work Experience for Teenager
I have a teenage son that wants to work in games development and design when he is older. We've been to several conferences that explain the importance of experience when looking for a job. Also being a IT developer myself that often interviews new hires, I know how critical experience is. So we've been looking to try and find him some work at Games Dev companies in London for several weeks over the Summer holidays but haven't got anywhere.

My son is very smart and is expected to get 8+ GCSEs of a high grade (7+ or A/Bs in old marks), he plans go on to get A levels and then study Computer Science at University. He has some programming experience in Python. All he wants is some work experience, if he ends up just running errands and making coffee that would be fine as long as he also gets involved in some way with the games development process. He also doesn't really expect to get paid (although that would be a bonus).

I've approached several companies with details and a CV but haven't had a single response back from them. This seems strange to me as apart from a little of their time these companies don't seem to have anything to lose here.

So my question is, is there something stopping games companies hiring teens in this kind of situation? Any other pertinent advice would be welcome.

# Answer
> 29 votes
You've hit on a real problem in the games industry. We don't know how to judge game-making expertise. Training someone up to be productive on a new game project can take weeks on its own, so we're very skittish about making that investment. Our best guess is to look at games someone has already made, which leads to a catch-22 situation where you need to be hired to work on a game so you can have your name on a shipped game so you can get hired.

Going through the job postings for my studio for example, nearly all of them ask for 5 years of prior game experience and multiple shipped titles, and there's a lot of competition for the few student/new-grad level positions. This is especially prevalent at the big AAA companies. A lot of us were able to get our start because a smaller indie studio took a chance on us (or we took a chance starting our own indie studio).

Just to add to these troubles, of the studios that do hire students/grads/interns frequently, some have a reputation for churn - treating these beginners as cheap replaceable labour to work till they burn out, knowing there are always more out there to take their place. So make sure you read up on the work culture at any studio to which you apply.

There is a way to break this catch-22 though, and it might be perfect for the summer experience you describe. It just requires broadening the definition a little from "work experience" to "game development experience"

We do these things called **Game Jams**, which are a bit like a hackathon or charette: a group of game creators get together and decide to build a new game from scratch in a very short amount of time - often a week, a weekend, or even just one day. They're usually free or very cheap to participate in, and don't require any CV review to get in.

I'd particularly recommend jams that happen at physical locations like schools or coworking spaces, since they give you the opportunity to mingle with fellow creators, get inspired, ask for help, offer to help, and generally just ride the energy of all these people getting together to create.

There's also a continuous stream of online-only jams - itch.io catalogues many of these in a handy timeline format. If you can't find a suitable jam near you or starting on the timeline you want, you can always grab some friends and start your own. :)

Most jams will have a theme or challenge of some kind to spark your creativity, others will have constraints like using specific platforms / tools / genres. Most in my experience aren't a judged competition - they usually end with an arcade or showcase where everyone gets to play all the weird little games the participants came up with.

You can join a jam as a team of friends, or as an individual if you want to do it all solo. Some of the bigger jams also provide matchmaking services to help you assemble a team, or "floater" roles where artists/sound designers without a team get paired up with teams that lack artists/sound designers.

I recommend jams because they reproduce a microcosm of game development - all the same pressures and joys and frustrations, team dynamics and scope challenges (and oh gosh the bugs!) condensed into a low-risk opportunity. If a jam goes badly, ehn, I lost a weekend at worst - I didn't have to live through a studio I founded going bankrupt. ;)

And the games that get created aren't just throw-away. With a bit of dedication and polish they can become great portfolio pieces to bring to a prospective employer to prove you have game-making skills. Here in Ontario, we've had a number of success stories of creators taking experimental game jam prototypes and continuing to build them up into finished games you can buy on Steam/Xbox/Playstation/etc, including Runbow, Keep Talking and Nobody Explodes, Toto Temple, Mount Your Friends, Super Time Force, Lovers in a Dangerous Spacetime, The Yawhg. (I have no affiliation with any of these games, I just think they and their creators are pretty awesome)

So yeah, all that to say: game jams can be a fun and accessible way to build up gamedev experience, sidestepping industry gatekeepers, and I highly recommend them even for experienced game developers as a way to periodically stoke your passion for making games. Feel free to hit me up on Twitter if you want more information about jams. :)

# Answer
> 4 votes
Just an addition to the other answers (because I can't comment): I agree that working on a game at home first is a better way to get started than trying to get experience at a company rigt away. He can start making is own small games to get used to the development, and get to know some of the components a game usually has. Another step I suggest as soon as he has enough experience is contributing to some game. It is not in Python, but as an example the game Terasology is a Minecraft-like project where everyone can contribute code, assets, anything on GitHub. Through things like that he'll also learn to use important collaborating tools like Git(maybe even advanced stuff like CI), learn about code style, and generally how a workflow can go (as GitLab puts it, "From idea to production"). Staying at the example if Terasology, they also take part in Google's Summer of Code (GSOC), another thing he could participate in (probably a little later) to learn more about Coding and Game Design.

When he has already made a few smaller games and maybe even participated in one that is a little larger, it might be a better idea to come back at some companys. Then they'll know he can actually understand what is going on, and they are not wasting resources on someone who might just get bored of coding some months later.

# Answer
> 4 votes
As a current college student (2nd year) that is currently on paid co-op with a studio, my biggest piece of advice would be personal projects. Start playing with C# and Unity and constantly be messing around and doing quick prototypes of ideas that you have. All. The. Time.

A great way to build up real game dev experience is with game jams. They are fantastic ways to learn, experiment, and meat new people. If you want more info on some public game jams, check out Itch.

If you want to learn more directly and want some structure, then Udemy has *amazing* game dev courses. Great support and community, and they are on sale all the time. I just got a 54 hour long Unreal Engine course for $15. Totally worth the investment.

Lastly, have your son do the work. Companies don't want to hire someone whose parents reach out to them. You need to let him get out there and learn for himself, otherwise he will not learn.

# Answer
> 4 votes
**Companies do have something to lose: time**

I have worked for companies that have accepted work experience students, although as part of formal work experience during schooltime rather than *ad hoc*. These students are not able to usefully contribute to the game development process but rather take up considerable amounts of time from developers who could otherwise be doing useful work. Time is required to plan things for them to do, show them how to do said things, and supervise them whilst they work. Further, as they are children, there are insurance and oversight considerations not present with normal staff.

Even a smart child, such as your son, cannot be expected to turn up and produce worthwhile work in a few weeks. Even when we took project students from the local university who were considerably older and taking a specific game development course it was rarely the case that they'd produce worthwhile work within the first few *months*. Some never managed it at all, or produced little enough good work that their cost in terms of other people's time was not covered.

So, in fact, taking students on for work experience or projects is frequently not beneficial to the companies involved. Instead it is offered out of a sense of community and duty to wider society. This role is less well achieved by taking on a random child interested in game development than it is by participating in formal programmes of work experience.

# Answer
> 3 votes
DMGregory is right. Finding job as a game developer is not just the same as throwing a CV at some engineering company. Basically because Software is something quite new, and a low percentage of the youth knows how to do it, and a tinier percentage does it well. I never went to any jam, but if your son has time, I'd strongly recommend him to create games himself and publish them. They don't have to be hard, they can be simple 2D games. Even simpler than a platformer. Look at "Pop the Lock" in Play Store. It's so simple and it got up to 5 million downloads. Besides, he could end up not wanting to be employed by anyone but to have his own company of game development, which he doesn't need money for, since he could get it by his own if he has success. The Android Play Store is a good start. Many frameworks have very good support, be it native like Android Studio, or Unity.

# Answer
> 2 votes
There are many good answers so far, but I wish to emphasise one point in particular.
To be blunt: You want to be a games designer? You mean programmer.

A lot of games come out of small teams or from lone developers. In this case each person has multiple roles. Unless you get to large corporations there's simply no way a dedicated games designer can be justified (or is even relevant), and even then I wouldn't trust someone who claimed to love games design and yet never made their own games. In big studios a lot of the senior staff who happen to be designers are usually industry veterans who have an awareness of everything required to bring a design into reality. There's little if any space for juniors in this field.

Being able to demonstrate technical competence and initiative; to bring a polished product from concept to market, is the most relevant thing you can do for a future career in games or IT. Forget about internship, you want to be able to evidence your ability, dedication, and talent. The only way to do this for games is by programming. People will notice your CV if you can mention such achievements.

Games, broken down to their most fundamental element, are about play. Narrative, sound, art; strip those away and you're left with the mechanics, and the only person who can make them happen is a programmer.

The good news is that these days it has never been easier for anyone, regardless of age, to learn programming, download a quality game engine, and just start implementing their ideas. Computer Science is an excellent start, and there's no reason you'd have to wait for university to teach yourself the basics. Acquire a copy of Bjarne Stroustrup's "Programming Principles and Practice using C++" (written by the man who invented C++ for his first year university students). I only got through the first 100 pages, but that was enough theory to get started in Unity with C#. And there's plenty of online communities, forums, wikis, to help with all manner of questions a novice might have. Google it, 9/10 times you'll find a solution on StackOverflow or a specialist forum. It's never been easier to go it alone.

Additionally, companies may be unwilling to look for interns partly because a lot of what they do is secretive. Employees usually sign a Non Disclosure Agreement, and an intern is something more of a liability than a salaried employee.

# Answer
> 1 votes
> **We've** been to several conferences \[...\] **we've** been looking to try and find him some work \[...\] **I've** approached several companies

Do *you* want a job or does *your son* want a job?

Stop being a helicopter mom. If your son wants a job, he needs to apply himself. Nobody will take him seriously if his mother is constantly behind him.

Besides that, I can reiterate the advise given by the other answers. Game development studios get swamped with application from teen gamers who think they have what it takes to become game designers because they have "the idea for the greatest game ever" but have absolutely no relevant skills. Those go to the trash can immediately. The best way to prove that you are a game developer is creating a game on your own. It doesn't need to be commercially successful. Some small freeware game is enough.

# Answer
> 1 votes
If the goal is experience, then your son could contribute to an open source project. There are lots of open source games that would welcome contribution. Even if not contributing code to the official game repository, many games have an open API to develop your own mod/plugin. See for example https://endless-sky.github.io/, a great place to start would be to have him build a plugin

# Answer
> 0 votes
Everybody apreciates your effort and good intentions, but let your son break the egg shell and fly. A mom approaching several companies for a job for her son beacuse "he is very smart" it is not serious.

The companies have their own ways to contract people. You have to fit them. Don't think they have to hire a teenager with 0 knowledge just because he lowers himself to work for free and his mom says he is very smart.

He is a teenager, looking tutorials and developing his own games it's a good start.

---
Tags: career
---


# Question
Title: What algorithm can I use to distribute energy between connected nodes?
I'm creating a game where every user has a network of connected nodes that each have a specific amount of energy. The nodes will try to distribute energy evenly amongst themselves. If a node has more energy than the average, it should deliver to the network. If a node has less than the average, it should receive from the network. An example network would be this, where + means more than average and - means less than average:

Now the one question I've been trying to solve for a while now: how can I calculate the cumulative amount of energy that flows through every edge until all nodes have the same amount of energy? For example we know that the node in the top left will in the end distribute 7 energy to the network, but will it give 5 down and 2 to the right? Or something else?

Is there any algorithm we could use to solve that problem? Could we potentially represent this problem as an electric circuit and solve it like that?

# Answer
> 5 votes
There are many ways we could choose which paths the energy will take, so here are a couple of starting points we could try.

## 1. Spanning Tree

This approach is inspired by dielectric breakdown, the phenomenon where a large potential difference across an insulator will drill a branching tree of conductive channels through it - lightning is the most familiar example.

We start by giving each edge a score based on the energy difference between its endpoints - we can consider this a measure of how "ionized" this edge is, and how eagerly energy will flow along it.

Next we run a minimum spanning tree algorithm on our graph, using the negative absolute value of this ionization score as our edge weight. Prim's algorithm or Kruskal's will both do great. This gives us a subset of our edges forming a tree that touches every node, which will become our energy distribution network.

Now you can pick a root of the tree arbitrarily, and work through the edges starting from the leaf nodes. Total-up the deviation from the average energy value in each subtree. The amount flowing down (leafward) along the subtree's incoming edge must be the negative of this value.

> eg. if I have a leaf node with -1 energy difference from the average, then 1 unit of energy must flow down the edge leading to it.
>
> If its parent has +2 deviation and a second child node with +1 deviation, then the parent's incoming edge must carry 2 energy back toward the root: -1 * (-1 + 2 + 1) = -2

## 2. System of Equations

Treating the amount of energy carried along each (oriented) edge as a variable, we can construct a system of linear equations, with one equation per node:

```
  [Node's deviation from average]
+ [sum of incoming edge variables]
- [sum of outgoing edge variables]
= 0

```

Here's how that system of equations might look for the example graph:

This system will usually be under-determined, since you'll have more edges (variables) than nodes (equations/constraints), meaning you'll have multiple solutions to choose from - unless of course your graph is a tree, in which case we can use the rule above to find the single unique solution.

The nice thing about this approach is it makes the problem pretty generic - something you can chuck at a general linear system solver library (or integer programming solver, if you want to enforce a constraint that each edge carry a whole number of charges).

By playing with the solver objective function, you can search the solution space for options that spread the load as evenly as possible over all paths, as opposed to the spanning tree approach which necessarily concentrates the flow along a minimal transport network.

# Answer
> 0 votes
It looks like I cannot determine the exact solution directly. What I created in the end is an iterative algorithm that *approximates* a natural distribution.

Code can be found here:

---

Roughly it runs like this:

## Step 1

For the whole set of nodes, find all the disconnected subgraphs, i.e. find all separate networks.

## Step 2

For every separate network, calculate the average energy position. In the example that average energy position is 0. Then calculate what every node should be delivering to the network or receiving from the network. Those are the +7, -2 etc that we see in the example image.

## Step 3

We prepare a list of nodes that we want to process. This list initially contains all the nodes that want to distribute any energy to the network.

Then, the algorithm runs for a specific number of rounds. Every round

1. It will loop over the prepared list and distribute any 'surplus' energy to the connected nodes. These connected nodes store the incoming energy into an 'incoming energy' bucket just for now.
2. The algorithm loops over all nodes and adds all incoming energy for that node together and sets that as the surplus energy to distribute next round.

So after e.g. 50 rounds, the energy from a specific node has hopped over 50 nodes and distributed itself to quite a big network.

To keep things efficient, I use a few tricks

1. If there is less than 1 energy to distribute for a node, it will remove itself from the list of nodes that we want to process. This because we don't want to distribute ever smaller amounts of energy around the network. A node will be added back to the list again if any incoming energy for that node moves it surplus energy \> 1.
2. If a node has only 1 connected node, then we know exactly how much energy will transfer between them. For example node A has +3 and connects only to node B. Then we know that A will transfer all that energy to node B, no matter what. So we confirm that energy distribution between those nodes and remove node A from the list to be processed. Even better, if that one connection becomes confirmed, that might mean that node B might be left with only one connection to a node C, which can then be confirmed as well, etc.
3. If the list of nodes to be processed is 0, then obviously break.

The algorithm seems fast enough right now (1-2 ms for a few not-so-complicated networks).

Any suggestions much appreciated!

Again, full code can be found here: https://github.com/willemmulder/Energia/blob/master/static/js/core.js

---
Tags: algorithm, graph
---


# Question
Title: How do I make bullets in a list intersect with bullets from another list, when both lists are not in the same class?
I have the initial "Game1" class, with a "Ship" class initiated inside, and within the "Ship" class there's a List, where the "Bullet" class is used.

How can I make a bullet in a list from one of the ship classes intersect with a bullet from the other ship's bullet list?

Do I have to make a list of Rectangles too for their hitboxes?

# Answer
> 1 votes
Generally it's wise to create an object manager if your game is using collisions. The object manager will contain a list of all of your game objects, then check collision between all of them in one go, usually with a function that they all derive from a common parent class. If the objects collide, they then call another function for handling their collision. You can pass in the object it collided with if it has a specific reaction depending on what it collided with.

---
Tags: c#, xna, monogame
---


# Question
Title: How do I make so the player jump happens only once in a onScreenController on LIBGDX and the player doesn't stick on the roof?
I'm making a simple platform game, and I was following this tutorial to make an onScreenController (https://www.youtube.com/watch?v=z4Vqkp\_ve3I&t=66s). There's one think that's not how I want it to be, whenever I jump and I keep the jump button pressed the player keeps "glued" to where it hits, it wasn't happening when I was using the handleInput of the console, back then I used the "Gdx.input.isKeyJustPressed(Input.Keys.UP)" and it was working as intended, the player jumped and falled. But now, with this new onScreenController it doesn't. How do I make so the player must press up again so it jumps again and the player doesn't stick on the "roof"?.

The controller class:

```
package com.jeancarlous.codewizard.Scenes;

 import com.badlogic.gdx.Gdx;
 import com.badlogic.gdx.Input;
 import com.badlogic.gdx.graphics.OrthographicCamera;
 import com.badlogic.gdx.graphics.Texture;
 import com.badlogic.gdx.scenes.scene2d.InputEvent;
 import com.badlogic.gdx.scenes.scene2d.InputListener;
 import com.badlogic.gdx.scenes.scene2d.Stage;
 import com.badlogic.gdx.scenes.scene2d.ui.Image;
 import com.badlogic.gdx.scenes.scene2d.ui.Table;
 import com.badlogic.gdx.utils.Disposable;
 import com.badlogic.gdx.utils.viewport.FitViewport;
 import com.badlogic.gdx.utils.viewport.Viewport;
 import com.jeancarlous.codewizard.CodeWizard;

/**
 * Created by Jean on 09/06/2017.
 */

public class Controle implements Disposable{

Viewport viewport;
Stage stage;
boolean upPressed, leftPressed, rightPressed;
OrthographicCamera cam;
boolean x=false;

public Controle(){
    cam = new OrthographicCamera();
    viewport = new FitViewport(800, 480, cam);
    stage = new Stage(viewport, CodeWizard.batch);

    stage.addListener(new InputListener(){

        @Override
        public boolean keyDown(InputEvent event, int keycode){
            switch (keycode){
                case Input.Keys.UP:
                    upPressed = true;
                    break;
                case Input.Keys.LEFT:
                    leftPressed = true;
                    break;
                case Input.Keys.RIGHT:
                    rightPressed = true;
                    break;
            }
            return true;
        }
        @Override
        public boolean keyUp(InputEvent event, int keycode){
            switch (keycode){
                case Input.Keys.UP:
                    upPressed = false;
                    break;
                case Input.Keys.LEFT:
                    leftPressed = false;
                    break;
                case Input.Keys.RIGHT:
                    rightPressed = false;
                    break;
            }
            return true;
        }

    });

    Gdx.input.setInputProcessor(stage);

    Table table = new Table();
    table.left().bottom();

    Image upImg = new Image(new Texture("Controle/cima.png"));
    upImg.setSize(100, 100);
    upImg.addListener(new InputListener(){

        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            upPressed = true;
            return true;
        }
        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            upPressed = false;
        }
    });

    Image rightImg = new Image(new Texture("Controle/direita.png"));
    rightImg.setSize(100, 100);
    rightImg.addListener(new InputListener(){

        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            rightPressed = true;
            return true;
        }
        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            rightPressed = false;
        }
    });

    Image leftImg = new Image(new Texture("Controle/esquerda.png"));
    leftImg.setSize(100, 100);
    leftImg.addListener(new InputListener(){

        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            leftPressed = true;
            return true;
        }
        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            leftPressed = false;
        }
    });

    table.add();
    table.add(upImg).size(upImg.getWidth(), upImg.getHeight());
    table.add();
    table.row().pad(10,10,10,10);
    table.add(leftImg).size(leftImg.getWidth(), leftImg.getHeight());
    table.add();
    table.add(rightImg).size(rightImg.getWidth(), rightImg.getHeight());
    table.row().padBottom(10);

    stage.addActor(table);

}

public void draw(){
    stage.draw();
}

public boolean isUpPressed() {
    return upPressed;
}

public boolean isLeftPressed() {
    return leftPressed;
}

public boolean isRightPressed() {
    return rightPressed;
}

public void resize(int width, int height){
    viewport.update(width, height);
}

@Override
public void dispose() {

}
}

```

How I'm handlingInput with the controller.

```
 public void handleInput(float dt) {
  if (player.currentState != TheWizard.State.DEAD && player.currentState != TheWizard.State.ACERTOU) {
      if (controle.isUpPressed() && player.b2body.getLinearVelocity().y == 0) {
          player.b2body.applyLinearImpulse(new Vector2(0, 4f), player.b2body.getWorldCenter(), true);
      } else if (controle.isRightPressed() && player.b2body.getLinearVelocity().x <= 2) {
          player.b2body.applyLinearImpulse(new Vector2(0.1f, 0), player.b2body.getWorldCenter(), true);
      } else if (controle.isLeftPressed() && player.b2body.getLinearVelocity().x >= -2) {
          player.b2body.applyLinearImpulse(new Vector2(-0.1f, 0), player.b2body.getWorldCenter(), true);
      } else {
          player.b2body.setLinearVelocity(new Vector2(player.b2body.getLinearVelocity().x, player.b2body.getLinearVelocity().y));
      }
  }

```

# Answer
> 0 votes
I managed to solve it.

My character body was two circles (one above the other), in the worldContactListener class I made it so a variable is set true or false whenever the "head" hits something, and I made it so the condition to jump is something like: "if (controle.isUpPressed() && player.b2body.getLinearVelocity().y == 0 && CodeWizard.CONTATO == true)". In other words, I used a GLOBAL BOOLEAN VAR CONTATO, if the head hits something the VAR value changes to false. I also fixed a problem when both circles was in contact with something, that would make the value of VAR to false, if I press "UP" in the Controller class the value is set to true, it doesn't bug cause it only changes to false when it hits something. This way it doesn't stop it from jumping.

---
Tags: java, android, libgdx, mobile, android-studio
---


# Question
Title: Gameobject with Canvas child (Unwanted inspector behavior)
When I try to focus (by double clicking or pressing f) on gameobjects in my scene which have a Canvas as a child, the scene view zooms out to show the Canvas. I would like to be able to see the gameobjects themselves when focusing on them. Is there a way to do this?

# Answer
> 1 votes
If the canvas is a screen space or camera overlay UI, un-child them from the parent object entirely or create a new parent and place the old parent and canvas as siblings under the new parent.

If it's a world space UI, you likely don't have much choice (unless the moving it to a common parent works for your situation), because you probably need it where it is to inherit the parent's transform. But in that instance the UI should likely be smaller than a screen space UI, so make sure you have it scaled appropriately for your scene.

---
Tags: unity
---


# Question
Title: Unity 5.6 - Can no longer select empty GameObject with Gizmo in editor
Has anyone else noticed this? I'm using the latest version of Unity (5.6.0p2) and it appears Gizmos are no longer selectable by default.

Is there any way to restore this behaviour?

Some of my objects are essentially empty (no meshrenderer/Filter) with a MonoBehavior attached, which require a gizmo drawn sphere so it can be selected.

Is there a better/more appropriate way of making non-mesh gameobjects selectable in the editor that I'm not aware of?

I understand I could use Handles to detect a mouse click but this doesn't allow for simple drag selection (marquee tool) if I want to select a load at once.

# Answer
Judging by the comment thread above, it appears that the problem was that the user had unintentionally left one of their layers locked.

You can use the Layers drop-down menu in the Unity Editor toolbar to configure which object layers should be selectable.
> 1 votes

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


# Question
Title: Is it acceptable to use Hash Maps for input, copying one hash map to an another during the game loop?
I recently started developing a simple 2D game in Java using JavaFX and no proper game library (libgdx etc.) and among the things I did was to make an InputManager to handle every input from the player.

In the InputManager I'm using a Hash Map, called `inputMap`, using a String as the key and a Boolean as the value. When the player presses a movement key, e.g. the UP arrow key, InputManager sets the value of the "UP" key of the map to "true". The game loop which also has a Hash Map, copies the map from the InputManager (via a getInputMap() method) to it's own map every frame and then using if statements the player moves.

My questions is, is this an acceptable way of doing this? The movement and every action in general.

Is there a better way of doing it without the use of Hash Maps or if Hash Maps are the way to go is there a better, more appropriate, way to implement them?

Below is the InputManager class:

```
class InputManager {

    private Scene scene;
    private Map<String, Boolean> inputMap = new HashMap<String, Boolean>();

    InputManager(Scene scene) {
        this.scene = scene;
        populateInputMap();
        getInput();
    }

    private void populateInputMap() {
        inputMap.put("UP", false);
        inputMap.put("DOWN", false);
        inputMap.put("LEFT", false);
        inputMap.put("RIGHT", false);
        inputMap.put("RESTART", false);
    }

    private void getInput() {

        scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {

                if (event.getCode() == KeyCode.UP) {
                    inputMap.put("UP", true);
                }
                if (event.getCode() == KeyCode.DOWN) {
                    inputMap.put("DOWN", true);
                }
                if (event.getCode() == KeyCode.LEFT) {
                    inputMap.put("LEFT", true);
                }
                if (event.getCode() == KeyCode.RIGHT) {
                    inputMap.put("RIGHT", true);
                }
                if (event.getCode() == KeyCode.R) {
                    System.out.println("RESTART");
                }
            }
        });

        scene.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if (event.getCode() == KeyCode.UP) {
                    inputMap.put("UP", false);
                }
                if (event.getCode() == KeyCode.DOWN) {
                    inputMap.put("DOWN", false);
                }
                if (event.getCode() == KeyCode.LEFT) {
                    inputMap.put("LEFT", false);
                }
                if (event.getCode() == KeyCode.RIGHT) {
                    inputMap.put("RIGHT", false);
                }
            }
        });
    }

    public Map getInputMap() {
        return inputMap;
    }
}

```

And this is the part of the Game Loop that the map gets copied:

```
private void updateGame() {
    frameCount++;
    inputMap.putAll(inputManager.getInputMap());

    if (inputMap.get("UP").booleanValue()) {
        y -= 5;
        player.setLayoutY(y);
    }

    if (inputMap.get("DOWN").booleanValue()) {
        y += 5;
        player.setLayoutY(y);
    }

    if (inputMap.get("LEFT").booleanValue()) {
        x -= 5;
        player.setLayoutX(x);
    }

    if (inputMap.get("RIGHT").booleanValue()) {
        x += 5;
        player.setLayoutX(x);
    }
    inputMap.clear();
}

```

I am aware that the movement part is not right.

# Answer
> 2 votes
What do you really need to do here? You need to check for the presence of an action. While your current solution will get you there, it's fairly heavy for a presence/non-presence check.

First, using `String` constants typically isn't a good idea when designing a framework. It's easy and expandable, but more often than not you want to use an `enum`:

```
enum Command{
    UP, DOWN, LEFT, RIGHT;
}

```

This lets you easily add and remove commands down the line. If you needed to add a fire button, for instance, you could add `FIRE` to the enum, and you'd be set.

Second, while a `Map` to `Boolean` seems like the logical choice, if you're just checking two states, you can use a `Set` and use `contains(Object)` to reduce the overhead. Because you're now using an `enum` to store your states, you can use the blazingly fast `EnumSet` to do this:

```
private EnumSet<Command> inputKeys = EnumSet.noneOf(Command.class);

```

As a side note: if you're comparing a single value to a bunch of other values, `switch`/`case` is the way to go.

The simplified code:

```
import java.util.EnumSet;

import javafx.scene.Node;
import javafx.scene.Scene;

class InputManager{
    private EnumSet<Command> inputKeys = EnumSet.noneOf(Command.class);

    InputManager(Scene scene) {
        scene.setOnKeyPressed(event->{
            switch(event.getCode()){
                case UP:
                    inputKeys.add(Command.UP);
                    break;
                case DOWN:
                    inputKeys.add(Command.DOWN);
                    break;
                case LEFT:
                    inputKeys.add(Command.LEFT);
                    break;
                case RIGHT:
                    inputKeys.add(Command.RIGHT);
                    break;
                case R:
                    System.out.println("RESTART");
                    break;
            }
        });
        scene.setOnKeyReleased(event->{
            switch(event.getCode()){
                case UP:
                    inputKeys.remove(Command.UP);
                    break;
                case DOWN:
                    inputKeys.remove(Command.DOWN);
                    break;
                case LEFT:
                    inputKeys.remove(Command.LEFT);
                    break;
                case RIGHT:
                    inputKeys.remove(Command.RIGHT);
                    break;
            }
        });
    }

    public EnumSet<Command> getInputKeys(){
        return inputKeys;
    }

    enum Command{
        UP, DOWN, LEFT, RIGHT;
    }
}

class GameLogic{
    // Dummy values
    volatile int frameCount = 0, x = 0, y = 0;
    InputManager inputManager = null;
    Node player = null;

    private void updateGame() {
        frameCount++;

        EnumSet<InputManager.Command> keys = inputManager.getInputKeys();

        if(keys.contains(InputManager.Command.UP)){
            y -= 5;
            player.setLayoutY(y);
        }
        if(keys.contains(InputManager.Command.DOWN)){
            y += 5;
            player.setLayoutY(y);
        }
        if(keys.contains(InputManager.Command.LEFT)){
            x -= 5;
            player.setLayoutX(x);
        }
        if(keys.contains(InputManager.Command.RIGHT)){
            x += 5;
            player.setLayoutX(x);
        }
    }
}

```

# Answer
> 5 votes
Hashmaps are okay. If you believe you are going to get a performance bottleneck on input, then you are doing something critically wrong, or you're pre-maturely optimizing.

Unlike the other answer, with hashmaps you don't have to worry about array bounds or things going wrong, you just put it in and get it out when you need it.

I use my own custom **enumerations** with hashsets/maps, and the footprint is so small that if I take it out (as in, drop polling input) it's not even noticeable. Spending time converting to arrays and then always making sure I don't do something dumb forever afterwards with array bounds is not a good tradeoff IMO.

While putting in an "UP"/"DOWN"/"LEFT"/"RIGHT" probably means you should be using an enumeration, you can leave it for right now and revisit it later if you want.

# Answer
> 3 votes
Copying hash maps is horribly expensive, in the context of an operation that needs to be executed millions of times a second.

You're doing this up to 120 times a second. Performance-wise it's perfectly acceptable. That's not saying I'd do it the same way, but you have a decent approach that's going to work, so stick with it.

# Answer
> 3 votes
It seems like you will know what types of inputs there will be ahead of time, so using a `HashMap` seems over-complicated to me. You want to pass around a bunch of booleans, so why not just pass around a bunch of booleans like this?

```
class Input {
    public boolean up = false;
    public boolean down = false;
    public boolean left = false;
    public boolean right = false;
}

```

Instead of having to call two methods to get a boolean you can just check the value directly, like so:

```
private void updateGame() {
    frameCount++;
    Input input = inputManager.getInput();

    if (input.up) {
        y -= 5;
        player.setLayoutY(y);
    }

    if (input.down) {
        y += 5;
        player.setLayoutY(y);
    }

    if (input.left) {
        x -= 5;
        player.setLayoutX(x);
    }

    if (input.right) {
        x += 5;
        player.setLayoutX(x);
    }

}

```

# Answer
> 0 votes
Hashmap seems like overkill. I personally use an array for buffering (if you even need it), a flag-style enum for my inputs, and a currentInput variable that gets set with these flags.

```
int UP = 1;
int DOWN = 2;
int RIGHT = 4;
int LEFT = 8;

// The current input as the user entered
int currentInput = 0;

void handle(KeyEvent event)
{
    if (event.GetKeyCode(Keys.Up))
    {
        currentInput |= UP;
    }
    // etc...
}

```

Later in your `updateGame()` method:

```
void updateGame()
{
    if ((currentInput&UP) == UP)
    {
        // set velocity, pos, etc.
        // Reset currentInput
        currentInput ˆ= UP;
    }
    // ...
}

```

EDIT: Excuse me for my slow edits, I'm on my tablet.

---
Tags: java, 2d, architecture, movement, input
---


# Question
Title: How do I slowly decrease a float from 0.5 to 0?
I have a 2D racing game with a track, and the track is repeated with `vector2`. When I die, I want to slowly stop moving the track, but I do not know how.

---

Here is my code:.

```
using UnityEngine;
using System.Collections;

public class trackMove : MonoBehaviour
{
    public static trackMove Instance { get; private set; }

    public float speed;
    Vector2 offset;

    // Use this for initialization
    void Start ()
    {
        Instance = this;
    }

    // Update is called once per frame
    void Update ()
    {
        offset = new Vector2(0, Time.time * speed);
        GetComponent<Renderer> ().material.mainTextureOffset = offset;
    }
}

```

---

Here is my current Inspector view:

# Answer
You will have to make slight changes to the way you compute the offset and put additionnal code.

```
public float decreasingSpeed = 1;

private bool decreasing = false;
private float initialSpeed ;
private float stopTime = 0 ;

void Start ()
{
    Instance = this;
}

void Update ()
{
    if( decreasing )
       speed = Mathf.SmoothStep( initialSpeed, 0, (Time.time - stopTime) * decreasingSpeed ) ;
    offset = offset + new Vector2(0, Time.deltaTime * speed);
    GetComponent<Renderer> ().material.mainTextureOffset = offset;
}

public void Stop()
{
    decreasing = true;
    initialSpeed = speed;
    stopTime = Time.time ;
}

```
> 0 votes

# Answer
What i've seen is , you got most of the logic right. What you need is just decrease speed to 0 when you die. Add a bool. Lets say;

```
public bool isPlayerDead = false;

```

Also you can add a float for decrease speed. Lets say;

```
public float decreaseSpeed = 0.01f;

```

In addition you can make one more bool to make the decreasion stop.

```
public bool isDecreasingDone = false;

```

When the player dies you turn this bool to true. So you can add the following in `Update()`

```
if(isPlayerDead == true && isDecreasingDone == false)
{
   speed = speed - decreaseSpeed;
}

if(speed <= 0.0f)
{
   speed= 0.0f;
   isDecreasingDone = true;
}

```

You can edit the `decreaseSpeed` to change the slowing speed. This gives you a linear slowing.

Hope this helps! Cheers!
> 0 votes

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


# Question
Title: GUI override for weapon stats in Warhammer 40K Armageddon
I'm developing some additions to WH40K Armageddon and trying to add a Weapon 4 to units.

Game uses .gui file called unit\_details.gui for when right clicking to a unit. Weapon 1, 2, 3 is exactly the same for each other and with this, I added a Weapon 4.

And in game's source files, I thought I added all necessary codes for Weapon 4.

But this doesn't work. It only writes "Weapon 4, 85, 85, 85, 1" and etc, not weapon's actual stats. But stats for Weapon 1, 2, 3 work well except for Weapon 4.

And in visual studio's console it writes: "Gui WARNING:Override class 'CUnitDetailsGui::Weapon4' not found". But I'm sure I added all necessary codes for Weapon4 in all related classes I found. There is none other class for Weapon4.

Do you have opinion what I'm not doing?

Here is an example in unit\_details.gui file. All codes for Weapon 1 and 2 is exactly same as well.

```
[CUnitDetailsGui::Weapon3] RootElement
                                    {
                                        classOverride = "CUnitDetailsGui::Weapon3"
                                        offset = (294, 86)
                                        offsetRB = (700, 108)
                                        size = (406, 22)
                                        childs = {
                                            [Weapon::Range] Text
                                            {
                                                classOverride = "Weapon::Range"
                                                offset = (200, 10)
                                                font = "fonts/caslon.ttf"
                                                text = "85"
                                                textAlignX = CENTER
                                                textAlignY = CENTER
                                                fontSize = 14
                                                lineGap = 9
                                            },
                                            [Weapon::Damage] Text
                                            {
                                                classOverride = "Weapon::Damage"
                                                offset = (239, 10)
                                                font = "fonts/caslon.ttf"
                                                text = "85"
                                                textAlignX = CENTER
                                                textAlignY = CENTER
                                                fontSize = 14
                                                lineGap = 9
                                            },
                                            [Weapon::AP] Text
                                            {
                                                classOverride = "Weapon::AP"
                                                offset = (277, 10)
                                                font = "fonts/caslon.ttf"
                                                text = "85"
                                                textAlignX = CENTER
                                                textAlignY = CENTER
                                                fontSize = 14
                                                lineGap = 9
                                            },
                                            [Weapon::Ammo] Text
                                            {
                                                classOverride = "Weapon::Ammo"
                                                offset = (316, 10)
                                                font = "fonts/caslon.ttf"
                                                text = "3"
                                                textAlignX = CENTER
                                                textAlignY = CENTER
                                                fontSize = 14
                                                lineGap = 9
                                            },
                                            [Weapon::Accuracy] Text
                                            {
                                                classOverride = "Weapon::Accuracy"
                                                offset = (354, 10)
                                                font = "fonts/caslon.ttf"
                                                text = "35%"
                                                textAlignX = CENTER
                                                textAlignY = CENTER
                                                fontSize = 14
                                                lineGap = 9
                                            },
                                            RootElement
                                            {
                                                offset = (0, 1)
                                                offsetRB = (184, 22)
                                                size = (184, 21)
                                                childs = {
                                                    [Weapon::Name] Text
                                                    {
                                                        classOverride = "Weapon::Name"
                                                        offset = (5, 10)
                                                        font = "fonts/caslon.ttf"
                                                        text = "Weapon 3"
                                                        textAlignY = CENTER
                                                        fontSize = 15
                                                    }
                                                }
                                                crop = false
                                            },
                                            [Weapon::HexAccuracy] Text
                                            {
                                                classOverride = "Weapon::HexAccuracy"
                                                offset = (392, 10)
                                                font = "fonts/caslon.ttf"
                                                text = "10%"
                                                textAlignX = CENTER
                                                textAlignY = CENTER
                                                fontSize = 14
                                                lineGap = 9
                                            },
                                            [Weapon::TraitList] List
                                            {
                                                classOverride = "Weapon::TraitList"
                                                offset = (415, -2)
                                                offsetRB = (506, 24)
                                                size = (91, 26)
                                                childs = {}
                                                crop = false
                                            }
                                        }
                                        crop = false
                                    },
                                    [CUnitDetailsGui::Weapon4] RootElement
                                    {
                                        classOverride = "CUnitDetailsGui::Weapon4"
                                        offset = (294, 114)
                                        offsetRB = (700, 136)
                                        size = (406, 22)
                                        childs = {
                                            [Weapon::Range] Text
                                            {
                                                classOverride = "Weapon::Range"
                                                offset = (200, 10)
                                                font = "fonts/caslon.ttf"
                                                text = "85"
                                                textAlignX = CENTER
                                                textAlignY = CENTER
                                                fontSize = 14
                                                lineGap = 9
                                            },
                                            [Weapon::Damage] Text
                                            {
                                                classOverride = "Weapon::Damage"
                                                offset = (239, 10)
                                                font = "fonts/caslon.ttf"
                                                text = "85"
                                                textAlignX = CENTER
                                                textAlignY = CENTER
                                                fontSize = 14
                                                lineGap = 9
                                            },
                                            [Weapon::AP] Text
                                            {
                                                classOverride = "Weapon::AP"
                                                offset = (277, 10)
                                                font = "fonts/caslon.ttf"
                                                text = "85"
                                                textAlignX = CENTER
                                                textAlignY = CENTER
                                                fontSize = 14
                                                lineGap = 9
                                            },
                                            [Weapon::Ammo] Text
                                            {
                                                classOverride = "Weapon::Ammo"
                                                offset = (316, 10)
                                                font = "fonts/caslon.ttf"
                                                text = "1"
                                                textAlignX = CENTER
                                                textAlignY = CENTER
                                                fontSize = 14
                                                lineGap = 9
                                            },
                                            [Weapon::Accuracy] Text
                                            {
                                                classOverride = "Weapon::Accuracy"
                                                offset = (354, 10)
                                                font = "fonts/caslon.ttf"
                                                text = "35%"
                                                textAlignX = CENTER
                                                textAlignY = CENTER
                                                fontSize = 14
                                                lineGap = 9
                                            },
                                            RootElement
                                            {
                                                offset = (0, 1)
                                                offsetRB = (184, 22)
                                                size = (184, 21)
                                                childs = {
                                                    [Weapon::Name] Text
                                                    {
                                                        classOverride = "Weapon::Name"
                                                        offset = (5, 10)
                                                        font = "fonts/caslon.ttf"
                                                        text = "Weapon 4"
                                                        textAlignY = CENTER
                                                        fontSize = 15
                                                    }
                                                }
                                                crop = false
                                            },
                                            [Weapon::HexAccuracy] Text
                                            {
                                                classOverride = "Weapon::HexAccuracy"
                                                offset = (392, 10)
                                                font = "fonts/caslon.ttf"
                                                text = "10%"
                                                textAlignX = CENTER
                                                textAlignY = CENTER
                                                fontSize = 14
                                                lineGap = 9
                                            },
                                            [Weapon::TraitList] List
                                            {
                                                classOverride = "Weapon::TraitList"
                                                offset = (415, -2)
                                                offsetRB = (506, 24)
                                                size = (91, 26)
                                                childs = {}
                                                crop = false
                                            }
                                        }
                                        crop = false
                                    }

```

# Answer
> 1 votes
I figured out problem... Project wasn't even building correctly. So I was working with old codes.

---
Tags: c++, gui
---