# Question
Title: Get enemy/chaser object to face player object - OpenGL
My chaser object will not face the player object. It simply keeps spinning around and won't face the player.

```
void chaser::Move() {
    vec3 plannedFacingDirection = normalize(p->GetPosition() - GetPosition());

    vec3 currentFacingDirection = normalize(vec3(0.0f, 0.0f, -1.0f)); //yes i know it's already normalized

    vec3 axisOfRotation = normalize(cross(currentFacingDirection, plannedFacingDirection));

    float dotProductOfVectors = dot(currentFacingDirection, plannedFacingDirection);

    clamp(dotProductOfVectors, -1.0f, 1.0f);

    float angle = acos(dotProductOfVectors);
    if (plannedFacingDirection != currentFacingDirection) {
        if (dotProductOfVectors != -1.0f && dotProductOfVectors != 1.0f) {
            transform = rotate(transform, angle, axisOfRotation);
        }
    }

    transform = translate(transform, normalize(currentFacingDirection) * speed);
}

```

Move() is called in the render() function. `p`is the player object. `transform`is a mat4 object. I will be eyeing this question like a hawk. It's really bugging me that I can't figure this out. Please comment with any questions of your own and I will answer them ASAP.

# Answer
To face a certain direction, I find that a much better approach is to built a new matrix, instead of transforming an old one with a rotation.

Let's say you want the chaser X axis to point at the target, and world Z is up:

```
vec3 x = ( tgt - chaserpos );
x.normalize();
// y is z cross x.
vec3 y = vec3(0,0,1).crossProd( x );
y.normalize();
// z is x cross y.
z = x.crossProd( y );

mat44 chasermat;
chasermat.setRow( 0, x );
chasermat.setRow( 1, y );
chasermat.setRow( 2, z );
chasermat.setRow( 3, chaserpos );

```

This code creates three axes that are perpendicular to each other. The x points to the target, the y points to the left, the z points up.

The resulting matrix will have pan, tilt, but no roll (horizon stays horizontal.)

NOTE: This code does not work if the chaser needs to look perfectly straight up or perfectly straight down.

NOTE: Your matrix library may have a LookAt() function that does just this. But described here is how to do this manually. After the LookAt() don't forget to set the translation.

**PS:** Your original code does not work because you determine an angle, but **not the sign of the angle**: do you need to turn clock wise or counter clockwise?
> 0 votes

---
Tags: opengl, c++, matrix, glm
---


title: HAA* / HPA* C++ Algorithm / Help

text:
# Question
Title: HAA* / HPA* C++ Algorithm / Help
so I have been working on implementing a form of HPA\* but i'm really struggling to decide what to do next.

https://webdocs.cs.ualberta.ca/~mmueller/ps/hpastar.pdf \<- here is the article.

There is pseudo-code but the notation is very hard for me to understand, but I struggle to read due to learning difficulties (visual snow / ADD) and I find the paper very difficult to understand, so I appreciate anyone willing to explain/ break it down to me in simpler language.

I have implemented my grid and seperated it into squares. Example diagram - here is my guess, I haven't implemented exits and entrances yet, green terrain is normal, white terrain are roads which travellers will travel across quicker, brown is mountains inpassable unless meets a special condition, and there are boats but they will use a different algorithm, since im only implementing HPA\* for ground units in the game ,and JPS for sea units as the sea grid is uniform without costs.

Lets say for sake of argument each pixel on that image is its own individual grid space.

Question 1. Do I have to resize the squares if water/mountains is involved- lets assume the water/mountains is a wall for the sake of the argument. (If so whats a good method?)

Question 2. Is there a general algorithm that can be used, I know the A\* algorithm, but how do entrances and exits link to eachother ? (thinking quad tree)

Question 3. How do I reconstruct the squares dynamically if the map could change or be dynamic.

Question 4. how does one traverse across the map from higher representation to lower representation.

Assumptions, I'm assuming first we path-find across the squares as a whole, then work out individually the route inside it from one end to another yes?

Also if you know the location of a good HPA\* library that would be also be nice.

# Answer
This paper is actually set up pretty oddly, most CS papers I see are, well, more succinct and to the point? This one kind of rambles doesn't properly label headers and doesn't go into what it is actually doing until section 3 and the *appendix*. You'll need to learn how to read these papers if you want to use these algorithms, so if you have problems with the appendix interpretation, I'm afraid you have a deeper level of misunderstanding somewhere that we can't help with unless you give more specific information on the holdup. But I can give you an overview of what the algorithm is.

This tackles the problem of "equal weighted un-directed graph with small constant maximum edge vertices per node (4 for rectangular grids) with predictable connection order" if you are looking for some keywords to look up for other methods.

Basically, the whole idea is:

* subdivide rectangular grid into sub grids.
* for each subgrid pre-compute paths to the borders
* create 2 border symetrical border "node" for each unobstructed border of equal length for adjacent subgrids.
* created edge between nodes on adjacent blocks if they were symmetric.
* created edge between nodes on the same block if there exists a connection.
* abstract grid now created.
* perform all pathfinding calculations using this as a heuristic and recalculate fastest path from your position to next position

On new path, the paper recommends using straight line approach to find smoothed paths, additionally A\* is used on the higher level graph.

Even higher levels of abstraction can be obtained for graphs via using combining the clusters seen at the previous levels, and essentially going through these steps again, but using your subgrids/clusters as the new basic block unit, and using the connections we previously created on them instead of cardinal direction connections.

This paper seems to ignore the existence of search algorithms that are APSP (all points shortest path) with which you would find the entire set of path for all nodes in a graph. If you try to use A\* for this you will have a very slow algorithm. The most basic algorithm taught in school, Floyed Warshalls, will mislead you into thinking that is the best one to use for this problem, however its runtime complexity is \\$O(V^3)\\$ and trust me, I've personally tried to use this on uniform grids only to find that it will literally take days to months to compute any significantly sized grid (1024x1024? forget about it). For grids, you can just use breadth first search with \\$O(EV)\\$ runtime complexity, and if you subdivide your grids into small enough chunks, your complexity (for example for 8x8 subdivisions) will be quite small, \\$O(NC)\\$, where \\$N\\$ is the number of blocks you have, and \\$C\\$ ends up being number of vertices \\$V\\$ * number of edges \\$E\\$ but since it never changes it is constant.

You can additionally reduce the cost even further by only computing the paths from edge to edge, reducing both computational and space cost significantly (and with smaller subgrids this is probably preferred).

It might look like we did some magic to make the complexity go down, but keep in mind that we eat that cost at run-time since we still have to do some path finding.

Just know that each of your precomputed results for each subgrid will have a space complexity of \\$O(N^2)\\$, so if you divide each into blocks of 8x8 = 64 cells, you'll have 4096 entries in some table telling you how to move to each thing in the fastest way for each of the \\$N\\$ subgrid blocks. You can use this on the higher level abstracted grids as well for faster results.

> Question 1. Do I have to resize the squares if water/mountains is involved- lets assume the water/mountains is a wall for the sake of the argument. (If so whats a good method?)

Nope, they are walls, as long as they don't change edge traversal cost your all good, the algorithm applies the same.

> Question 2. Is there a general algorithm that can be used, I know the A\* algorithm, but how do entrances and exits link to each other ? (thinking quad tree)

Not sure exactly what you are getting at, really all you need to know is if you can move from one edge to another, in this algorithm, edges are unobstructed symmetric lines of grid points of the same length from adjacent blocks. All you need to do here is just run A\* on each edge point within a block, and if a path is found with in one of the cells a long that edge to the other edge you are good, and you don't have to look at the rest of the cells with in an edge since they are all connected (if you can get to one block you can get to them all).

> Question 3. How do I reconstruct the squares dynamically if the map could change or be dynamic.

You would have to re-run the algorithm to construct the sub-grid/block edges for that specific block, remove any previous connections, and find the adjacent edges again. Additionally rerun the algorithm to create the abstract graph on top of the blocks/subgrids/clusters if you had higher levels of graphs.

> Question 4. how does one traverse across the map from higher representation to lower representation.

Run A\* on the top level representation, this essentially becomes your heuristic where you can then run more localized versions of A\* in the subgrids you created earlier in the lower levels, knowing that a path now *absolutely* has to pass through that subgrid.
> 2 votes

---
Tags: c++, tree
---


title: Is PID considered Steering Behavior?

text:
# Question
Title: Is PID considered Steering Behavior?
So I've recently used a PID controller to build a bot for a 2d physics based game. I also did a bit of reading on steering behavior but am still confused over one thing: Is a PID controller considered an implementation of steering behavior? Or are they two completely unrelated things?

# Answer
> 1 votes
I've use the term "steering" to describe PID control.

I find that I often have two parts to control a physics object:

First, a higher level function uses strategy/logic to determine where to steer to.

Next, the lower level function of actually steering towards this point, for which I tend to use PID controllers.

Oh, and as last step, you take the PID output of course, and use it as a force to apply to your physics object. Either as a linear force, or a torque. (If you want to cheat, you could use it to set a velocity, but that makes your simulation discontinuous.)

So to conclude, I think you can say that PID control is a form of steering, yes.

---
Tags: movement, ai, steering-behaviors
---


title: Inventory Grid Detection

text:
# Question
Title: Inventory Grid Detection
I'm working on creating an inventory system for a game. The inventory system will use cells and 2D images to represent items, like Minecraft, Diablo, or WoW. I've hit a bit of a snag when trying to let the player place items in the bag (click and drag style).

So far, I've successfully created the inventory grid, which is really smoke and mirrors:

```
public class InventoryMenu {
boolean objectSelected = false;
Item selectedItem;

public final int COLUMNS = 5;
public final int ROWS = 7;

ArrayList<Item> inv = new ArrayList<Item>((ROWS + 1) * COLUMNS);
Sprite slot;

public void render(Graphics g) {

    for (int i = 0; i < 40; i++) {
        int col = i % COLUMNS;
        int row = ROWS - i / COLUMNS;

        slot.draw(g, (Camera.width - slot.getWidth() * COLUMNS) + slot.getWidth()* col, row * slot.getHeight());

        if (inv.get(i) != null) {
            inv.get(i).render(g);
        }
    }
    if (selectedItem != null) {
        selectedItem.render(g);
    }
}

```

Basically, I have an arraylist that can hold items, and it just draws the "slot" image 40 times and if there's an item in that "slot" it draws the item image too. Cool? Cool. The problem comes if I want to allow the player to select an item in their inventory and move it to a different slot. I have no problem letting them pick it up (I use a pretty primitive brute force, but with any reasonably sized inventory, it works):

```
private Item grabItem(Point2D mouse) {
    for (Item i : inv) {
        if (i != null) {
            if (i.getPhysicsShape().contains(mouse)) {
                Item pick = i;
                selectedItem = pick;
                objectSelected = true;
                i = null;
                return pick;
            }
        }
    }
    return null;
}

```

That bit of code lets a player pick up an item, but placing it fails - it rarely gets the right slot, except if its the bottom row (0-4):

```
setDown(){
    int slotLoc = calcSlot(InputHandler.mouseCoords);
    placeItem(slotLoc);
}

private void placeItem(int loc) {
    if(loc < 0 || loc > ROWS * (COLUMNS + 1))
        return;

    int col = loc % COLUMNS;
    int row = ROWS - loc / COLUMNS;
    selectedItem.pickUp((Camera.width - slot.getWidth() * COLUMNS) + slot.getWidth() * col, row * slot.getHeight());

    inv.set(loc, selectedItem);
    selectedItem = null;
    objectSelected = false;
}

private int calcSlot(Point2D mouse){
    int colPos = (int) (COLUMNS - (Camera.width - mouse.getX()) / slot.getWidth());
    int rowPos = (int) (ROWS+1 - (mouse.getY()) / slot.getHeight());

    if (colPos > COLUMNS || colPos < 0 || rowPos < 0 || rowPos > ROWS + 1) {
        dropItem();
        return -1;
    } else {
        return colPos + 4*rowPos;
    }

}

```

I'm fairly confident that the problem is in calcSlot, but I can't seem to find where. Any help would be greatly appreciated, I'm sure it's something silly.

Images!!

So, I can pick up an item with no problem, and it automatically places it in the last slot. So far, everything is gold.

I can then click that image and lift it out of the grid, and it follows my mouse (mouse is hidden by PrntScrn, but its at the top left corner of the image:

When I try to place the item by clicking in the middle of slot 33, however, it derps and places it, inexplicably, in slot 27.

# Answer
I'll just give you the basic logic, not in Java, but I hope you can understand it.

Find the bottom left corner of the inventory (where the slot 0 is) and save that point in `BLpoint`. Then use variable `dropPoint = (mouse.x - BLpoint.x ; BLpoint.y - mouse.y)`.

If `dropPoint.x` or `.y` is less than zero, you've missed the inventory slots.

The slot coordinates `X = dropPoint.x / slotWidth`, `Y = dropPoint.y / slotHeight`.

For items larger than 1×1 this might require some alteration. I would suggest you make your slot numbers start at top left corner of the inventory, it's going to be more simple for you to code.

nice metal dude btw
> 3 votes

# Answer
```
private int calcSlot(Point2D mouse){
    int colPos = (int) (COLUMNS - (Camera.width - mouse.getX()) / slot.getWidth());
    int rowPos = (int) (ROWS - ((mouse.getY())- slot.getHeight()) / slot.getHeight());

    if (colPos > COLUMNS || colPos < 0 || rowPos < 0 || rowPos > ROWS + 1) {
        dropItem();
        return -1;
    } else {
        return COLUMNS*rowPos + colPos;
    }

}

```
> 0 votes

# Answer
have you tried to use an array of Rectangles then use a method like this to draw for example 35 inventory slots going left to right until finished.

```
 public Rectangles[] invSlots;

 public int INVENTORY_CELL_SIZE_X = 50;
 public int INVENTORY_CELL_SIZE_Y = 50;
 public int AMOUNT_OF_INVENTORY_CELLS = 35;

public void createSlots() {
invSlots = new Rectangle[AMOUNT_OF_INVENTORY_CELLS];
 for(int id = 0;id < invSlots.length;id++) {
    for(int x = 0;x<INVENTORY_CELL_SIZE_X;x+=INVENTORY_CELL_SIZE_X) {
        for(int y = 0;y<INVENTORY_CELL_SIZE_Y;y+=INVENTORY_CELL_SIZE_Y) {
       //use all incremented integers above to create rectangles transform;
          invSlots[id] =
         new Rectangle(x, y,INVENTORY_CELL_SIZE_X, INVENTORY_CELL_SIZE_Y);
        }
    }
 }

```

}

You can then draw one of these cells like so;

```
    g.drawImage(image or rect_here,
invSlots[incrementedInteger].x, invSlots[incrementedInteger].y,
invSlots[incrementedInteger].width, invSlots[incrementedInteger].height);

```

heres how to check what cell the player's mouse is inside of.

Make sure you call it from within a loop.

```
public void checkForMouseEntryOrWhatever() {
    for(int id = 0;id<invSlots.length;id++) {

        //mouse start
         if(mouseX >= invSlots[id].x
            && mouseY >= invSlots[id].y
            && mouseX <= invSlots[id].x+invSlots[id].width
            && mouseY <= invSlots[id].y+invSlots[id].height)
         {
                //DO WHATEVER WHEN THE PLAYER ENTERS THE INVENTORY CELL.
         }
         //Mouse end
    }
}

```

this method was made to be universal no matter the rectangles size.

it also has a basic id system because of the array, and is organized because of the 'left-to-right' drawing technique.

creating a Item dragging system shouldnt be very difficult after this if your using mouseDragged() method, simply make the item (that the player clicked-to-drag) follow the players mouse until released and then place that item in the slot that it was released in.

try this if statement for example.

it only works inside of a loop (for loop or while loop should do depending on engine)

```
 if(releasedX >= slotX && releasedY >= slotY && releasedX <= slotX +
 slotWidth && slotY <= slotY+slotHeight) {
     drawItem(item, slotX, slotY, itemWidth, itemHeight);

 }

```
> 0 votes

---
Tags: java, mathematics, rpg
---


# Question
Title: How do I get text width and height in Swing/AWT?
I'm making a game engine based on Java Swing and I wonder if I can get the text width/height.

Say, what I have is:

* the text string
* the font and text size (the `Font` object)

What I've done is:

* `g.drawString(...)`

What I want to know is:

* the width/height of the text that displayed on the screen

# Answer
Graphics returns FontMetrics that have method getStringBounds (and other usefull methods):

```
Rectangle2D r = graphics.getFontMetrics().getStringBounds(string, graphics);

```

With `r` you can for example render background for text and then render text.
> 4 votes

---
Tags: java, swing
---


# Question
Title: Entity update or Keyboard commands transferred to the Gaming server?
I am working on a research project .

I need to know the network communication in games in large Multiplayer games (Battlefield,GTA 5). Is there some official documentation present for these games?

Does the client(player) send Game Commands to the server which it communicates to all the other attached clients(players) or instead of commands ,Entity Update is carried forward which is then broadcastto other players?

Thanks

# Answer
> 1 votes
These things are seldom openly documented, unless they're patented. So if you know the company behind the game you're interested you could do a patent search to see if they're using a patented mechanism.

Another possibility is to play the game and sniff your own network traffic. That way you can see what packets are sent from your computer and received by your computer and you can then easily find out which of these belong to the game you play, filter them, and start analyzing their payloads. A great tool for that is Wireshark.

---
Tags: architecture, networking, entity-system, client-server
---


title: Separating Axis Theorem is inconsistent

text:
# Question
Title: Separating Axis Theorem is inconsistent
I recently implemented the SAT algorithm into my 2D game and at first it appeared to be working fine. However, when I move around and rotate the character in and out of the wall tiles, there are some angles and positions that do not register as a collision when the player and wall tile are clearly overlapping. I created my own RotatingRectangle class that rotates around the player and is the bounding box.

I am unsure what could be causing this, or if this is just natural SAT behaviour and it does not actually detect all collisions accurately? There are no other resources online for inconsistent SAT collision detection so I am lost. I will post my code for the projections and actual collision detection in case I made a silly mistake somewhere

```
    // Returns an array of projections, one onto each axes
    public Vector2[] ProjectOntoAxes(List<Vector2> points)
    {
        Vector2[] projections = new Vector2[2];

        for (int i = 0; i < Axes.Length; i++)
        {
            float max = float.MinValue;
            float min = float.MaxValue;

            for (int j = 0; j < points.Count; j++)
            {
                float res = Vector2.Dot(Axes[i], points[j]);

                if (res < min)
                {
                    min = res;
                }
                else if (res > max)
                {
                    max = res;
                }
            }

            projections[i] = new Vector2(min, max);
        }

        return projections;
    }

        private bool PlayerTileCollision(Tile tile)
    {
        // Check overlap on projections onto player axes
        Vector2[] projections = Player.BoundingRect.ProjectOntoAxes(tile.BoundingRect.Corners);
        for (int j = 0; j < projections.Length; j++)
        {
            if (Player.BoundingRect.Projections[j].X > projections[j].Y ||
                Player.BoundingRect.Projections[j].Y < projections[j].X)
            {
                // No overlap can exit
                return false;
            }
        }
        // Check overlap on projections onto tile axes
        projections = tile.BoundingRect.ProjectOntoAxes(Player.BoundingRect.Corners);
        for (int j = 0; j < projections.Length; j++)
        {
            if (projections[j].X > tile.BoundingRect.Projections[j].Y ||
                projections[j].Y < tile.BoundingRect.Projections[j].X)
            {
                // No overlap can exit
                return false;
            }
        }

        return true;
    }

```

UDPATE: I have added code to visualise the projections and axes to see what is going on, and it appears that the projection code is not properly selecting the correct minimum and maximum values. I will try to figure out why now. (Purple lines are player projections and orange is the projections of that tile I am standing on, the top left one and the player axes can be visualised via the white lines at the origin)

# Answer
> 3 votes
I am happy to say that I have squashed the bug. The visualisations really aided me and I strongly recommend anybody struggling with anything to try and get whatever it is your working on onto the screen. Now for how I fixed the bug and what it was. The reason it was not properly setting the min and max projections is due to the ProjectOntoAxes method. For the min and max values, I initially set them to the complete opposite values via the lines

```
float min = float.MaxValue;
float max = float.MinValue;

```

This was so that they were guaranteed to be set to one of the corners. Now the bug causing lines are the if and else if conditional statements inside the for loop. What was happening was that if the very first corner checked was actually the maximum value, it would actually always set off the first if statement checking if it is less than the minimum because the minimum is literally the highest value possible. Due to the next if having an else before it, it would not be checked and thus the max value will not actually be set to the real max value. Therefore the simple fix was to remove the else and just have to regular if statements, this allows for the case where if the first corner checked is actually going to end up being the maximum, it will still trigger the second if statement for setting the maximum value.

This:

```
if (res < min) {
min = res;
} else if (res > max) {
max = res;
}

```

became this:

```
if (res < min) {
min = res;
} if (res > max) {
max = res;
}

```

# Answer
> 1 votes
Your projection is incorrect. Instead of

$$projected = \vec a \cdot \vec b$$

(Where \\$\cdot\\$ means dot product)

you need to use

$$projected = \vec a \cdot \frac{\vec b}{|\vec b|}$$

(Where \\$|\vec v|\\$ is the length of the \\$\vec v\\$ vector and \\$ \vec a\\$ is the axis)

---
Tags: c#, monogame, separating-axis-theorem
---


# Question
Title: How do you decide on the size of a tech tree?
Is there any established metric with which a game designer might decide the best size for a tech tree?

In this case the game is a single player 4X game (thank you, Peter, for that term). I wanted to incorporate an appropriate length and breadth of tech tree as a basic design goal.

For instance, is there data on player reactions to tree size vs game scope or game length? Or even a reasonably established rule of thumb?

# Answer
> 20 votes
What you must worry about is the number of **choices** in the tech tree.

In terms of a 4X game, lets say the depth of the tech tree is what affects how long a single play-through takes, while the width of the tech tree affects how many choices a player has each time they pick a new technology. The depth is determined by your game design, but the width should be limited, and relatively constant over time, although it's common to start narrow then get slightly wider as the game progresses.

When letting the player pick between different options, you should generally try to **keep the number of options between 3 and 8\*** If you want a wider variety of choices than that, a good way around it is to implement a hierarchy of choices - for example in MoO you could chose from 8 fields of research and in each field you could chose from up to 3 techs. In Crusader Kings there were 3 types of techs with 8 sub-choices each.

Figuring out how deep you want the tech tree to be depends on too many factors to be solved with a formula. But in most cases it's at least 3 levels deep, so I say implement 3 and start playtesting. Keep in mind that more than 10 levels are quite rare.

* Why 3 and 8? 3 is the minimum required for a multiple choice scenario, which players experience slightly different from a binary choice. 8 because it is believed by some that *7 plus or minus 2* is the upper bound of objects that can be retained in working memory - more choices than that are very likely to overwhelm the player making the choice and cause them to just pick one at random. Truthfully, I just wrote 8 because I know of some games that set the upper bound at 8, but in practice I like to aim at 5 myself.

# Answer
> 33 votes
In order to answer this question, we first need to consider why we have tech trees in the first place.

* They limit the complexity in the beginning of the game by hiding the more advanced game mechanics. This makes the game more accessible to beginners.
* They serve as a reward mechanic. Unlocking a new tech tree node gives the player a feeling of progression and accomplishment (as long as they are relevant).

The size of the tech tree is dictated by these two considerations.

First you need game content and features which are worth unlocking form a design perspective. What to add and what to leave out is an important decision which is influenced by both design considerations ("Would adding 20 more unit types make this game more interesting or just more confusing?") and business considerations ("Yes, it would make the game better, but do we have the budget for it?"). And in what order and frequency to unlock content and mechanics to make sure every phase of the game is interesting to play is another important game design decision. Both of these design aspects are far more important than the UX of your research screen. And there are no simple rules of thumb for them either, because they depend too much on design details of the overall game concept.

(Not that the UX of your research screen doesn't matter. But its job is to *sell* the complexity to the player. You shouldn't optimize the complexity of your game solely for being easy to represent on the research screen)

And then you need to make sure that every tech tree node is relevant in order for it to feel like a reasonable step of progression. "Now I can build space ships" is a relevant progression step. "Now my woodcutters are 0.15% more productive while it rains" is likely not. You also need to make sure that each tech node is useful just by itself. Unlocking railroads, locomotives and train wagons separately when none of them serves any purpose without the other two is just busywork, so they should be merged into one tech node. This limits the number of nodes into which you can divide your mechanics and content.

That means the size of the tech tree is determined by the depth and breadth of your game mechanics and content, not the other way around.

# Answer
> 3 votes
I think you should start from definition of the context: which kind of games? genre? single or multiplayer?

In my experience as player and hobbyist, less options with meaningful effect into gameplay are desirable instead of a lot of options with few impact on gameplay. And keep in mind that presentation to player is a critical point. A huge (100+) tech tree is hard to fully master for a player and could be difficult even to display. Also is not clear how much important is the tech tree, I mean if right choice is critical in your game or is something not even mandatory to win.

Some examples:

1) less options in a tech tree, like in Starcraft 2. Because the realtime and mostly multiplayer nature of the game, game designer decided to stay on a limited choices. Games duration here the critical point: a SC2 game in average could last 11 minutes. In that time player has to control everything, understand and use tech tree and win.

2) more options like in Hearts of Iron 4. Because game is mostly single player could be paused and games could require a lot of time (20 hours?) many players stay a lot of time inside the game, game designers develop an huge tech tree ( more than one actually). Mastering a tech tree in order to win is critical and many guides are written only on this

---
Tags: game-design, progression
---


# Question
Title: How can I speed up slow loading of big levels?
I created a level loader that loads levels saved in an XML format. This means I am using an XML parser to read the levels. It works, but slightly bigger levels take too long to load. So now I am looking for a way to speed up loading. I don't need the whole file to be loaded at once, as the player can't see the whole map anyway, so partial loading would be fine.

I thought about a tile based loading mechanism where there are multiple parts of the map, and the loader only loads the part/tile where the user is standing. But I am not sure if that is a good idea.

# Answer
First of all, you should measure where exactly the bottleneck is so you don't waste time improving things which are already good enough. The bottleneck could be any of these:

* Reading the XML file from the hard drive
* Your XML parser parsing it
* Your code which interprets the output of the XML parser and converts it into your internal data structures
* The loading of related assets (map tiles, etc.)
* Initialization of the game

But your question specifically mentions partial loading of map parts. So for the sake of this answer, let's assume that you did profile your code, found that reading and/or parsing the XML file is the problem and that partial loading is indeed the most obvious solution to your problem.

With XML-based file formats, this is usually not possible. A DOM-based XML parser will need to parse and validate the whole XML document before you can extract any data from it. A SAX-based XML parsers will at least have to read everything up to the node you are looking for. So if you want to allow partial loading, you will have to ditch the XML-based format and invent your own binary file format where map chunks start at known file positions you can selectively `seek` to without having to read the data in between.

When you really want to keep using XML, you could store each map chunk as a separate XML file.
> 26 votes

# Answer
Despite it being used for virtually everything, and despite it being used even in high-volume, low-latency applications, XML is an abysmal format for almost everything, but in particular for applications that have timely constraints, including games (except maybe for storing the game's settings). Even for live data, a simple binary tagged format which basically does the same as XML, just not human-readable (say, a 16-bit node type, 32-bit length, followed by contents), will be *many times* faster to read and write.

XML is tempting because it is human readable, and you don't need more tools than a text editor to write an XML file. However, it is also overly verbose, doesn't handle several types of data (binary data, large amounts of numbers, etc.) too well, and it takes a *very* non-neglegible time to process.
You can speed up parsing considerably by using a different parser, there are many alternatives (rapidxml, pugixml, whatever), however, that does not address the general problem of the format being overly verbose and human-readable to begin with.

While it is acceptable, and not even too uncommon, to use XML in one's production pipeline (though most people would rather use JSON or YAML), normally there is a custom-made tool that runs during the build process and that converts your XML files to a proprietary binary format which can ideally (not necessarily, but ideally) simply be loaded or memory-mapped as-is. No parsing whatsoever, just memory map, and set a pointer.
That same tool (or a similar one) will usually also read in other data such as e.g. textures which are stored in a variety of formats that may also be non-trivial to parse, and also put them into a binary game file in a way so they can just be mapped ready-to-go.
With the correct format, loading should be rather 0.45 seconds than 45 seconds.
> 7 votes

# Answer
There are a number of factors to approaching this problem, although you are on the right track.

**Single Load**

The first approach, as you've already tried, is to load it all at once. This puts all your load time and file I/O up front. As you've already noticed, as a map size grows, your initial load time can become annoying to the user. This also creates an upper bound on your maximum world size based on the minimum required memory of the target platform.

There are two other ways of handling this that I know of: you can chunk the world, and load them off screen as the player moves closer to them(stream loading); and you can have loading zones.

**Loading Zones**

Loading zones allow you to find a maximum chunk size that performs favorably, and subdivide your world into pieces no larger than that. When the player walks into a transit region (door, cave, map edge), some sort of transition graphic or animation takes place to distract the player. The new zone is loaded from the file system, while the old is saved and unloaded. This is a middle of the road approach. While it allows you to have worlds much larger than the memory capacity of the target device and puts all your I/O effort before the player is given control, this increases I/O operations over your initial approach. This can also break continuity of gameplay, which may or may not be favorable for the style of your game. The Final Fantasy series is probably the most recognizable for this type of approach.

**Stream Loading**

What I would consider the most recognizable example of stream loading is Minecraft. Chunks are loaded to and removed from memory as the player proximity changes. As with zone loading, stream loading removes the upper bound on world size as well. It also removes the interruptions of the loading effort from the user experience. However, this is the most file I/O heavy approach, as zones may be loaded and dropped from memory many times during a play session. Care must also be taken to load a zone at a closer proximity than they are removed from memory, in order to prevent a player repeatedly walking across a chunk boundary from burying the game in I/O operations. For 3D games, a method called *doglegging* is often employed which blocks the player's view of the area that is being loaded. This usually takes the form of a hallway with a turn in it, but can be any obstruction that blocks the player's line of sight.

Which of these approaches works best for your game is up to you.
> 5 votes

# Answer
Let's have a look at *smart*... what is smart exactly?

You state that you use XML as a format to store your levels. XML is a hierarchical format that is stored into a file. Thus we have 2 main factors that influence our loading times:

1. IO speed: That one is a **hard constraint**. You can't influence the reading and writing speed with your code. At least not too much. You can make use of things such as the processor cache size, etc. but that is low-level stuff and also different from computer to computer.
2. Your XML structure: This is where you can go wild. You can decide how you store things and what comes earlier, what later. You can even start grouping parts of a level into smaller datasets and then order these datasets in your big XML document, the earlier needed ones being closer to the beginning of the file.

So expanding on the second factor you could store your level in a format something like this:

```
<level>
    <name>Dragon Boss</name>
    <par-time>45</par-time>
    <sections>
        <section>
        ...
        </section>
        <section>
        ...
        </section>
        <section>
        ...
        </section>
    </sections>
</level>

```

Each `<section>` containing part of the level so it can be loaded one of these at a time.

Now that we've organized the format into something more useful the next step would be making sure that we can actually make use of this feature. One way is to load the whole file into memory, then breaking it down and only start parsing the level data after breaking it down. Thus you can load additional sections on demand without having to do all the expensive creation of textures, physics objects and what-not before you need them.

If your file is, for some weird reason, too big to load into memory then you could start using a SAX-parser instead of the DOM-parser you're likely using. The advantage of a SAX-parser is that it doesn't need to parse the whole file before you can work on it. It also reads and processes the file inherently different from a DOM-parser, so reading up on both might be good anyways.

---

Another topic that seems to boil up from your comments on other answers is that of **organizing your data**. You should in general strive to decouple your game logic from your game-data where possible. E.g. loading a level must not mean to read a file from the disc and create everything that is described in each line of the file. It might be (it actually is) better to, instead, store the data in an in-memory datastructure and then start working on that only where necessary.
> 3 votes

# Answer
Don't change your XML file if you find it a useful format for you to work with.

The trick is to keep the file you like but not have your game use that file directly. Write a simple routine (to run as part of packaging the game) to parse your XML into optimal chunk sizes to be loaded dynamically and at the same time create an index for those chunks that you can load into memory when your game starts.

As a very simplified example if your draw distance is .9km then each chunk file could represent a 1km square of your world grid.

Your parser splits your world into 1km square chunk files

In each chunk file have the parser add the filenames of the 8 chunk files adjacent to it, that way you don't need to hit the index to know which neighbours to load. Also add the top-left coordiate and bottom-right coordinate of the grid chunk so you can easily test if a players location is in that chunk

The parser then creates an index file by going through all the chunks storing chunk-file-name, top-left coordinate, bottom-right coordinate

Game loads, searches the index to find which chunk the player is in. Loads the chunk file, reads the adjacent chunk list from that chunk file and loads those chunks too. You now have 9 chunks loaded surrounding your player. As your player moves through the level if your players location goes beyond the current chunk then search the other loaded chunks for the chunk the player is now in. Use the new chunk's list of adjacent chunks to load the newly adjacent chunks and unload ones that are nolonger adjacent.

If the player moves ( teleports ) searching the loaded chunks to find out which one it is in will fail .. at which point you lookup against the index again
> 1 votes

# Answer
This is basically ignoring the suggestions about profiling your load time, evaluating file format complexity, etc. and is I see now a variant on Stephan's loading zones suggestion.

Consider if you had a VERY large level - like an MMO would have. Realistically you would not load the entire thing in one shot. Instead, you'd do it in pieces. Or load it at different levels of detail - low level detail (and probably thus smaller data files) for things far away, and only the high level of detail near the player.

So the approach would be something like this...

1. Break your level up into sections
2. Model these sections at different levels of detail - from very low detail which is sufficient for the player to view it from a long distance, and very high detail for where the player is.
3. Only load sections based on what level is required.
4. Dynamically load (and unload) sections as the player moves.

The assumption is that low level detail sections will load very very quickly, and high level will take more time.

This will help by allowing you to load just what you need, not everything. It also gives you some control over processor load, as you won't have to render or simulate fine details that are distant - only where the player is.

It's a generalized answer, but it's one that might work for you. It definitely is an approach for a very large level, but not really practical for a small one. Maybe your needs are somewhere in between and it will help.
> 0 votes

---
Tags: loading, levels, world-editor
---


title: share assets beetween platforms

text:
# Question
Title: share assets beetween platforms
What is the good way to share assets between platforms (android, desktop, etc) ?

by default there is an assets folder in each platform folder.

# Answer
The plebiscited and usual way is to use the android asset folder for all other platforms

ie for desktop:

Click Run -\> Edit configurations..., then change the "Working directory" parameter

https://stackoverflow.com/questions/28433012/how-do-i-link-assets-from-android-to-desktop-in-libgdx
> 0 votes

---
Tags: libgdx, assets
---


# Question
Title: Why is the "back" key acting like it is pressed twice?
I want to show toast message when the user presses the back button. I am handling button using this code, which is in my `Update` function:

```
if (Input.GetKeyUp(KeyCode.Escape)) {
  print ("UPUP");
  ToastHelper.ShowToast ("Back", false);
  //Application.Quit();
}

```

`ToastHelper` is plugin here.

The issue is that the toast message shows up twice, so it seems like the back key is acting like it was pressed twice. I only want it to execute once.

# Answer
> -1 votes
Problem gets solved. Its due to same script attached to two gameobject.

---
Tags: unity
---


# Question
Title: Why do my Box2D bodies occasionally get stuck and separate forcibly?
I'm making a space game with LibGDX and Box2D. I made a video here to illustrate the issue.

*Verbal description*: When objects collide, they sometimes get stuck together and are then suddenly separated by a strong force.

Both objects have identical body definitions and fixtures:

```
bod = new BodyDef();
bod.type       = type;
bod.allowSleep = false;

shape = new CircleShape();
shape.setRadius(values[0]);

fix = new FixtureDef();
fix.restitution = 0f;
fix.friction    = 1f;
fix.shape       = shape;
fix.density     = 1f;

worldBod = world.createBody(bod);
worldBod.setTransform(position.x, position.y, 0);
worldBod.createFixture(fix);

```

Why might this be happening? How can I fix it?

**Update**: Here is some more info.

The Player class contains a function update(float deltaTime) with the rest listed below

```
force.x += (directionVector.x * SPEED)*deltaTime;
force.y += (directionVector.y * SPEED)*deltaTime;

//This helps keep the object in control from preventing forces greater then 3
if(force.x >= 3){
    force.x = 3;
}if(force.x <= -3){
    force.x = -3;
}if(force.y >= 3){
    force.y = 3;
}if(force.y <= -3){
    force.y = -3;
}
//This quickly reduces the force back down to 0
force.x *= 0.5;
force.y *= 0.5;

this.getBody().applyForceToCenter(force, true);

```

In the render part of the main game class I step the world with

```
gameWorld.step(Gdx.graphics.getDeltaTime(), 6, 6);
//although increasing or decreasing the itterations seems not to help

```

and Finally the hexagon's are created using the ShapeRenderer pulling the position and

```
sr.setProjectionMatrix(camera.combined);
sr.begin(ShapeType.Line);
sr.circle(p1.getBody().getPosition().x, p1.getBody().getPosition().y, 1);
sr.circle(barrierPole.getBody().getPosition().x, barrierPole.getBody().getPosition().y, 1);
sr.end();

```

# Answer
Don't use a variable time step for physics, this will mess up the entire engine.

Box2D will attempt to apply enough force depending on the level of penetration, if the step is constantly changing then Box2D is getting different numbers each time it tries to separate fixtures.

Use an fixed timestep instead:

```
world.step(1f/60f, 5, 8);

```

Or some other variation, I sometimes do 1f/30f, depending on the performance of the high time step.
> 2 votes

# Answer
Try to think about what happens when the objects overlap by a bit. This is the usual reason for such behaviour. Most likely the issue is in the part where collision is worked out and the force after collision applied.
> 1 votes

# Answer
**`b2Settings::b2_velocityThreshold`**

https://github.com/erincatto/Box2D/blob/f655c603ba9d83f07fc566d38d2654ba35739102/Box2D/Box2D/Common/b2Settings.h#L94

If something with speed below that value hits a wall, it just sticks to it instead of bouncing back.

The default value is `1.0` currently. To modify it you have to hack the define in that header file apparently.

Here is a simple Urho3D example to illustrate this point: https://github.com/cirosantilli/Urho3D-cheat/blob/7f48db5046bfd54584919dddbe55cef7c8459684/velocity\_stop.cpp Try hacking the Box2D source that is copy pasted inside Urho3D to see how it affects the bouncing.

One workaround is to just make the scene larger. So e.g., the 1.0 world size I was using in my example was too small, but if you use magnitudes along 100.0 as done in the Testbed, things look fine.

Using small bodies also has further related caveats, e.g. the skin size that separates bodies becomes more visible: Rectangles render with gaps in between them (Box2D)

Related: https://stackoverflow.com/questions/5381399/how-can-i-prevent-a-ball-from-sticking-to-walls-in-box2d
> 1 votes

---
Tags: java, libgdx, jbox2d, bug
---


title: Handling variable frame rate in SDL2

text:
# Question
Title: Handling variable frame rate in SDL2
i am creating a game with C++ and SDL2 game engine but i noticed this. I used the Vsync option for rendering, so it'll render at 60fps. If i use this game with another monitor, fps are different (for example 75). I understood that this depends by the monitor frame rate. My monitor is 60Hz and the other is up to 75Hz. The problem is if i disable the Vsync option, Rendering will be accelerated. Fps will increase up to 200 or will be unstable.

Sorry if my english is bad but for example this: I want a block moving 5 pixels per frame. If i have a slow pc the block will move slow. If i have a fast pc the block will move fast.

So i searched for Frame Independent Movement and i pick up this:

```
movementPerSecond * (timeElapsedInMilliseconds / 1000.0)

```

I got this formula but i don't know what to use for "movementPerSecond" if i want the same velocity as before. That block will not move 5 pixels per frame but some pixels per second. Before, frames were 60 so the blocks was moving 60\*5=300 pixels per second. 300 p/s should be this movement. I disabled Vsync and i tried to do this:

```
while(1) {
    ...
    // updating coords
    x += 300.f * (timer.get() / 1000.f);
    timer.start();
    // rendering..
    ...
}

```

i was thinking that this was correct but velocity is faster than before. In some frames, the block doesn't go. i use timer.get() to get the time elapsed since i used timer.start(); i tried to print to the console these values and i got (1, 2, 0, 1, 1, 0, 2, 1). So i think time in one frames is about 1ms. I think however that if milliseconds are 0, movement variation will be 0.. (300\*(0/1000) = 0).

I hope you understand what i'm telling. What should i do? Thanks

# Answer
The most consistent way to do this is to use a fixed time step for your game logic. This avoids game logic oddities due to rounding errors when frame rate changes (collisions or events that don't happen or happen too often).

## Fixed Step:

A typical fixed step loop would look like:

```
Uint32 time_step_ms = 1000 / fps_the_game_was_designed_for;
Uint32 next_game_step = SDL_GetTicks(); // initial value

while(!quit){
  Uint32 now = SDL_GetTicks();

  // Check so we don't render for no reason (unless vsync is enabled)
  if(next_game_step <= now || vsync_enabled){

    int computer_is_too_slow_limit = 10; // max number of advances per render, adjust this according to your minimum playable fps

    // Loop until all steps are executed or computer_is_too_slow_limit is reached
    while((next_game_step <= now) && (computer_is_too_slow_limit--)){
      AdvanceGameLogicBy1Step();
      next_game_step += time_step_ms; // count 1 game tick done
    }

    RenderGame();
  } else {
    // we're too fast, wait a bit.
    if(be_nice_and_dont_burn_the_cpu){
      SDL_Delay(next_game_tick - now);
    }
  }
}

```

If you have `vsync_enabled` you don't need `SDL_Delay` as the game will (should) wait for the vsync to happen. So we're counting on the graphic drivers to do the wait for us even if we have to render extra identical frames.

`be_nice_and_dont_burn_the_cpu` is there to optionally disable the wait for systems where the granularity of `SDL_Delay` is 10ms, this can be turned off but will cause the game to busy-loop waiting, warming up the CPU and drain the laptop batteries.

Optional: `computer_is_too_slow_limit` is there in case the computer has a hiccup where the system hangs for a second or so. For offline games it's often a better user experience to slow down in extreme cases like this rather than skip ahead and end up killing the player.

## Variable Step:

Alternatively you can use variable delta-time game logic with a minimum of 1 millisecond:

```
Uint32 minimum_fps_delta_time = (1000/6); // minimum 6 fps, if the computer is slower than this: slow down.
Uint32 last_game_step = SDL_GetTicks(); // initial value

while(!quit){
  Uint32 now = SDL_GetTicks();

  // Check so we don't render for no reason, avoid having a 0 delta time
  if(last_game_step < now){

    Uint32 delta_time = now - last_game_step;

    if(delta_time > minimum_fps_delta_time){
      delta_time = minimum_fps_delta_time; // slow down if the computer is too slow
    }

    AdvanceGameLogicBy(delta_time);

    last_game_step = now;

    RenderGame();
  } else {
    // we're too fast, wait a bit.
    if(be_nice_and_dont_burn_the_cpu){
      SDL_Delay(1);
    }
  }
}

```
> 7 votes

---
Tags: c++, sdl2, c, frame-rate, vsync
---


title: Turret aiming code

text:
# Question
Title: Turret aiming code
I'm currently working on turret aiming code. If I can't hit the center of the object (due to an obstacle), I want to see if I can hit any of the object. To do this i'll get it's bounds, and check in between that range instead of doing a full 360 sweep. I can calculate 1 and 2 (sort points by angle to turret/blue dot), but how do I ensure I get sweep A and not B?

# Answer
I was origionally going to post Brams answer, however I forgot that you are already pointing at the center, and we can use the knowledge of point 1 and point 2 to our benefit.

If your turret is already aiming at the center of the object, no complicated angle math is necessary at all.

You know point 2 is to the right (with respect to your turret) and point 1 is to the left. You simply will scan from the left angle, clock wise, to the right angle via subtracting some constant angle value to sweep, no need for any complicated logic, and no chance to accidentally go the wrong direction.
> 1 votes

# Answer
You always sweep over the smallest delta-angle.

There is always one delta which is smaller than 180° and one that is bigger than 180°.

In your example, one range is appr 90° and the other 270°.

That said, your original problem of hitting partly obscured objects can also be handled in a simpler and more elegant way:

Every frame, pick a random point on the target, and check for visibility. If it is visible, you can aim for it and shoot. If it is not visible, then next frame you may be more lucky in the choice of random spot on target.

This method is easier to implement, and will also generalize to 3D much better.
> 0 votes

---
Tags: vector, linear-algebra
---


# Question
Title: SVG textures for 3D game objects in Unity?
Is there a way to make textures using vector graphics and use it for 3d models so that textures would be object size independent and won't get blurry?

# Answer
Possible? Sure, all you would need to do is implement a custom pixel shader which can renders SVG files instead of using an albedo texture.

Is it a good idea? Likely not, because vector graphics are usually not rendered pixel-by-pixel but shape-by-shape. GPUs are not optimized for that. I doubt you would manage to achieve a passable performance, even with very trivial SVGs.

It would very likely be a better idea to just use higher resolution textures. If you want to use vector graphics just to save file space (would of course only work if your textures are of an aesthetic which is expressed well in vector graphics) you could render the SVGs to textures at game start.
> 3 votes

---
Tags: unity, textures
---


# Question
Title: Browser game - small models with tileable textures vs one big model and one big texture
I am few years behind in terms of browser capabilities. I plan to combine 3D with pixel art, and I am going to use Unity to make a browser based game.

I have made a stage that is one model and has around 1k poly's. Then I made a large 2048x2048 texture for it. Lots of that texture is tileable, I'd say that I could fit unrepeated parts on a 256x256 texture while the rest is just repeated content. This looks like a huge waste when I just tile it manually in photoshop on a big texture file and I feel like I am doing something "dirty".

But when I would split that one model into 100 models and tile them separately with 32x32 textures, that would make more sense, but would increase model count from 1 to 100.

What is the correct way to do this? Lots of models with tiled textures, or screw it and make one big model with one large texture? Or maybe performance now is so great I don't even need to care and just do whatever?

Thanks

# Answer
> 2 votes
It's almost always better to have one model; that's mostly because GPUs are optimized for pushing lots of polygons in a small number of draw calls. Indeed, a common optimization when there are lots of little models in a scene is to combine them all into one (generally referred to as "batching" or "baking" the meshes).

I do want to respond to this:

> Lots of that texture is tileable, I'd say that I could fit unrepeated parts on a 256x256 texture while the rest is just repeated content

Assuming the mesh is tessellated in areas where the texture repeats, you simply arrange the UVs so those polygons share the same space on the texture. Boom, that portion of the texture is now tiled over the mesh.

In other words, tiling the texture is about manipulating the UVs on a single model, not making lots of separate models. Now you get a smaller texture and it's still only 1 object.

---
Tags: unity, textures, performance, low-poly
---


# Question
Title: How to make neon lightning effect in unity 3d
How can i Create Neon Lighting effect in unity 3d ,

so i have 2d scene and i want the rect to glow like neon

# Answer
> 2 votes
You could achieve the neon light effect in two different ways, depending on your lighting. If in your game you use static baking with lightmaps you could use an "emissive shader", if you want to use realtime lighting with realtime shadows, you can use an emissive shader or an unlit one, and with pointlights or a spotlight. If you dont want to do everything by yourself there is also this package

# Answer
> 1 votes
A simple way to perform a glow, particularly in 2D, is to make a blurred copy of your image and then blend it with the original image. You can use either a normal blend with a 50/50 mix between the original image and the blurred image, or you can use an additive blend. It can be helpful to threshold the original image before blurring it if you want only the brightest parts to glow. You can also give it a color cast before the glow if you want the glow to be a particular color.

# Answer
> 1 votes
Here I'm answering my question.

0. copy the following shader and create a new Shader ;

```
 Shader "Glow" {
     Properties {
         _MainTex ("Texture", 2D) = "white" {}
         _Color ("Color", Color) = (1,1,1,1)
         _Glow ("Intensity", Range(0, 3)) = 1
     }
     SubShader {
         Tags { "Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Transparent" }
         LOD 100
         Cull Off
         ZWrite On
         Blend SrcAlpha OneMinusSrcAlpha

         Pass {
             CGPROGRAM
                 #pragma vertex vert
                 #pragma fragment frag

                 sampler2D _MainTex;
                 half4 _MainTex_ST;
                 fixed4 _Color;
                 half _Glow;

                 struct vertIn {
                     float4 pos : POSITION;
                     half2 tex : TEXCOORD0;
                 };

                 struct v2f {
                     float4 pos : SV_POSITION;
                     half2 tex : TEXCOORD0;
                 };

                 v2f vert (vertIn v) {
                     v2f o;
                     o.pos = mul(UNITY_MATRIX_MVP, v.pos);
                     o.tex = v.tex * _MainTex_ST.xy + _MainTex_ST.zw;
                     return o;
                 }

                 fixed4 frag (v2f f) : SV_Target {
                     fixed4 col = tex2D(_MainTex, f.tex);
                     col *= _Color;
                     col *= _Glow;
                     return col;
                 }
             ENDCG
         }
     }
 }

```
1. create new material now select that shader from shader dropdown;
2. apply on your object;
3. import post-processing from asset store;
4. create new post-processing profile in project;
5. now select camera type post-pro and you get that script drag and drop your profile in it;
6. select bloom in profile and bam you are all done.

---
Tags: unity, lightmap
---


# Question
Title: Random Direction Vector Relative To Current Direction
I have a 2D vector where the x and y values are randomly generated using a range between -1 and 1 respectively. I use this as the direction to move an object in which works great.

```
var direction = Vector2(Random.Range(-1f, 1f), Random.Range(-1f, 1f));

```

What I would like to do is after some period of time, randomly generate a new direction vector, but this time keep the same "relative" direction that it currently has. Probably within 45 degrees or so on either side of the current direction.

So I'd like to randomly generate a new direction vector within a range of 45 degrees on either side of it's current direction vector, and start moving in that new direction. Does that make sense?

I'm not quite sure how to go about this, but I'm sure this isn't too difficult if someone could help get me started. Thanks!

# Answer
# Random direction relative to current direction:

Assuming you already have an initial `direction` vector prepared, as per DMGregory's comment on the OP:

1. Generate a random float that will represent the angle to change the direction by. Since the angle should be constrained to a 90 degree arc "forward" of the initial direction, we restrain the range of the random value to be from `-45` to `45`:
    * `var angle = Random.Range(-45f, 45f);`
2. Since you're working with 2D rather than 3D, the axis used for the rotation necessary for the new angle is already known: Z. Because of this, a cross-product calculation is unnecessary.
3. Unity already implements rotation matrices, in the form of the `Quaternion` class. Since the rotation is done through the Z axis, we can generate the quaternion for the rotation using the `Euler()` static method.
    * `var quaternion = Quaternion.Euler(0, 0, angle);`
4. Finally, we multiply the `quaternion` by the original direction vector, to get a new, rotated vector:
    * `var newDirection = quaternion * direction;`
    * **Important note:** To rotate a vector by a quaternion, it's important that the quaternion always comes first in the multiplication.
5. Now that each step of the operation is clear, we can simplify it by making it inline:
    * `direction = Quaternion.Euler(0, 0, Random.Range(-45f, 45f)) * direction;`

---

# Extra:

If you intend to "stack" these operations on top of each-other, it's important to note that the constraint will be relative to the current direction **in the current step**, and so, overall, the 90 degree cone might not be respected; in fact it's hypothetically possible to get a 90 degree *turn* (180 cone) with two operations, a full "U-turn" with 4, and a circle with 8.

To get consecutive operations to always generate new angles within the initial 90 degree cone, you need to make the constraint be determined relative to the current step's angle with respect to an "ideal" direction (the initial direction, in this case):

```
var point = Vector2.zero;
var idealDirection = Vector2.up;
var direction = idealDirection;
for(var i = 0; i < 10; i++){
    var constraint = Vector2.SignedAngle(direction, idealDirection);
    direction = Quaternion.Euler(0, 0, Random.Range(-45f + constraint, 45f +
 constraint)) * direction;
    var newPoint = point + direction;
    Debug.DrawLine(point, newPoint, Color.yellow, 1f);
    point = newPoint;
}
//Done this in cellphone, from memory, but hopefully creates something resembling a directional "lighting bolt".
//It should work, but if I made any mistakes due to lacking VS's intellisense, do tell!
//And regardless of that, the most important: Have fun!

```
> 6 votes

# Answer
I've done this, and its not too hard.

1. Firstly, generate a random non 0 length vector. Normalise it.
2. Cross product with your current direction vector to create a rotation axis.
3. Generate a random value in your -45 to 45 degree range (radians usually I do!)
4. Depending on your flavour, I usually generate a matrix with the angle and the rotation matrix.
5. Multiply your direction vector with said matrix.

Im sure someone has a better method, but this is what I have done in past.
> 2 votes

---
Tags: unity, vector, random, direction
---


# Question
Title: Seeking to streamline message system in my engine (C++)
So been building up my own custom engine, and one core bit of it is a message system to keep all the systems disconnected.

As it currently stands I have it take in a pointer to every other system, and then during their creation they register with the message system for what they want to receive.

The problem is the message system right now knows exactly what each system is, and I would like to simplify that.

My goal is to have any system sign up for messages, without the message system needing to care about the type of system. I thought about adding a "message class" parent class wrapper to put around every system, but that feels more like a jury rig then a fix, and I would like to avoid having layers of class wrappers.

Anyone have any thoughts how to simply this?

# Answer
> 2 votes
Usually messaging systems work by having a message receiving interface that other classes can implement if they want to receive messages. It can be something simple like this:

```
class MessageHandler {
    public:
        MessageHandler();
        ~MessageHandler();

        virtual void MessageHandler::handleMessage(MessageType msg, MessageSender* msgSender, void* msgData) = 0;
};

```

You can make any class be able to receive messages by inheriting from this base class and implementing the above method.

You can make a `MessageDispatcher` object that allows any object to register itself with the dispatcher. Something like this:

```
class MessageDispatcher {
    public:
        MessageDispatcher();
        ~MessageDispatcher();

        RegisterMessageHandler(MessageHandler* newHandler, MessageType msg);
        DispatchMessage(MessageType msg, MessageSender* msgSender, void* msgData);
};

```

Generally, the MessageDispatcher is a singleton, though it's certainly possible to have different dispatchers for different parts of your system, if that would be more efficient or appropriate. In any case, when you create any object that you want to be able to receive messages, you simply call:

```
msgDispatcher.RegisterMessageHandler(this, whateverMessage, msgData);

```

And when you have a message you want to send, the sender can do this:

```
msgDispatcher.DispatchMessage(whateverMessage, this, msgData);

```

With this system, any object can sign up for messages without knowing or caring about any of the other objects types or systems. (Though they will have to agree on what data goes with what message type so they can communicate.)

---
Tags: c++, messaging
---


title: How to disable spring joint in unity 3d

text:
# Question
Title: How to disable spring joint in unity 3d
How can I disable Spring joint in unity 3d, since disabling feature only available in 2d mode, I am not able to find any way to disable it via script

# Answer
According to this thread on Unity forums, there's no way to disable a spring joint other than to break it and re-connect it. Quoting from the forum thread in Unity:

> I was able to create a JointToggler component that finds a joint on the same object and connects/disconnects the connectedBody rigidbody when it is enabled/disabled (like Joints should do by default).

This is the relevant code supplied in the quoted post: using UnityEngine;

```
public class JointToggler : MonoBehaviour
{
   [SerializeField] private Joint joint;
   private Rigidbody connectedBody;

   private void Awake()
   {
       joint = joint ? joint : GetComponent<Joint>();
       if (joint) connectedBody = joint.connectedBody;
       else Debug.LogError("No joint found.", this);
   }

   private void OnEnable() { joint.connectedBody = connectedBody; }

   private void OnDisable()
   {
       joint.connectedBody = null;
       connectedBody.WakeUp();
   }
}

```

I'd normally downvote a question like this for lack of research, since the first google result of `disable spring joint unity` gave me what I needed, but I couldn't find anything like the sort here, so I'm putting this answer here for archiving purposes.
> 1 votes

---
Tags: unity
---


# Question
Title: Tile detection on a 2D isometric layered diamond shaped map - What are the math?
**What are the math for tile detection on a 2D isometric layered diamond shaped map ?**

Here is an image of a layer (this is an image from an old folder, I didn't write the display yet for my current project, so it's incomplete but you get the idea) :

A layer

*I have them staggered on top of each other. Tile detection could works with a loop but it would take too much time. The basic math for floor tiles doesn't work.*

**A layer is composed of a tiles(array) :**

A tile\_size * tile\_size image representing a 3D square.

---

A long time ago I asked this question with an account I'v lost unfortunatly and I had one answer :

* Create an hollow ground

But I never understood what that was and when I type "tile detection hollow ground" on google, I got nothing.

I also found several solution I do not understand the concept :

* Ray scan on neightbours (I know the theory for ray scanning, but neightbours ??? All of that sounds very difficult for me)
* using color mask for a pixel perfect detection (no time to implement such a method)

So, was left the math. And here I'm stuck. I'm looking at my formula 'isometric to screen' conversion(for display), hoping a miracle ha ha :

```
int x = (i - j) * TILE_SIZE_HALF,
    y = (i + j) * TILE_SIZE_QUARTER - (layer_id * TILE_SIZE_HALF);
//This one is totally working

```

Anyway, is there even a formula able to solve tile detection for such a map ? Am I missing something ?

**What I'm looking for :**

```
   //With given x & y (mouse coordinates on screen)

    int i = ?,
        j = ?,
        layerID = current_layer_index,
        //tile's index in tile array(layers are tile arrays) :
        tileIndex = calculated from I & J;
        //Where goes the offsets in these calculations ?

```

**How am I gonna know which layer the tile is from ?**

I decided to only edit the selected layer (current\_selected\_layer variable) and then check if the tile is empty. If yes, I'll select the "same tile" but the layer under the selected one and so on. **Now the problem should be less complicated since it's like there is only one layer. What bother me are the map offsets.**

EDIT : I didn't tought about the corner... This is not gonna work. If I don't find a solution, I'll maybe switch to classic 2D. Sounds very complicate to code tile selection with isometric map.

**There is another problem I have no idea how to handle these :**

*(this is a layered map, the screen do not represent the final result)*

**End note:** *Pseudo code is welcome. Also, consider you have all informations about the map. Since I use a pseudo MVC code, I have access to all data everywhere (tile size, layers number, etc...). There is no restriction.*

# Answer
The isometric stuff is just a projection, based on that, you have to unproject your mouse coords.

the following code is in pseudo javascript:

```
var x = MOUSE_X,
    y = MOUSE_Y,
    retX = 0,
    retY = 0;

    retX = Math.round(x / TILE_WIDTH) * TILE_WIDTH;
    retY = (Math.round(y / (TILE_HEIGHT/2)) - 1) * TILE_HEIGHT/2;

    if ((Math.round(y / (TILE_HEIGHT/2)) - 1) % 2) {
       retX -= (TILE_WIDTH/ 2);
    }

```

In this case, mouse coords are unprojected from isometric ones, so you can, after this, request your tile by doing:

`map[retx + MAP_WIDTH * rety]` (1D Array)

`map[retx][rety]` (2D Array)
> 1 votes

# Answer
Not efficient, but accurate on complex structures, is drawing all cubes with a different color and no shade(r) onto a black background into a **framebufferobject** and later testing which color a given pixel has. You should draw the objects without blending and without texture into the buffer.

Another way is, you ray-trace until you reach a cube or a limit.
> 0 votes

# Answer
First, I'll deal with the simpler problem with the edge and corner of the map you showed above. For that, you will only be concerned with the top of the tile when a person selects it, so if they click on the outer edge along the side or corner of the tile, than they are out of bounds and clicking off the map. It doesn't matter than they click the side of a tile. I would reject such a click as out of bounds.

As for layer selection, this is something I struggled with as well, and still do a little, but I have come up with several ideas on this. One idea I had was to store the highest layer on your map. Then when you click, you check to see if there is a tile at that location on the highest layer, so basically, take your normal flat selection, and offset it by the height of the layer; so, if your layers are all 16 pixels higher for each layer, than you would do your normal detection, except you would adjust the Y location by -16 * LAYER. You check the highest layer where the mouse clicked, if there is no tile at that height at that location, than check the next layer down until you end up at the ground level.

That was one idea anyhow. The other idea was to use mouse maps to determine if the tile you selected was the right one, of if you're clicking a tile next to it that is at a higher level.
> 0 votes

---
Tags: 2d, mathematics, maps, isometric, coordinates
---


# Question
Title: How to mouse click an object in scene view to select it from editor
I have several game objects with colliders in my game. I have enabled `Always Show Colliders` to keep all of them visible in my scene view. Because the objects are a lot, selecting them from the hierarchy window is a bit cumbersome and really slowing down my workflow. How can I select an object by left mouse clicking on it in the scene view of an editor?

# Answer
If you want to be able to select colliders without adding any sort of mesh to them, then you can call an icon draw `OnDrawGizmos()` on a script and just add it to whatever you want to be drawn:

using System.Collections;

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

public class DrawIcon : MonoBehaviour {
    void OnDrawGizmos()
    {
        Gizmos.DrawIcon(transform.position, "Collider Gizmo.tiff", true);
    }
}

```

You can also then select a shape / color combo from the gizmos menu for `DrawIcon` in this case.

Clicking on it will select the relevant object:

Experiment with the code to customize it.
> 1 votes

---
Tags: unity
---


# Question
Title: libGDX - orthographic camera and world units
I've followed the advice in this post to handle world/screen coordinates, but I'm getting results I don't quite understand, as I'm not terribly good in math.

So, when I use this code:

```
SpriteBatch batch;
OrthographicCamera camera;
public static float width = 0, height = 0;

private void setupGraphics(SpriteBatch batch) {
    height = Constants.TILES_Y; // 20
    float pixelsPerUnit = Gdx.graphics.getHeight() / height;
    width = Gdx.graphics.getWidth() / pixelsPerUnit;
    Gdx.app.log("debug", "Width: " + width + " height: " + height + " ppu: " + pixelsPerUnit);
    camera = new OrthographicCamera(width, height);
    camera.position.set(0, 0 / 2, 0);
    camera.update();
    batch.setProjectionMatrix(camera.combined);
}

```

...the result looks like this - it seems that the view height is now 20 pixels, not 20 32x32 tiles:

However, when I add a multiplier to the height, like 16, the result looks like this, which is more like what I want:

Here's the changed code:

```
    height = Constants.TILES_Y * Constants.TILES_MULTIPLIER; // 20 * 16

```

How would I modify the code to avoid having to supply the multiplier every time when I handle coordinates?

# Answer
Thanks to @MrIlliteracy for the extensive answer. I finally managed to wrap my head around this, I got it to work by setting the target width and height to 1 unit in my rendering method, like this:

```
public void render(SpriteBatch batch, Point location) {
    if(tileset != null) {
        batch.draw(
                tileset, // a libGDX Texture
                location.getX(),
                location.getY(),
                1, 1, // ADDED THESE
                (int)bottomLeft.getX() * Constants.TILE_DIM,
                (int)bottomLeft.getY() * Constants.TILE_DIM, Constants.TILE_DIM,
                Constants.TILE_DIM,
                false, false // flips to get the right method overload
        );
    }
}

```

The program now looks like this:
> 0 votes

# Answer
I would recommend re-reading the post as I don't think you completely understand why you're setting up an orthographic camera.

The whole point of this is to move *away* from pixels and move towards your own unit that doesn't depend on screen size. This way, everything can be properly scaled no matter the device.

`it seems that the view height is now 20 pixels, not 20 32x32 tiles:` \- It's not 20 pixels, it's 20 units high. As I said above, these units are basically your new pixels that scale with the device's screen.

To answer your question, `How would I modify the code to avoid having to supply the multiplier every time when I handle coordinates?`, the answer is: you don't.

There are other things you can do though like have your tile rendering method take in a coordinate in "tiles coordinates" and then it multiplies by the tile size when you draw it.

Here's a little diagram I drew up quickly to explain it graphically.
> 2 votes

---
Tags: java, libgdx, camera, projection-matrix
---


title: How can I play audio instantly in Java?

text:
# Question
Title: How can I play audio instantly in Java?
I know JavaSound API like this:

```
audioInputStream = AudioSystem.getAudioInputStream(file);
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info info = new Info(SourceDataLine.class, audioFormat);
sourceDataLine = (SourceDataLine) AudioSystem.getLine(info);
sourceDataLine.open();
sourceDataLine.start();
floatVoiceControl.setValue(-20);
byte[] buf = new byte[0xFF];
int onceReadDataSize = 0;

```

While `file` is the `File` object.

But when I tried to play some very small audio very frequently (say, the audio played when a small enemy is killed), it blocks my main thread and make the game very slow.
Is there any alternative or workarounds? I prefer something inside the Java's standard library, since I'm developing a game engine based on Swing.

# Answer
> 2 votes
From the code you provide it is not discernible if you run the sound on your main-thread or on a worker thread. I will just assume that you are using a `ThreadPoolExecutor` or similar so you don't have to expensively create a new thread every time you want to play some sound.

From reading the Javadoc of the DataLine Interface I understad that the `start()` method you use in line #6 of your codesample initiates some I/O operations for reading the audiodata from the underlying file:

> Allows a line to engage in data I/O.

Excerpt from the javadoc of the `start()` method

Digging further into the javax soundAPI sources we find that the implementation of `AudioSystem.getAudioInputStream(File)` works with a list of `AudioFileReader`s for which there are no *known implementations*, which means without knowing what sort of audio-file you're trying to load we cannot reasonably dig any much further.

---

**Conclusion**:

From our research into the APIs and sources, and from your statement that:

> But when I tried to play some very small audio very **frequently**...

**emphasis** mine

We can reasonably assume that you're getting limited by I/O operation limitations. You might want to see if you can load the sound-file into the heap and play it from memory instead of playing it from disk.

---
Tags: java, audio, music
---


# Question
Title: Why do I get this compile error when using InputComponents in UE4?
I'm following this documentation, but it doesn't compile cause of "InputComponent". Unfortunately the error is not that clear even in my language.

Here's the error:

> CompilerResultsLog: Error: C:\Users\Paradisee\Desktop\C++\Paper\Source\Paper\PlayerTile.cpp(83) : note: I tipi a cui si punta sono privi di relazioni. La conversione richiede reinterpret\_cast, cast di tipo C o cast di tipo funzione CompilerResultsLog: ERROR: UBT ERROR: Failed to produce item: C:\Users\Paradisee\Desktop\C++\Paper\Binaries\Win64\UE4Editor-Paper-583.dll

Here's the code:

```
// Called to bind functionality to input
void APlayerTile::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
    Super::SetupPlayerInputComponent(PlayerInputComponent);

    // Respond every frame to the values of our two movement axes, "MoveX" and "MoveY".
    InputComponent->BindAction("MoveX", IE_Pressed, this, &APlayerTile::MoveX);
    InputComponent->BindAction("MoveY", IE_Pressed, this, &APlayerTile::MoveY);
}

```

This is the definition of the method MoveX():

```
void APlayerTile::MoveX(float AxisValue)
{

}

```

# Answer
`BindAction` expects to take a `FInputActionHandlerSignature::TUObjectMethodDelegate<UserClass>::FMethodPtr` as the last parameter. This is, basically, a function that takes no arguments and returns nothing. In other words, something like:

```
void APlayerTile::MoveX() {
  ...
}

```

You're giving it a function that takes a float parameter:

```
void APlayerTile::MoveX(float AxisValue) {
  ...
}

```

Pointers to those functions don't match because they have different signatures, and cannot be implicitly converted. The error is telling you that: that if you want to force this conversion you must use a C-style cast or a `reinterpret_cast`, which would make the code compile (but crash or otherwise misbehave at runtime, so that's not a solution).

You either need to change your `MoveX` so it doesn't take a parameter, or use `BindAxis` to bind it instead of `BindAction`. `BindAxis` is for "axis" inputs, which have a value associated with them representing their current state. `BindAction` is for "action" inputs, which don't have continuous values but rather are either "pressed" or "released."
> 0 votes

---
Tags: c++, unreal-4
---


title: Add image to button in unity

text:
# Question
Title: Add image to button in unity
Sorry if this question has already an answer somewhere, but I've just started to play with Unity and now I'm stuck. :(

I've tried a few things ( from here , here and here and others ) but none of them work, I'm sure that I do something wrong but I don't know what.

I have this code:

```
public class SceneManager : MonoBehaviour {

    public Image myButtonImage;
    private Button switchBtn;

    // Use this for initialization
    void Start () {

        switchBtn = GameObject.Find("switchBtn").GetComponent<Button>();
        myButtonImage = Resources.Load<Image>("switchCameraImg");

        switchBtn.image = myButtonImage;
    }
}

```

and this are my objects:

where `cameraSwitchObj` is a `GameObject` and `switchBtn` is the button itself.

`SceneManager` is the script attached to `MainCamera`

I receive this error :

```
NullReferenceException: Object reference not set to an instance of an object SceneManager.Start ()

```

for this line : `switchBtn.image = myButtonImage;` but according to what i read from different posts this is all i must do. What I am missing?

# Answer
> 1 votes
You didn't show what is switchCameraImg in your assets folder. Also is this asset in your "Resources" directory?

Afaik, you cannot load Image via Resources.Load method. But you can load a Sprite, and next set a sprite of Image as loaded component.

Try this:

```
myButtonImage.sprite = Resources.Load<Sprite>("someGraphics");

```

Where the sprite is an graphics, for example in ".png" extension, with Texture Type option set as "Sprite (2D and UI)":

# Answer
> 0 votes
In Unity 2017.2, Button already supports an images through the `Target Graphic` field.

Typically this is a 9-Patch image, but it's easy to turn an image into a 9-patch.

See the documentation for Button.

---
Tags: unity
---


# Question
Title: How to get the loudness of the real world environment using the device's microphone in Unity?
I am trying to create a game where the character's movement is dependent on the loudness of the real world environment. So if the person playing the game screams or do something loud the character will move accordingly.

What I need is a function returning the loudness of the real world environment and use it in the Update() to control the character.

Is there such a function or if not how can I make one?

# Answer
> 4 votes
As mentioned by Philipp, The `Microphone` class is indeed what you want to use.

The `AudioClip` that it produces is your audio buffer. When you call the `Microphone.Start()` method, you are opening the connection to the physical microphone, and the `AudioClip` is where the input is stored for you to access the sounds.

The `Microphone.Start()` method has a parameter `loop` which tells the `Microphone` to continue recording over the beginning of the `AudioClip` when the `lengthSec` is reached.

So as a quick and dirty example:

```
using UnityEngine;
using System.Collections;

public class MicrophonePoll : MonoBehavior {
    private AudioClip clip;
    private float[] samples;

    void Start()
    {
        //Start recording 1 second blocks of audio from the default microphone, and loop the recording
        clip = Microphone.Start(null,true,1,44100);
    }

    void Update()
    {
        if(clip!=null)
        {
            //Sample from the AudioClip to determine how loud the room was over the last second of recording
            if(samples == null)
            {
                samples=new float[clip.samples*clip.channels];
            }
            clip.GetData(samples,0);
            foreach(float sample in samples)
            {
              //do something with the value (ranges from -1.0f to 1.0f)
            }
        }
    }
}

```

---
Tags: unity, sound
---


title: Camera rotation deforms objects

text:
# Question
Title: Camera rotation deforms objects
I'm working on a ray-tracer in C++ with an adjustable camera for a university assignment. I'm entirely new with graphics and I'm struggling with one thing.

I have a matrix as a mat4 object (4x4 matrix with each cell saved in a 1D array) that I save in a Camera object that handles transformations of every point in the scene (which is currently just two spheres). Translations seem to be working fine, but when I attempt rotations, things break. The spheres deform, and it only gets worse the more I attempt to rotate the camera.

This is where I set the camera matrix:

```
mat4 Renderer::setCameraMatrix(const Camera &camera)
{
    mat4 cameraToWorld = mat4(); // Initialise 4x4 matrix.

    // Translation.
    cameraToWorld.cell[3] = camera.pos.x;
    cameraToWorld.cell[7] = camera.pos.y;
    cameraToWorld.cell[11] = camera.pos.z;

    // Rotation.
    cameraToWorld.cell[0] = camera.orientmat.cell[0], cameraToWorld.cell[1] = camera.orientmat.cell[1], cameraToWorld.cell[2] = camera.orientmat.cell[2];
    cameraToWorld.cell[4] = camera.orientmat.cell[4], cameraToWorld.cell[5] = camera.orientmat.cell[5], cameraToWorld.cell[6] = camera.orientmat.cell[6];
    cameraToWorld.cell[8] = camera.orientmat.cell[8], cameraToWorld.cell[9] = camera.orientmat.cell[9], cameraToWorld.cell[10] = camera.orientmat.cell[10];

    return cameraToWorld;
}

```

This matrix is then used to set the origin and direction of the camera in the world space later on in the code:

```
vec3 orig = transformpoint(vec3(0), cameraToWorld);
/*...*/
vec3 dir = transformvector(vec3(x, y, -1), cameraToWorld) - orig;
dir.normalize();

```

The transformpoint and transformvector functions basically multiply a vector v by a matrix M (M.v), except the former takes into consideration translations, and the latter doesn't. Their code can be found here.

The orientmat matrix is calculated from the three separate orientation angles (orient.x, orient.y, orient.z) in this line of code:

```
cam->orientmat = mat4().rotatexyz(cam->orient.x, cam->orient.y, cam->orient.z);

```

Using this function:

```
mat4 mat4::rotatexyz(const float a, const float b, const float c)
{
    mat4 M;
    const float ca = cosf(a), sa = sinf(a);
    const float cb = cosf(b), sb = sinf(b);
    const float cc = cosf(c), sc = sinf(c);

    M.cell[0] = cb * cc, M.cell[1] = -1 * cb * sc, M.cell[2] = sb;
    M.cell[4] = sa * sb * cc + ca * sc, M.cell[5] = -1 * sa * sb * sc + ca * cc, M.cell[6] = -1 * sa * cb;
    M.cell[8] = -1 * ca * sb * cc + sa * sc, M.cell[9] = ca * sb * sc + sa * cc, M.cell[10] = ca * cb;

    return M;
}

```

(This function basically creates this transformation matrix from the three camera orientation angles.)

I've tried to keep this question as compact as possible but I can provide more code if needed. I'm completely baffled about why I'm getting this kind of deformation on my spheres, and some insight would be invaluable! Thanks.

# Answer
> 1 votes
Well, first off, unlike transformation and scale, you can't just combine orientation matrices in order to get a real orientation matrix out. You have to apply the orientation matrices with respect to a single axis, apply them separately, or use a single complex valued quaternion matrix. You may be getting into something called a gimbal lock or some other strange positional artifact in combination with other bugs in your code.

***Since your Y rotation doesn't change after going the other direction if you look at your gif, I suspect there is a bug in the code you aren't showing us, probably not updating rotation when going the opposite direction.***

The easiest way to avoid gimbal locking is to just rotate with respect to each axis individually, something like this:

```
// because I don't want to use silly linear indexing
class mat3 : ...{
    ...
    // incase of inheritance
    int width(){
        return 3;
    }
    int height(){
        return 3;
    }
    // can put this in parent class if inherits width and height functions
    float& operator () (int row, int col){
        // if m_array is row ordered
        int linear_index = row * width() + col;
        // if m_array is column ordered
        int linear_index = col * height() + row;

        assert(linear_index < (width()*height()));

        return m_array[linear_index];
    }

    // duplicated for const usage
    const float& operator () (int row, int col) const{
        // if m_array is row ordered
        int linear_index = row * width() + col;
        // if m_array is column ordered
        int linear_index = col * height() + row;

        assert(linear_index < (width()*height()));

        return m_array[linear_index];
    }
    ...
};

...

mat3 mat3::xAxisRotMat(const float radians){
    //from https://stackoverflow.com/questions/14607640/rotating-a-vector-in-3d-space
    mat3 m;

    float cos_rad = cosf(radians);
    float sin_rad = sinf(radians);

    m(0,0) = 1;
    m(0,1) = 0;
    m(0,2) = 0;

    m(1,0) = 0;
    m(1,1) = cos_rad;
    m(1,2) = -sin_rad;

    m(2,0) = 0;
    m(2,1) = sin_rad;
    m(2,2) = cos_rad;
}

mat3 mat3::yAxisRotMat(const float radians){
    //from https://stackoverflow.com/questions/14607640/rotating-a-vector-in-3d-space
    mat3 m;

    float cos_rad = cosf(radians);
    float sin_rad = sinf(radians);

    m(0,0) = cos_rad;
    m(0,1) = 0;
    m(0,2) = sin_rad;

    m(1,0) = 0;
    m(1,1) = 1;
    m(1,2) = 0;

    m(2,0) = -sin_rad;
    m(2,1) = 0;
    m(2,2) = cos_rad;
}

mat3 mat3::zAxisRotMat(const float radians){
    //from https://stackoverflow.com/questions/14607640/rotating-a-vector-in-3d-space
    mat3 m;

    float cos_rad = cosf(radians);
    float sin_rad = sinf(radians);

    m(0,0) = cos_rad;
    m(0,1) = -sin_rad;
    m(0,2) = 0;

    m(1,0) = sin_rad;
    m(1,1) = cos_rad;
    m(1,2) = 0;

    m(2,0) = 0;
    m(2,1) = 0;
    m(2,2) = 1;
}

```

Now where you would normally use your camera to transform the points (and I guess rotate?) use these matrices. Assuming your using the opposite transformation method to move the world around you, first create your translation matrix and your rotation matrix, and to rotate each of your points, first translating, and then rotating with each of the respective axis transformations, you should be using a total of 4 matrix multiplications per point.

I should also point out that translating the vector `[0,0,0]` by another vector `[x,y,z]` just returns `[x,y,z]`, because all a translation will do is add x, y, and z to the original xyz elements.

---
Tags: rendering, camera, rotation, matrix, raytracing
---


title: Entity-Component-System design

text:
# Question
Title: Entity-Component-System design
I read a lot about ECS (strategy) pattern and have a few questions. Consider simple space game.

1. We have stars there. Obviously star is an `entity`. What if I want to make a galaxy? It looks reasonable to make galaxy an `entity`. On the other hand galaxy is just a set of stars. In usual OOP design I would just made it a class which holds a list/vector of stars. Is it legial to make an `entity` which is just a container for other entities? Wouldn't it brake at some point?
2. Now consider planetary system. It looks like planet is an `entity` too. But it would be wise to link a planet to its parent star. May one entity refer to another (having pointer, or something like that)? How would you compose that?

Thanks in advance.

# Answer
This is an X Y problem. An entity component system is a sort of design pattern like you would find in typical software engineering. ***But entity component systems are meant to solve a certain type of problem***. The problem is one of dealing with objects with many components with unbounded complexity, such as RPG items having different effects and abilities, where inheritence would result in potentially hundreds or thousands of classes in order to encompass the complexity/ and/or constant downstream client side updates to actual code in order to add new items.

ECS is not a system meant to be used in simulation systems or games with unbounded number of entities (say thousands) in play at one time, where the number of entities is the dominating factor in performance. ***Entity component systems have a very real, very significant performance cost compared to just simple inheritance or composition, and the decision to use such a large system should not be taken lightly***. The cost of using ECS can be ignored when the number of entities is not the primary performance factor on your system. The use case for ECS is legitimized when you have a situation where "I need to be able to get a sword with 10 different elemental types on it and 10 other effects, or some combinations of a very large amounts of effects", not one where "I need to create a building".

This is a problem that not all games have, and given what you've said your problem is, is one you simply don't have. Additionally you can have ECS and ***not have every entity in your game live inside the ECS framework***. Some entities may be inside of ECS, while other, less versatile entities can just be plain entities which exhibit normal inheritance characteristics.

Your situation doesn't call for any of this complicated ECS stuff because you have a very small finite amount of entity types and a known configuration for each entity (they don't have dynamic components).

You have stars, planets, planetary system, galaxies. Galaxies contain solar systems, solar systems contain at least one star and 0 to 1 planets.

Stars have certain characteristics, and the list of those characteristics never change (temperature, size, etc...), planets are likewise the same. ***You don't need ECS to solve this problem, simple OOP design and arrays will solve your problem***.

So stay away from ECS for this part of your project, it won't solve your problem, and as you can see from even needing to ask this question, it will just make your life more difficult trying to fit it where it doesn't belong.
> 1 votes

# Answer
Why not give each star a galaxyid? If the entity is not a star, but e.g. an astronaut, set it to -1.

To find stars in a galaxy, just iterate over all entities and check the galaxyid. If this is expensive and has to be done frequently per frame, then just cache that info.

Your array with entities/stars will remain flat this way, and there will be no need to iterate over containers.

This makes the membership by a star of a galaxy to be an attribute of the star, as opposed to actual container data structures.
> 1 votes

---
Tags: c++, entity-system, design-patterns
---


# Question
Title: Get the up vector of the camera in ARKit
I'm trying to get the four vectors that make up the boundaries of the frustum in ARKit, and the solution I came up with is as follows:

* Find the field of view angles of the camera
* Then find the direction and up vectors of the camera
* Using these information, find the four vectors using cross products and rotations

This may be a sloppy way of doing it, however it is the best one I got so far.

I am able to get the FOV angles and the direction vector from the `ARCamera.intrinsics` and `ARCamera.transform` properties. However, I don't know how to get the up vector of the camera at this point.

Below is the piece of code I use to find the FOV angles and the direction vector:

```
func session(_ session: ARSession, didUpdate frame: ARFrame) {
  if xFovDegrees == nil || yFovDegrees == nil {
    let imageResolution = frame.camera.imageResolution
    let intrinsics = frame.camera.intrinsics
    xFovDegrees = 2 * atan(Float(imageResolution.width) / (2 * intrinsics[0,0])) * 180 / Float.pi
    yFovDegrees = 2 * atan(Float(imageResolution.height) / (2 * intrinsics[1,1])) * 180 / Float.pi
  }

  let cameraTransform = SCNMatrix4(frame.camera.transform)
  let cameraDirection = SCNVector3(-1 * cameraTransform.m31,
                                   -1 * cameraTransform.m32,
                                   -1 * cameraTransform.m33)
}

```

I am also open to suggestions for ways to find the the four vectors I'm trying to get.

# Answer
In a 4x4 transformation matrix, all directions are contained:

* First row of matrix contains the x-axis.
* Second row of the matrix contains the y-axis.
* Third row of the matrix contains the z-axis.
* Fourth row of the matrix contains the position/translation.

Looking at your code, -z is the direction the camera looks at. Most likely, the y-axis in that transformation is the vector that you are looking for.

```
SCNVector3( cameraTransform.m21, cameraTransform.m22, cameraTransform.m23 );

```
> 3 votes

---
Tags: camera, ios, swift, scenekit
---