title: How many shaders for my 2D game?

text:
# Question
Title: How many shaders for my 2D game?
My 2D OpenGL game is going to have 5 different types of objects I want to render.

-Text

-unTextured AABBs

-unTextured Polys

-Textured AABBs

-Textured Polys

Text will have its own shader and thats fine.

I want things to be simple to code but not insanely slow either. I'm willing to do a little bit of batching and texture atlasing for bulk things like Tiles which can be drawn all at once, but otherwise objects will be drawn in an unpredictable order and therefore requires some state switching.

Polys will need a matrix for rotation passed as a uniform but obviously AABBs won't. So I'm not sure if they need to be separate or not.

One way I thought of uses 3 shaders. One for text and two for rendering textured and untextured polys and AABBs. For AABBs I could just pass an identity matrix instead of a rotation matrix.

Another way just has 5 separate shaders.

I'm concerned with the amount of switching between different shaders I'll need to do since I already know my GUI renderer will have to switch between rendering text and AABBs (though I don't expect more than a few dozen total widgets and containers).

Since the tiles will be batched and are by far the most numerous object in my game, I expect an asbolute maximum of less than 150 different draw calls (with shader and texture switches).

Just wondering which approach between the two seems the most sensible or if there's another suggestion.

# Answer
> 1 votes
Why not use a single shader not only for polys and sprites, but also for textured and untextured objects?

You can do that if you pass *both* texture coordinates and color information into your shader, together with a coefficient controlling the proportion in which they should be mixed:

```
final_color = color * (1 - n) + texture2D(blah, blah) * n;

```

As a bonus, if you do that separately for RGB and alpha, it will allow you to add color overlay to your sprites as needed.

Here is a simplified version of the shader I'm currently using, adjusted for your purposes:

```
/* Vertex */

#version 330 compatibility

uniform mat4 u_matrix_view;
uniform mat4 u_matrix_model;

attribute vec2 a_position;
attribute vec4 a_color;
attribute vec2 a_tex_coord;
attribute float a_color_factor; // I used two separate float attributes for readability, but
attribute float a_alpha_factor; //   in reality you should merge them into a vec2.

varying vec4 v_color;
varying vec2 v_tex_coord;
varying float v_color_factor;
varying float v_alpha_factor;

void main()
{
    gl_FragCoord = u_matrix_view * u_matrix_model * vec4(a_position, 0, 1);
    v_color        = a_color;
    v_tex_coord    = a_tex_coord;
    v_color_factor = a_color_factor;
    v_alpha_factor = a_alpha_factor;
}

/* Fragment */

#version 330 compatibility

uniform sampler2D u_texture;

varying vec4 v_color;
varying vec2 v_tex_coord;
varying float v_color_factor;
varying float v_alpha_factor;

void main()
{
    vec4 tex_color = texture2D(u_texture, v_tex_coord);
    gl_FragColor.rgb = a_color.rgb * (1 - a_color_factor) + tex_color.rgb * a_color_factor;
    gl_FragColor.a   = a_color.a   * (1 - a_alpha_factor) + tex_color.a   * a_alpha_factor;
    // If you need premultiplied alpha: gl_FragColor.rgb *= gl_FragColor.a
}

```

Also, about the font shader: I assume you have a reason to make a separate shader for font rendering (are you using SDFs for them maybe?). But just in case your fonts are rendered as simple sprites, I'd consider using the same shader for them too.

---
Tags: opengl, 2d
---


# Question
Title: How do I offset a TouchPanel input in Monogame
I am creating my first 2D game in monogame. I have used RenderTarget2D to maintain a 4:3 aspect ratio. If it is played in a window of any other ratio it will offset the RenderTarget2D position to create a Letterbox black bar effect. I accomplish this with:

```
        Rectangle RenderArea;
        // Calculate target and current aspect ratios
        float outputratio = (float)Window.ClientBounds.Width / (float)Window.ClientBounds.Height;
        float targetratio = (float)Screen.Width / (float)Screen.Height;

        // Calculate rectangle on screen we will be drawing to
        if (outputratio <= targetratio)
        {
            // output is taller than it is wider, bars on top/bottom
            int currentheight = (int)((Window.ClientBounds.Width / targetratio) + 0.5);
            int barheight = (Window.ClientBounds.Height - currentheight) / 2;
            RenderArea = new Rectangle(0, barheight, Window.ClientBounds.Width, currentheight);
        }
        else
        {
            // output is wider than it is tall, bars left/right
            int currentwidth = (int)((Window.ClientBounds.Height * targetratio) + 0.5);
            int barWidth = (Window.ClientBounds.Width - currentwidth) / 2;
            RenderArea = new Rectangle(barWidth, 0, currentwidth, Window.ClientBounds.Height);
        }

```

(Screen being my RenderTarget2D)

I then draw my RenderTarget2D to this area on the screen. This works great. The only issue I have is how to get touch and mouse inputs offset to this location on the screen without having to offset my TouchPosition.Position.X and Y manually every time I check their position.

I have already set my TouchPanel virtual size with:

```
        TouchPanel.DisplayWidth = Screen.Width;
        TouchPanel.DisplayHeight = Screen.Height;

```

but I don't know of a way to offset the returned TouchLocation X and Y by my RenderArea X and Y.

Is there any way to accomplish this without manually offsetting every position check?

# Answer
> 1 votes
I have not gotten an answer for a while, so I will post what I came up with. Hopefully it helps someone else.

I stopped trying to manipulate the TouchPanel size as I discovered it keeps reverting back to the window size anyway. I wrote a method that all touch checks must run through:

```
    bool Touched(Rectangle target, TouchCollection touchcollection)
    {
        foreach (TouchLocation tl in touchcollection)
        {
            if (tl.State == TouchLocationState.Pressed &&
                ((tl.Position.X  - RenderArea.X) * ((float)Screen.Width / (float)RenderArea.Width)) > target.Left &&
                ((tl.Position.X - RenderArea.X) * ((float)Screen.Width / (float)RenderArea.Width)) < target.Right &&
                ((tl.Position.Y - RenderArea.Y) * ((float)Screen.Height / (float)RenderArea.Height)) > target.Top &&
                ((tl.Position.Y - RenderArea.Y) * ((float)Screen.Height / (float)RenderArea.Height)) < target.Bottom)
            {
                return true;
            }
        }
        return false;
    }

```

It offsets for the black bar based on the XY location of the already calculated RenderArea. It then calculates a multiplier also based on the already calculated RenderArea.

Seems to work well.

---
Tags: xna, monogame
---


title: Associating game object with some class

text:
# Question
Title: Associating game object with some class
Disclaimer: Somewhat long-winded question & new to developing

In my game I have a class called Item which defines what an item is. It contains several fields like the name of the item, the sprite of the item, the item's ID number, etc. I also have little physical objects on the ground that "represent" items, but they aren't really tied to the Item class in the way I want. I'll get back to this point.

So, when an enemy dies in my game, `SpawnItem(Item item)` is called. Depending on a randomly generated number, `SpawnItem(ItemData.sword)` might be called or `SpawnItem(ItemData.axe)` and so forth. **SpawnItem** itself just instantiates a generic prefab (that little physical object on the ground), modifies some state like `bool itemDropped` and `int numItemsDropped`, makes some calculations to determine where to drop the item, and **displays that item's name in a UI label above the item**.

I'm currently in the process of making an inventory system, and I've realized something. Those physical objects on the ground that are supposed to be items don't really know that they're items (in the sense defined by the class). A sword doesn't know it's a sword, and an axe doesn't know it's an axe (**the game object sword doesn't know that it's a sword Item defined by the class**) So when I pick up an item, I can probably do some **code gymnastics to get the appropriate sprite to appear in the inventory**, but that doesn't seem like a smart solution.

So, my question is how do I get my sword **game object** (just a sphere on the ground representing a dropped item) to be linked to the sword **Item**? How do I get the sphere to know that it represents a sword with the ID number "1", the name "Sword", a weight of "1.5" etc. so that I don't have to do awkward code gymnastics? After all, when I'm adding an item to my inventory, I don't really think of it as JUST drawing that item's sprite in the first non-empty slot of the inventory. I would think it's much better to get each game object to know what Item it represents than to just try and get that sprite to show up in the inventory.

I might be overlooking something basic, but understand that I'm pretty new to Unity. Anyway, thanks for the time and help!

# Answer
> 2 votes
Create two prefabs, one for items laying on the floor and one for items in the user's inventory.

Program a MonoBehaviour `FloorItem` which has a reference to an instance of your class `Item`.

Add it to the floor item prefab. Whenever you `Instantiate` the floor item prefab, set the appropriate `Item` on it. The `FloorItem` class then sets up the other components on that prefab (like the `Renderer` and spatial `UI.Text`) using the information from the `Item` (name, model, etc.).

When the player picks up a `FloorItem`, get the `Item` from it and then `Destroy` the floor item game object. Then `Instantiate` the inventory item prefab. This prefab will be an UI object. Put it into the object hierarchy of the inventory UI. Program a MonoBehaviour `InventoryItem` for that prefab. This component also needs a reference to an `Item` object. Just as the floor item, it uses that reference to get information about the item it represents and uses it to set up all the visual components on the game object.

Your class FloorItem / InventoryItem class would look something like this:

```
public class FloorItem: MonoBehaviour {
     public Item item;

     void Start() {
          GetComponent<MeshRenderer>().mesh = item.mesh;
          GetComponentInChildren<UI.Text>().text = item.name;
          // ... and other components...
     }
     // ...code to handle interactions during gameplay...
}

```

The code to instantiate them would look something like this:

```
 newFloorItem = Instantiate(floorItemPrefab, position, rotation);
 newFloorItem.GetComponent<FloorItem>.item = ItemData.sword;

```

By the way, if you have your class `Item` inherit from `ScriptableObject`, you can handle item types as assets inside Unity and edit their properties with the Unity inspector. This can be quite handy. How to use scriptable objects exactly would be beyond the scope of this question. But we have plenty of questions about this.

---
Tags: unity
---


# Question
Title: How can I add a satisfying objective and/or win condition to a game with respawns?
I am looking to add an objective to my game.

https://www.youtube.com/watch?v=O3uxaxy5\_tc

The above video is the most recent video I've made of gameplay in my game. As you can see, the game **has** got:

* Opponents to fight (in the video NPC opponents, but multiplayer opponents will be there soon)
* Objectives to capture (the towers).
* Variation. That is, players can choose different skills to have different setups.
* A large and diverse map (note that multiple maps are easily possible, but that isn't the point right now).
* Constant action, thanks to the fact that players respawn immediately after they die.

On the surface, this looks fine. There appears to be everything needed for a game. However, I have a problem with a win condition, and an overall objective. Let me explain:

The map is divided into squares. Each tower controls a square. To take over a tower you must destroy it - Once "destroyed", the tower switches team and regains all of it's health.

The problem is when a team starts losing. Let's say that the map is like this:  (Ignore the red line in the picture)

As the teams respawn only in territory controlled by themselves, this means that the blue team would be respawning in a much smaller area than the red team. This means that the blue team are always in the territory they are defending, but the red team are mostly spawning really far away.

Using Photoshop to better visualize the problem:

With the black dots representing members of the red team, and the white dots representing members of the blue team (both teams have 10 members in ***this example***), you can see clearly how the blue team can **never** be defeated. Any member of the red team is simply ganged up on, overwhelmed, and then respawns really far from the fight. Yes, theoretically in that example one or two of the territories could be taken. But then the problem just gets worse. Imagine this example if the blue team only has one territory.

This isn't just theoretical, by the way. I've actually left the server and the AI tanks battling for over 3 hours and no team was able to win.

So to summarize the problem:

When a team controls less territory, there are more members of that team per piece of territory they own, and so there is no way that the opposing team can ever win.

Now let's talk about possible solutions that I've tried and dismissed:

One solution would be to remove respawning entirely. This would mean that:

* Taking territory would not be a problem, as you would not be attacking lots of newly-spawned opponents.
* Winning would not be as difficult.

However,

* This would encourage users to play very cautiously, just like in World Of Tanks.
* If a user dies, they have either a long boring wait in front of them, or have to quit and join a new battle.

I could also make each tower taken give the team more power (for example more health the more towers they have). This:

* *Technically* does solve the problem. A players' team can overwhelm the other team.

However:

* The battles are too quick. Once one team gains one or two towers there is far too much of a "landslide victory", where the extra power the team gains allows them to decimate the opposition.
* It isn't much fun being on the losing team, being able to die to the winners in far less shots and barely being able to harm them.

I could also make towers simply be permanently destroyed, rather than having them take over the other team. However, this then creates a permanently equal match.

* Players travel the same distance from their controlled areas, fight on equal terms in no-mans-land, and can never reach each others' towers to destroy them. This also sort-of falls prey to the original problem anyway in that there are tons of players who just respawned in that small area protecting all the towers, whereas the enemy players had to travel through the whole map to attack them. Which makes the problem *worse*.

I could limit the respawns, or have a respawn timer. However obviously,

* Players do not want to be sitting around.
* It interrupts the action to have to wait around.

I could leave the game how it is! I could add progression in a shop and buying skills. However,

* I am an indie developer. A multiplayer shop system, skills, storing player data, is all a ton of work for me. This is a huge amount of work for something which isn't really significant or that satisfying for a game as a whole.

In short, I've done a lot of experimentation with this and thought a lot about it, however there appears to be no clear answer.

And, even if a team takes all the towers and wins, what then!? The map just resets, and the battle starts again? This would be repetitive, and boring.

In short:

My game needs an objective system which is fulfilling, which allows one team to win, but to not make that victory worthless, and which allows both teams to have a long and enjoyable battle.

Edit: I forgot to mention that players in their own territory get a health regen, meaning the defenders in their own territory have even more of an advantage.

# Answer
**The winning condition is to capture all the towers and control the entire map.**

* Add respawn timer per tower.

Each tower has its own respawn timer so the players will only have to wait in 2 situations:

1. A teammate just respawned in the strategical point I want to respawn. This will give the option to more impatient players to do it in another tower and the more patient ones to wait and implement the desired strategy.
2. The team that has smaller territory don't have enough towers to respawn all members. This should help to finish the battle. Also, the first time a player notices that he needs to wait, he will play with more caution.

How this works remains completly on the balance of the timers and how many tiles a team need to lose before timers matter. So this first "wait to respawn" should translate into "ok, or we turn that now or we are doomed"

* "players in their own territory get a health regen, meaning the defenders in their own territory have even more of an advantage."

Each tower acts as a "healing beacon" and the healing splits between players. The more players in one area the less they individually heal.

Edit: Additionally, consider adding a "wipe-out respawn" if all players in a team die they all have to wait n-seconds. That is intended to give a cornered team a chance to make a "comeback", regain territory and turn the match around.
> 21 votes

# Answer
* Savage 2 and Warcraft worked around this problem by having a global ~60s timer: **every 60s all dead players spawn**. This causes players to naturally create "waves", which reduces the issues caused by defenders spawning at the battle site closer than the attackers.
* Battlefield 2 worked around this issue by allowing you **the option of your spawnpoints**, allowing attackers to spawn in combat areas, instead of the dead area.
* One game I don't recall provided **a minigame while awaiting spawn timers** that gave your teammates tiny bonuses.
* Several games allow you to **watch teammates while waiting to spawn** which provides useful intel about cross-map movements.
* DotA type games **give a team bonuses as they approach the enemy base** (such as stronger or siege creeps), so that by the time you get to that last point, you have enough of a bonus to landslide. You have to be careful that the bonuses near the middle are small or zero to avoid the early game landslide you mentioned, but once a team is clearly winning, this is an excellent way to go to end the game, and not draw out a losing match. I saw an interview with Blizzard where they said this was a key piece of why Heroes of the Storm maps work the ways that they do, and why siege creeps are so strong, but I can't find it now.
* DotA type games also **have mercenaries and boss creeps** for the same reason: A team that's way ahead can afford the time to take these side goals, which give a large enough bonus that they can take the final goals and end the game.
* Heroes of the Storm maps offer **side goals which attack the enemy base directly**, allowing a team that's winning to remotely end the game.
> 10 votes

# Answer
A quite typical solution for "control" maps is this: game win condition is achieving a certain amount of points, with points being received regularly based on the number of towers/amount of territory under control. Optionally, if you make the relation between towers controlled and points gained non-linear, you can tweak the unpredictability of the end result as you see fit.

If a simple "point" game is too boring for you, you can make those points a sort of a currency, rather than the win condition. Make it so you can activate a powerful (but temporary and one-shot) power-up or ability for a certain amount of points. Then, on the one hand, the weaker side still generally enjoys numerical superiority to make it easier to push back and return in the game. On the other hand, the winning team can get the momentum required to finish off tightly respawning enemies.
> 8 votes

# Answer
Victory points.

Controlling territory, killing turrets, killing players, etc. Some or all of these could generate differing numbers of victory points. Collect enough victory points, and you win.

Additionally, or alternately you could make it so there is a no man's land between the guaranteed spawning locations and the spawning locations you earn by securing objectives.
> 6 votes

# Answer
The game becomes a drag when it runs long, so impose a time limit:

* Use a hard time limit. Frequently I see games offer this as a setting for the round/battle regardless of the type of round (Capture the Flag, Free for all, etc) and usually with a number of reasonable options, but defaulting to No Time Limit.
* See @Alice's answer for a variation where controlling towers earns points and the first to a set number of points wins. I've seen the number of points be a setting for Control types of rounds, but you could also just arbitrate a reasonable number.
> 3 votes

# Answer
I offer Team Fortress 2's design choice for the analogous mode, capture point; there are 5 points on a symmetrical map, with 1 in the middle. Each team starts controlling the two closer to their base, with the middle one neutral. You capture points by standing on them without enemies standing there. The points are in a line, it's a tug-of-war kind of deal, and you can only capture the enemy's point closest to you.

Your spawn points move up as you capture points to ensure the team with advantage can actually reach the fight in a timely manner, but the losing team always spawns closer to the main "conflict zone". The final capture point is right next to their spawn. How is this gamestate resolved?

Points that are further from the center get captured faster. The final point is captured in 2 or so seconds, compared to the 30 it takes to get the middle one. Consider something similar! **Towers have more health if you control more of the map, meaning that having more map control makes defending a little easier, and speeding up the game once one team has obviously been put in a losing spot.**
> 3 votes

# Answer
In the spirit in keeping constant action as one of the games design goals, I would consider adding secondary objectives. These objectives would not technically be necessary to win the game, however they would provide a large bonus that would greatly aid the attacking team and allow them to finish the game.

For example, certain towers (either deep in the defensive territory or in a sort of "side-quest" area) could provide debuffs to the respawns of the defending team. Some ideas I was toying with were:

* Slowing field on spawn points
* Smokescreen to block vision
* Cannot fire weapon for x number of seconds (I particularly like this one because it allows the defense to make proactive movements while they are disabled)

You could also have a neutral "mini-boss" in the middle of the map that gives a huge combat bonus. Depending on the difficulty of the boss, fighting him would risk allowing the other team to come back, kill your team, and steal the objective. This sort of objective would create the play-style of pushing deep enough into the enemy base to give you the time and space to retreat to the boss and take him safely.
> 2 votes

# Answer
You could designate the top left/bottom right corners as spawn zones, with no towers. That way, tanks that re-spawn need to travel towards towers to defend, giving the other team an opportunity to get some shots in on the tower before the defenders reach them.

This prevents any imbalance-ing that your suggestions might have. It also makes it so that the defenders don't crowd around a single objective to fortify, they have to split up. That gives the attackers the chance to form strategy, i.e. if each team has 10 tanks the defenders will need to split up 5-5 on the last two remaining sectors, so the attacking team can see this and split 7-3 on some. When that tower is destroyed, the defenders don't instantly spawn on the other objective to defend it, the attackers can make a push there while the defenders are en-route to defend.

That system is more like ***Battlefield 1***'s multiplayer mode **Rush**, which is probably a good indication of it being a good system; if a major publisher uses it in a game that is very critically acclaimed, chances are it's at least usable. The only difference is in **Rush** there is 1 attacking team and 1 defending team, and the attackers have a limited number of lives to destroy all objectives. That provides a time limit without actually having a *temporal* time limit, which I usually don't like, but may be necessary to stop a game.

You could award points only for team kills (or devise other methods not related to tower destruction, like killing the last enemy inside of a square to 'clear the zone' or something), to give the game a multi-faceted approach for winning. Players will have to devise strategy. It won't make players too cautious, either, because they'll need points to win if they don't capture all the objectives!
> 2 votes

# Answer
UT2004 onslaught mode tackled this in the following ways:

* players can choose spawn points =\> attackers don't have to walk as far and can reenter the action more quickly
* towers spawn vehicles =\> vehicles are faster =\> attackers can reenter the action more quickly
* ... at a fixed rate =\> the more towers, the more vehicles (which are stronger than infantry)
* towers spawn some items at fixed rate =\> the more towers the better your weapons
* some long ranged weapons =\> attackers don't necessarily have to walk far to fight
* no respawn at towers under attack =\> attackers can lock down a tower for taking it
* after 20 minutes game time, towers would start to loose health for every tower under enemy control
> 2 votes

# Answer
Have you played Star Wars Battlefront 1 or 2? Those have endless respawning (sort of), and taking of territory, but they have several things your game doesn't. You could try any or all of these.

1) A total troop limit. Each team has, for example, 500 total soldiers, and each spawn decreases that number by one. So, eventually one team will run out of people, but the human players won't need to wait around if they run out of lives, because they can draw from the shared pool of soldiers.

2) Each "territory" allows the owning troops to spawn there. So, in your example, as red takes more towers, red tanks can spawn at those towers, keeping red tanks closer to the front lines.
> 2 votes

# Answer
You could allow players on the winning side to respawn in regions close to the remaining towers to be captured. This would allow the winning side to also enjoy the benefit of having all of its players spawn in close to the action and would eliminate the frustration of having to trek across the map, unable to do anything important, between respawns.
> 1 votes

---
Tags: game-design
---


# Question
Title: Loss in quality on downsized sprites in Game Maker
I'm having an issue with sprites quality in Game Maker.

I have some sprites used for UI with an original size of 2048\*512. I need to resize them in game to 512\*128. But when I do, I got a loss in quality.

This is the original picture, resized to 512\*128 with a third-party software:

This is the sprite, as it appears in Game Maker room editor (and in game) once resized to 512\*128:

Are there general guidelines for this kind of situation?

By the way, it's on Windows. Though I tried launching the game on an Android device and the result was the same.

# Answer
> 1 votes
Try activating **Interpolate colors between pixels** in Global Game Settings-\>Windows-\>Graphics

# Answer
> 0 votes
I encountered this very unpleasant problem, which is related only to the way you make GM:S draw things. The solution I found is very simple, instead of drawing directly to the screen, I first draw whatever I need onto a surface, then I draw the surface itself on the screen. The interpolation quality is way better than drawing onto the screen, both for sprites and fonts (since fonts are stored in texture groups as well as sprites).

---
Tags: sprites, game-maker
---


# Question
Title: How can I get the normal vector for a plane from a set of vertices?
I'm working on a HLSL / C++ little project to going over my graphics work, and I am unsure how I am to get a facing vector from a vertex polygon. I can't seem to find the formula.

The positions are P1, P2,P3

Let's call them class VertexPoint with P1.x, P1.y, P1.z for example?

# Answer
> 28 votes
You could easily find the normal by calculating two vectors, V1 = P2-P1, and V2 = P3-P1, and then find the cross product N = V1 x V2. Then you normalize N. Depending on the ordering of the vertices (clockwise or counterclockwise) you will get a normal facing front or back.

You also need to make sure that three three points aren't aligned, if they are you have to pick another point.

---
Tags: mathematics, vector, geometry, vertex, normals
---


title: Removing/Updating Spritebatch

text:
# Question
Title: Removing/Updating Spritebatch
I am designing a Spritebatch class, for static and dynamic objects with WebGL. A problem I'm facing is that I have read several different opinions on sprite batching but with one goal.

* **Put all vertices in one buffer and render them**

So in **WebGL** I'm using `gl.bufferData(....,new Float32Array(size), gl.STEAM_DRAW)`.

And here is my first problem: when the `spritebatch` should be dynamic then `size` is not fixed and will increase, which leads to recreating the `Float32Array` which I found out is very expensive for *n* ≥ 10000 (at least on my machine).

Second Problem, let's say I give the `Float32Array(maxElements)` a maximum size, and I add 4 Sprites then I have allocated much more than I actually need.

Other way: I create Spritebatch when I know how many sprites I have. So basically I put 4 Sprites into my scene, then before rendering I create a Spritebatch with size `4 * numVerticesPerSprite`. However let's say I want to update *Sprite 2*, I need some kind of index structure in my Spritebatch class to identify at which position the vertices of Sprite 2 are stored inside the SpriteBatch (inside `Float32Array()`).

**So my question is :**

How is a dynamic Spritebatch supposed to work and can you think of an indexing method to identify *Sprite X*'s vertices inside the `Float32Array` to update/remove them? (Additionally: Do particle systems solve what i am looking for? I assume they are also some kind of sprite batching)

# Answer
> 1 votes
**For updating sprites**: You can use bufferSubData to overwrite a section of the buffer with new data. As far as knowing how to index that sprite, they should all be the same size and don't share any vertices, so it's merely a multiplication of `index * sizeof(Sprite)`.

**For adding new sprites:** You could have an abstraction layer dynamically reallocate the buffer, doubling in size each time you run out of space. This is how dynamic arrays like `vector` or `ArrayList` work in other languages.

However, since reallocating requires storing a copy of your data client-side, you could make do with pre-allocating a fixed buffer that will be a hard limit on your total number of sprites, but it would be okay as long as you're mixing deletions with additions and you can guarantee the total active sprites is less than your pre-allocated capacity.

**For deleting sprites:** Depending on your workflow, you could do several different strategies.

1) When deleting sprite `i`, move the last sprite into index `i` and decrement your total sprite count. This also requires storing the sprite data client-side in a javascript array, so use this strategy only if you're also dynamically reallocating in your `addSprite` function.

2) When deleting a sprite, zero it out in the array and add its index to a "free list" to make it available for reuse next time you create a new sprite. This lets you recycle unused slots in your array without having to allocate a larger buffer.

**JsFiddle proof-of-concept demo**: see the `var a = batch.addSprite(...); a.moveTo(...); a.delete();` section. https://jsfiddle.net/talyian/6pry2Lr1/

---
Tags: 2d, sprites, webgl, spritebatch
---


# Question
Title: What is a reasonable bandwidth usage for a RT multiplayer game?
My game uses UDP communication only. Meaning: after the lobby connect (performed by Google Play Services), not a single TCP transmission is made. Only unreliable messages are used.

The game is currently one versus one, and the players transmit a little over 16Kbit/sec in datagrams in a steady stream. (2 kbyte/sec.) It also receives the same steady 16kbit/sec from the other party of course. These numbers do not include packet headers.

The player experience is pretty good, even with players between continents.

What I would like to know: is 16Kbit/sec considered normal, high or low?

I intend to add a 2vs2 mode, which would triple both the send and receive network volume. Could I get away with that? Where can I find references to typical bandwidth use in real time games?

# Answer
From this article, I would say 100MByte/hour is a reasonable estimate for the popular multiplayer games out there:

https://www.rhoonet.com/how-much-data-does-online-gaming-use

100MByte/hour converts to 28.4KByte/sec, which is 228KBit/sec. Therefore your current usage of 16KBit/sec is definitely acceptable, even if you were to triple it.
> 3 votes

---
Tags: networking, google-play-services, udp, realtime
---


title: Implementing an open world environment

text:
# Question
Title: Implementing an open world environment
Lets say my engine supports a "Model" with a position in the world, hitbox and the data to paint in the render method. Should an open world map be a "Model"? How do I render only part of it in order to increase performance? How do I implement only "local" collisions, again, performance-wise. Logically, it seems different than a normal "Model", I just cannot figure out how.

Bottom line: How's terrain rendering and physics different than "normal" rendering and physics?

Some technical information: I am using OpenGL with GLFW using C++.

# Answer
On the one side, it isn't different. On the other, it is.

Models typically use *bounding volumes* (e.g. boxes) for collision detection, and only the really important stuff gets mesh-accurate collision detection.

Models are typically loaded into memory fully. You either need them or don't.

Terrain on the other hand isn't needed completely. You only need parts of it, commonly refered to as *chunks*. Those chunks *could* be individual models, but more often then not they aren't.

Terrain needs *LOD*, and with LOD comes *stitching* problems. So chunks need to be aware of their LOD state and the LOD state of the neighbouring chunks - a common solution is using *quad trees* for terrain.

Moreover, collision detection against terrain can often be simplified. If your terrain does not have holes but is derived from a *height map*, you can greatly simply collision detection by only checking the height of the bottom vertices of your chracaters bounding volume against the hight of the terrain *at that point*.

You will want to have your terrain in a data structure that supports *frustum culling* and potentially *caching* / *paging* (if a player goes back and forth a lot).

All in all, terrain is *vastly* different from normal models due to its sheer size. But at the end of the day, your piece of terrain is just a mesh with a shader and a few textures, just like any other model, too. So not so different after all.

You need to ask yourself what your terrain - for your game - has to be able to do. And then support that.
> 1 votes

---
Tags: opengl, c++, terrain-rendering
---


# Question
Title: Can I use Unity remote with a Android emulator instead of Android phone?
*Unity Remote* is good app. It allows to connect with Unity while you are running your project in Play mode from the editor.

But what if I want to test game but I don't have an Android phone? Yes, it happens ¯\\\_(ツ)\_/¯

I have a great Android emulator: *Nox APP Player*

The emulator doesn't have `USB`, so it just show me standsrt text `Connect device with a USB cable .....` bla bla bla ...Game in the Unity Editor is running...emulator doesn't display the game.

Can I somehow connect this emulator to unity using *Unity Remote*? Or using something else? How?

# Answer
I was able to run Unity Remote 4 on standard Android emulator.

Final efect looks something like

Whole procedure:

1. Install Unity and open some Unity tutorial project (2D Roguelike tutorial in my case)
2. Install JDK, Android SDK and setup Android emulator using AVD Manager. My emulator config looks like this:

**Important note:** CPU/ABI option seems to be one of most important ones(Intel x86 emulator didn't work for me)

3. Then install Unity Remote 4 from apk file to emulator using command: `adb.exe install path/to/apk` (Windows) or `adb install path/to/apk` (Linux/Mac).
4. Then in Edit \> Preferences \> External Tools - set paths to Android SDK and JDK
5. In Edit \> Project Settings \> Editor in section Unity Remote select: Any Android Device.
6. In File \> Build Settings - add Your scenes and switch platform to Android.
7. Press PLAY in Unity while Android Emulator is running and Unity Remote 4 app is opened.

**Tip:** At first I needed to restart unity after all changes, because it wasn't starting game on emulator. Now it runs everytime.

**Note:** My emulator config was only for test purposes, so You can find better config for yourself.

**Note2:** I have not tested this solution with other emulators like: Nox App Player or Genymotion.

**Note3:** Using emulator may be very laggy.
> 3 votes

# Answer
Not sure if you still need the solution for this problem, but I think I should leave an solution for those who come later.

You can connect Nox with Unity via UnityRemote (I'm using Unity Remote 5) with the adb of Nox. Here the steps :

* Rename your adb.exe to other (i.e adb\_origin.exe). It's normally located at SDK folder\platform-tools
* Go to Nox installation folder\bin, looking for nox\_adb.exe, copy it to the location of your origin adb.exe
* Rename nox\_adb.exe to adb.exe
* Open cmd and enter : adb.exe connect localhost:62001 and you will see "already connected to localhost:62001". If not, you can try replace localhost by 127.0.0.1
* Then apply steps 3-\>7 of @Axxxon
* At the Resolution dropdown, you can choose Normal (default is Downsize) to have better image quality on Nox

Note that after all of this, you should restore the origin adb.exe for later use. Here is my result picture :

Hope this will useful.
> 1 votes

---
Tags: unity
---


title: Voxel Game - High Memory and CPU Usage

text:
# Question
Title: Voxel Game - High Memory and CPU Usage
I am currently developing a voxel game and I had recently noticed that the game from startup is at around 2GB of memory. Currently I am rendering 14 x 14 chunks as shown:

I did a profile on the game and I noticed that the function call glfwSwapBuffers(...) takes 9,964 m/s to run (76.4%) and as the program's life continued it kept growing. The next function is glDrawElements() which takes 849 m/s to run (8.49%). I am unsure what is causing the bottleneck.

Going back to the high memory usage issue there are two things that seem to be causing high memory. As explained in this thread here: Voxel Game - Lag when camera is inside of the terrain I generate the terrain once and since I posted that question, I create a mesh for each chunk made up of the visible vertices. After that I send each chunk entity to my renderer and it is drawn from these two blocks of code.

```
    for(Chunk[] chunks1D: chunks)
    {
        for(Chunk chunk: chunks1D)
        {
            //Model matrix
            Matrix4f modelViewMatrix = transformation.getModelViewMatrix(chunk.getEntity(), viewMatrix);
            shader.setUniform("modelViewMatrix", modelViewMatrix);
            //Render mesh
            shader.setMaterialUniform(chunk.getEntity().getMesh().getMaterial());
            chunk.getEntity().render();
        }
    }

```

which calls this

```
public Matrix4f getModelViewMatrix(Entity entity, Matrix4f viewMatrix)
{
    Vector3f rotation = entity.getRotation();
    Vector3f position = entity.getPosition();
    float scale = entity.getScale();
    modelMatrix.identity().translate(position).
        rotateX((float)Math.toRadians(-rotation.x)).
        rotateY((float)Math.toRadians(-rotation.y)).
        rotateZ((float)Math.toRadians(-rotation.z)).
        scale(scale);
    //Copy view matrix
    Matrix4f currentView = new Matrix4f(viewMatrix);
    modelViewMatrix = currentView.mul(modelMatrix);
    return modelViewMatrix;
}

```

and this

```
public void render()
{

    //Bind the VAO
    glBindVertexArray(vaoID);
    glEnableVertexAttribArray(0); //Vertex Data
    glEnableVertexAttribArray(1); //Colour data
    glEnableVertexAttribArray(2); //Normal data

    //Draw the vertices: mode: Triangles, count, type: integers, offset
    glDrawElements(GL_TRIANGLES, numVertices, GL_UNSIGNED_INT, 0);

    //Restore state
    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(2);
    glBindVertexArray(0);

}

```

From the profile I found two sources of high memory, one for Matrix4f which is due to the getModelViewMatrix(...) function (the memory usage grows over the programs lifespan) and another for float and float\[\] from the genChunkMesh(...) function as shown in my other thread (Voxel Game - Lag when camera is inside of the terrain) which is called once when a chunk is loaded. It seems as if for both cases that Matrix4f, float\[\] and float instances are being created by they are never released from memory. :/ I have tried looking everywhere for a solution but I can't find one... I feel my game is optimised well enough for what is being rendered and these problems shouldn't be occurring.

**tldr:** Simple voxel terrain gen requires high amounts of CPU and the culprit is glfwSwapBuffers which takes 9,694 m/s to run (grows over time). High memory usage also from Matrix4f, float and float\[\] (floats of which seem to be retained from chunk mesh generation) objects causing the game to use ~2Gb of memory from startup (14 x 14 chunks) each chunk contains its own mesh (containing a VAO which has all of the chunks visible vertices, normals and colours) and two 3D int arrays one for the chunk's blocks and one for the chunk's visible blocks (16 * 16 * 128) each storing the block ID at that location.

# Answer
> 2 votes
First of all, we can say with absolute confidence that the culprit is **not** your glfwSwapBuffers call.

On it's own SwapBuffers doesn't do much; what it does however do is take all of the GL commands issued in the preceding frame and flush them to the GPU for execution. Because this happens *within* your SwapBuffers call, it only *appears* as though SwapBuffers is to blame; it most assuredly is not.

The cause of your problems is the amount of work you send to the GPU, and structuring your GL calls in a manner that allows your driver to optimize them should be your solution. Look at this for starters:

```
//Bind the VAO
glBindVertexArray(vaoID);
glEnableVertexAttribArray(0); //Vertex Data
glEnableVertexAttribArray(1); //Colour data
glEnableVertexAttribArray(2); //Normal data

//Draw the vertices: mode: Triangles, count, type: integers, offset
glDrawElements(GL_TRIANGLES, numVertices, GL_UNSIGNED_INT, 0);

//Restore state
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
glBindVertexArray(0);

```

One of your problems here is that **whether or not vertex attrib arrays are enabled or disabled are stored as part of the VAO state, so you do not need to enable them or disable them again**. You're doing needless work, your VAO is incurring 2 changes per bind, and your driver cannot optimise this workload.

Let's make things a little bit better:

```
//Bind the VAO
glBindVertexArray(vaoID);

//Draw the vertices: mode: Triangles, count, type: integers, offset
glDrawElements(GL_TRIANGLES, numVertices, GL_UNSIGNED_INT, 0);

//Restore state
glBindVertexArray(0);

```

Now you've still got a problem here which is coming from the fact that you unbind the VAO. Because of this you're also incurring 2 VAO changes per draw call, and your OpenGL driver is not going to be nice and optimize them out. A much better loop looks like this:

```
glBindVertexArray (...);

for (...) {
    for (...) {
        glDrawElements (...);
    }
}

```

See the difference - now you're only incurring a single VAO change overall and this is a workload that your driver will be **much better** able to optimize for you.

I suggest that you make these changes first and then re-profile.

# Answer
> 1 votes
when building the mesh for each chunk you can use the neighbouring chunk to see whether a face needs to be drawn. This could lead to some chunks not needing to be drawn at all.

Can you try using separate vertex formats? That may be a bit faster using a single VAO and VBO binding.

That will make the Chunk.render() look something like:

```
render(){
    if(numVertices == 0) return;

    //Bind the VBO & EBO
    glBindVertexBuffer(vertexBindingPoint, vbo, vboOffset, VertexStride);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);

    //Draw the vertices: mode: Triangles, count, type: integers, offset
    glDrawElements(GL_TRIANGLES, numVertices, GL_UNSIGNED_INT, 0);
}

```

---
Tags: lwjgl, terrain, voxels, procedural, memory
---


# Question
Title: How do I understand a big c++ gaming project in SFML?
Currently I am doing SFML- c++ as a basement in game development before starting out Unreal

When I see a game project in SFML, the codebase is huge, like above 30 classes, 100 functions, how can I get an idea of the code project, any suggestions about the usual standard class names in SFML projects and their purpose would be helpful.

# Answer
> 1 votes
If the code is nice, then the functions have a descriptive name, and you can basically skim through the main game loop to understand what it does.

If it's not that nice, then going throug the code with an inspector is probably your best option.

# Answer
> 1 votes
In my opinion, the best way to understand for you is to go straight from main function, examining line by line. You don't need (and it doesn't make any sense) to go through all the methods of each class unless you really know where and why they're being used. So just go straight from the beginning, and you're good to go.

---
Tags: c++, sfml
---


# Question
Title: How should I make (3D) buildings that can be entered in the game?
I have no idea about how would I make a building that can be entered in a game. Should I model separate parts of it and than combine them or should I model the entire thing as one object?

Are these things are built up in a 3D modeller like blender or if not where?

# Answer
Let's look at Skyrim (because I have no idea about other games). It has both houses and big dungeons. These are made from "tile sets", there are separate 3d models for corridors, walls, furniture, etc. These can be culled when you don't see them, but most dungeons and houses are small enough to render them.

There are separate tilesets for dwemer stuff and for usual buildings, but you can mix them, and get something like Markarth.

So, you shouldn't cut the house into rooms or floors. Cut it into objects, that can be repeated. This way you save on the resources and you also give your artist(s) a bigger space for creativity.
> 0 votes

# Answer
> Are these things are built up in a 3D modeller like blender or if not where?

When you want anything in a Unity scene which is more complex than the basic shapes it offers, you won't get around either using a 3d modeling program or to generate the mesh procedurally from a script. When you don't need infinite randomly-generated variety, a 3d modeling program is usually easier.

> Should I model separate parts of it and than combine them or should I model the entire thing as one object?

That depends. Do you have to split it? That depends on how many building you have, how large they are, what level of detail they have and the rendering capabilities of your target platform.

If it turns out that having a full high-def model of your building in your scene is too much, then splitting it up has the advantage that you can use LOD groups and thus allow Unity to use a different level of detail for each part of the building.

You might also get away with only activating the interior of the building when the player enters it and deactivating it when they leave it, but only if the player can not look into buildings from the outside or interact with things in buildings from the outside. You could even extend this system to only activate the room the player is in and any rooms they can look into from that room.

Also, any furniture items in your buildings which you might want to reuse (or even want the player to be able to interact with) should be individual game objects and not part of the geometry of the building interior. The reason is that Unity can save a lot of resources by reusing meshes. So if you have a room with 20 identical chairs, don't copy&paste the chair 20 times in your 3d modeling program. Model one chair as a separate 3d model, create one chair-prefab from it in Unity and drag it into the scene 20 times as children of the building interior.
> 1 votes

# Answer
> Game engines are tools available for game designers to code and plan out a game quickly and easily without building one from the ground up. Whether they are 2D or 3D based, they offer tools to aid in asset creation and placement.

(Source)

> There are so many good options out there today for mobile game development that any list is going to be incomplete.
>
> Unity - Though often considered to be the best SDK for 3D mobile games, their 2D technology is now also up there with the best of them. Because it’s so popular there is a huge community and loads of resources.
>
> Corona Labs - The claim is that you can create games 10 times faster than with other SDKs. It’s easy to learn and also has a large community. Could be the right choice for a 2D game.
>
> GameSalad - While lesser known than the first two, it’s still a great platform for games that deserves a look. Might be a better choice for a less experienced developer. Good ad network integration.

(Source)
> -2 votes

---
Tags: unity, 3d, models, blender
---


# Question
Title: How to rotate within a fixed interval in Unity?
I have very recently started to learn Unity.

I'm trying to write code that will make a character swing a flag. I want to use this object and rotate the arm up and down. So I need to make it rotate up and down with within 30 degrees.

This is my attempt but it simply keeps on turning. How would I make the hand rotate in motion within the interval \[-30, 30\] degrees.

```
private GameObject myobject;
public float timeElapsed =0;
public float delay = 3.0f;
float OO = 0.0f;

void Start () {
    myobject = GameObject.Find ("rightarm").gameObject;
}

void Update () {
    timeElapsed += Time.deltaTime;
    Debug.Log (timeElapsed);

    if (timeElapsed >= delay) {
        OO = 30.0f;
        timeElapsed = 0;
        if (myobject.renderer.enabled == false) {
            myobject.renderer.enabled = true;
        }

        myobject.transform.Rotate (OO, 0.0f, 0.0f);
    }
    else
    {
        myobject.transform.Rotate (-OO,0.0f, 0.0f );
    }
}

```

# Answer
There are two problems with your code:

* Whenever `timeElapsed >= delay` is true, `timeElapsed` is set again to zero, making the condition again false and causing it to rotate in one direction/
* Transform.Rotate adds the given rotation to it's current rotation, thus it will rotate the arm without stopping at 30°.

You could first check if `timeElapsed >= delay` is true and then switch between either lowering or raising the flag, so this is what the code may look like:

```
bool shouldRaiseFlag = true;

// [...]

timeElapsed += Time.deltaTime;
if(timeElapsed >= delay){
    if(shouldRaiseFlag) myobject.transform.localEulerAngles = new Vector3( 30.0f,0f,0f);
    else                myobject.transform.localEulerAngles = new Vector3(-30.0f,0f,0f);
    shouldRaiseFlag = !shouldRaiseFlag;
    timeElapsed = 0;
}

```

However, this will instantly raise/lower the flag, so if you want smooth motion you could instead use:

```
Vector3 armRotation = new Vector3(30,0,0);
float armDirection  = 1.0f;

// [...]

timeElapsed += Time.deltaTime;
if(timeElapsed >= delay/2){
    timeElapsed  = -delay/2;
    armDirection = -armDirection;
}
myobject.transform.localEulerAngles = armRotation * (timeElapsed / (delay/2)) * armDirection;

```

I am aware this solution is certainly not the best, so make sure to take a look at the other answers posted here.
> 1 votes

# Answer
I believe you have to make a modification in the above code because, Rotate will continuously rotate the object around the x-axis for every frame.

Instead of "myobject.transform.Rotate (OO, 0.0f, 0.0f);" you should use "myobject.transform.rotation = Quaternion.Euler (OO, 0.0f, 0.0f);".

Modification is as follows :-

```
void Update () {
timeElapsed += Time.deltaTime;
Debug.Log (timeElapsed);

if (timeElapsed >= delay) {
    OO = 30.0f;
    timeElapsed = 0;
    if (myobject.renderer.enabled == false) {
        myobject.renderer.enabled = true;
    }

    myobject.transform.rotation = Quaternion.Euler (OO, 0.0f, 0.0f);
}
else
{
    myobject.transform.rotation = Quaternion.Euler (-OO, 0.0f, 0.0f);
}

```

}

Hope this helps you out.
> 0 votes

# Answer
For something like swinging a flag back and forth, I'd be tempted to use simple harmonic motion, like a pendulum or sine/cosine wave...

```
// Specify how many degrees you want to rotate from the initial orientation.
public Vector3 amplitude = new Vector3(30, 0, 0);

// Specify how many seconds a complete loop should take.
public float period = 6f;

// Cache initial orientation so we can rotate relative to that pose.
Quaternion _initialOrientation;

// Perform caching on Start.
void Start() {
    _initialOrientation = transform.localRotation;
}

void Update() {
    // Calculate how far along we should be in the wave.
    float phase = Mathf.PI * 2f * Time.time/period;

    // Calculate the angle at this part of the wave.
    Vector3 angle = amplitude * Mathf.Sin(phase);

    // Rotate by angle relative to our initial orientation.
    transform.localRotation = _initialOrientation * Quaternion.Euler(angle);
}

```
> 0 votes

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


title: Good basemap generator

text:
# Question
Title: Good basemap generator
I am currently making a board game and cannot seem to find any vector world map creators where I can select a region of the world to capture and have it download that section. I just want a base map so no city names and preferably no borders.

The map doesn't have to be vector if it is of good enough quality.

# Answer
I have downloaded high resolution JPG maps for some clients with the Mapbox Studio tool. Its a software you need to install on your computer but it gives access to Google-style maps with tons of customization options and everything you do can be exported as 300dpi JPG files. Not vector but in good (print) quality.

You can remove city names, borders and everything you want via a CSS-style language they are using and there are also some ready-made styles you can use.
> 1 votes

# Answer
Wikimedia Commons has various blank SVG maps of the world.

The useful thing about SVG is that you already have the polygon information about the borders in an easily parseable XML format. Most of these maps even have the country-paths named with the ISO country-codes. When you are developing a web application, you can even make that map interactive with some JavaScript.

If you want only a part of the map, you will need to cut them out with a vector graphics editor like Inkscape.

But if you want to use one of these maps, keep the license conditions in mind. Most of them are in the public domain, which means you can use them freely. Others are under share-alike licenses which can make it hard to monetize your game if you use them.
> 0 votes

---
Tags: maps
---


# Question
Title: How can I represent collision for an object needing more than PolygonShape's maximum of 8 vertices?
This is a part of map (it is a cave) of my LibGDX game (using Box2D):

I would implement a PolygonShape as the black part of the map to prevent the whatever moves (for example a ball) inside the cave from leaving it.

This is an example of my PolygonShape like I would draw it (with 100 vertices):

The problem is that Box2D doesn't allow me create it with not more than 8 vertices...

How can I fix this thing?

Sorry, my English isn't very good. :)

# Answer
> 2 votes
Polygon shapes are normally limited by the internal `b2_maxPolygonVertices` setting (in the C++ library code), which as of Box2D 2.3.2 is set to 8.

The other problem though is that polygon shapes must be convex. What you're were trying to use a polygon for though looks to be a concave shape. For concave, static (immovable), shapes, the Chain Shape is the way I'd go.

From your comment, it looks like you have since decided on using ChainShape too.

---
Tags: java, libgdx, box2d
---


# Question
Title: Using a Coroutine in a character move left/right situation for a random amount of time
So what I am trying to do is have an AI character make decisions based on 3 zones, far distance, mid distance, or close range (not yet to close range). So far, the logic is set up so the character if in the far zone (50 to 100) will come forward. Once it reaches 50, it will decide if it will move left or move right (eventually going to add in move forward, or jump attack) for a certain amount of time between 2 and 10 seconds. This is based off a random number generator. Once this number is generated (1 or 2), it will call on either the move left or move right functions. These functions create a position vector, a destination vector (x or -x direction), and a time float which is another random range between 2 and 10. These values are then output to a coroutine. I am fairly new to coroutines. Right now, running the code I have, the AI character comes in from 100 units just fine. Once it reaches 50, it will slowly move left or right for a little bit, and then start glitching back and forth. I am wonder what I have done wrong here. Am I missing some type of position cache at the beginning or possibly the coroutine isn't returning a time. I'm really not sure. Please help.

```
static Animator anim;
public Transform player;
public float enemySpeed = 0.5f;
public float strafeSpeed = 0.5f;
public float attackdistance = 50;
public float farDistance = 100;
public float midDistance = 50;
public float closeRange = 5;

// Use this for initialization
void Start()
{
    //gets possible animations from stored unity animator
    anim = GetComponent<Animator>();
}

//start of game logic for AI
// Update AI mode based on enemy distance (far, mid, or close)
void Update() {

    // makes AI walk forward due to far distance
    //if ((Vector3.Distance(player.position, this.transform.position) <= farDistance) && (Vector3.Distance(player.position, this.transform.position) > midDistance))
    if ((floatDistanceBetweenAIPlayer() < farDistance) && (floatDistanceBetweenAIPlayer() > midDistance))
    {
        // magnitude of distance from AI to enemy
        Vector3 myDirection = vectorDistanceBetweenAIPlayer(player);
        //AI looks at player
        updateLookAtPlayer(myDirection);

        //AI walks toward player
        updateWalkForward();
    }

    //makes AI decide to go left, right, forward, jump attack, or idle
    //if ((Vector3.Distance(player.position, this.transform.position) <= midDistance) && (Vector3.Distance(player.position, this.transform.position) > closeRange))
    if ((floatDistanceBetweenAIPlayer() < midDistance)&& (floatDistanceBetweenAIPlayer() > closeRange))
    {
        // magnitude of distance from AI to enemy
        Vector3 myDirection = vectorDistanceBetweenAIPlayer(player);

        //AI looks at player
        updateLookAtPlayer(myDirection);

        //start decision process by generating a random numer
        int rnd = Random.Range(1, 3);
        //int rnd = 1;

        print("rando " + rnd);
        if (rnd == 1)
        {
            updateWalkLeft();
            print("walkleft");
        }
        if (rnd == 2)
        {
            updateWalkRight();
            print("walkright");
        }
    }
}

//finds magnitude of distance between player and AI as a float
float floatDistanceBetweenAIPlayer()
{
    //dist is getting the float magnitude of players position subtracted from the AI's postition
    float dist = Vector3.Distance(player.position, transform.position);
    return dist;
}

Vector3 vectorDistanceBetweenAIPlayer(Transform player)
{
    Vector3 dist = player.position - transform.position;
    return dist;
}

// updates AI's look direction
void updateLookAtPlayer(Vector3 direction)
{
    transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), 0.1f);
    direction.y = 0;
}

// moves AI forward and starts animation
void updateWalkForward()
{
    this.transform.Translate(0, 0, enemySpeed);
    //anim.SetBool("isIdle", false);
    anim.SetBool("isWalkingForward", true);
    anim.SetBool("isWalkingLeft", false);
    anim.SetBool("isWalkingRight", false);
}

// moves AI to left
void updateWalkLeft()

{
    float time = (Random.Range(2, 10));
    print("time" + time);
    //vector of position of AI
    Vector3 position = new Vector3(transform.position.x, transform.position.y, transform.position.z);
    //Vector with randomly generated x values to make the AI strafe left
    Vector3 destination = new Vector3((transform.position.x) + (Random.Range(2, 10)), transform.position.y, transform.position.z);

    StartCoroutine(MoveFromTo(position, destination, time));
}

//moves AI to right
void updateWalkRight()

{

    float time = (Random.Range(2, 10));
    print("time" + time);
    //Vector posistion of AI
    Vector3 position = new Vector3(transform.position.x, transform.position.y, transform.position.z);
    //Vector with randomly generated x values to make AI strafe right
    Vector3 destination = new Vector3((transform.position.x)-(Random.Range(2, 10)),transform.position.y,transform.position.z);

    StartCoroutine(MoveFromTo(position, destination, time));
}

IEnumerator MoveFromTo(Vector3 position, Vector3 desination, float time)
{
    float elapsedTime = 0;
    while (elapsedTime < time)
    {
        transform.position = Vector3.Lerp(position, desination, (elapsedTime / time));
        elapsedTime += Time.deltaTime;
        yield return null;
    }
    transform.position = desination;
}

```

}

# Answer
You call

> StartCoroutine(MoveFromTo(...))

multiple times in **Update** function. So your corotunes runs independently, and all of them have different parameters but they all change one position. To avoid this problem don\`t call you corotunes in **Update** function or create state machine.
> 1 votes

---
Tags: c#, ai, coroutines
---


# Question
Title: What happened with server code on deployment to Heroku
I'm starting to learn about making games on the web and am using this agario clone on GitHub to help.

I've succeeded in setting up a version on Heroku using the instructions from here. I've never used Heroku before, so I'm a little lost on a few more things. The link from the instructions allowed the files to be directly transferred from GitHub. However, I can't seem to view them at all from Heroku - I can only run the client with 'Open app' (which works).

What exactly happened when I deployed the app? Did Heroku immediately start running the server code and will it continue to indefinitely do so even if no clients are connected?

# Answer
Heroku's gear will have started up and started running your node.js instance. Node.Js is designed to run continuously, but depending on your pricing plan, heroku may shut down the 'Gear'(your server instance) if nothing changes in 30 minutes.
> 1 votes

---
Tags: javascript, multiplayer, webapp
---


# Question
Title: Tiled deferred rendering frustum calculation problem
I know there are plenty of tutorials how to create tiled frustum with compute shaders, but I\`m trying to understand the steps and want to build it on the cpu with pure C# code.

I translated a lof of Intels approach (which can be found at intels post: Deferred Rendering for Current and Future Rendering Pipelines, sorry I have to earn more reputation to link this) to c# code, which was a kinda hard work because I am not familiar with compute shaders.

So now I got some problems with the algorithm.

1. A single light is contained by a lot of tiles, even if the AttenuationEnd(or sphere radius) of the light is set \< 0,1. It seems to have no effect. (the image below shows the rays of each tile with light info)

*White: Tiles with no light | Red: Tiles with light*  2. I dont get right results if calculating a frustum ray from its corners. The following image shows the partially rendered (from 5 to 5.1) rays with origin at 0, 0, 0. Should\`nt there be more space between each tile at 70 degree fov?

This is the code I\`m using. I commented out a lof of stuff, also with debug info, if possible.

```
        vec4[] frustumPlanes = new vec4[6];

        // There is 1 light with following properties:
        // Position       : 5, 5, 5
        // AttenuationEnd : 0.1 (should fit inside some frusta)

        // Use a simple 70 fov (70 / 180 * PI) perspective setup.
        // width = 486
        // height = 279
        // near = 0.1
        // far = 10
        mat4 projection = scene.Camera.ProjectionMatrix;
        int TILES_COUNT = 16;

        for (int tX = 0; tX < TILES_COUNT; tX++)
        {
            for (int tY = 0; tY < TILES_COUNT; tY++)
            {
                // tileBias lies between 1 and -1, decreases from 1 to -1
                vec2 tileBias = new vec2(1 - tX / (TILES_COUNT - 1f), 1 - tY / (TILES_COUNT - 1f)) * 2f - 1f;

                vec4 c1 = new vec4(-projection.m00, projection.m01, tileBias.x, projection.m03);
                vec4 c2 = new vec4(projection.m10, -projection.m11, tileBias.y, projection.m13);
                vec4 c4 = new vec4(projection.m30, projection.m31, 1.0f, projection.m33);
                // c1 = { -0.82,     0, 1, 0 }  < 3rd index is tileBias.x for tX = 0
                // c2 = {     0, -1.43, 1, 0 }  < 3rd index is tileBias.y for tY = 0
                // c3 = {     0,     0, 1, 0 }

                frustumPlanes[0] = c4 - c1;
                frustumPlanes[1] = c4 + c1;
                frustumPlanes[2] = c4 - c2;
                frustumPlanes[3] = c4 + c2;

                // The following 3rd and 4th index signs confuse me, why +/-?
                frustumPlanes[4] = new vec4(0f, 0f, 1f, -0.1f); // near
                frustumPlanes[5] = new vec4(0f, 0f, 1f,  10f); // far

                // Normalizing corners
                for (int i = 0; i < 4; i++)
                    frustumPlanes[i] *= 1f / frustumPlanes[i].xyz.Length;

                // An attempt of converting the frustum into a ray.
                vec3 rayDir = frustumPlanes[0].xyz + frustumPlanes[1].xyz + frustumPlanes[2].xyz + frustumPlanes[3].xyz;
                rayDir = rayDir.Normalized;

                // Calculates whether a light is inside the frustum
                bool anyLightInFrustum = false;
                for (int i = 0; i < lights.Count; i++)
                {
                    Light light = lights[i];
                    vec4 lightPos = new vec4(light.Pos, 1.0f);
                    bool inFrustum = true;
                    for (int j = 0; j < 6; j++)
                    {
                        float dist = vec4.Dot(frustumPlanes[j], lightPos);
                        inFrustum = inFrustum && (dist >= -light.AttenuationEnd);
                    }
                    if (inFrustum) anyLightInFrustum = true;
                }

                // Set the color to red, if a light is contained
                vec4 color = new vec4(1);
                if (anyLightInFrustum)
                    color.rgb = vec3.UnitX;

                // Draws a ray with a range from {4} to {5}, origin at {0, 0, 0}
                DrawRayWithColor(tessellator, color, rayDir, 5.0f, 5.1f);
            }
        }

```

Maybe some of you can give me some hints for this. Even if I just did a translation mistake.

Thanks in advance!

# Answer
Try to use `tileBias` within a range of 0 to 2. You also have to use a cross product of two frustum corners.

For example, `vec3 rayDir = vec3.Cross(frustumPlanes[0].xyz, frustumPlanes[2].xyz);`.
> 0 votes

---
Tags: c#, rendering, vector, frustum
---


# Question
Title: Look rotation viewing vector is zero in Unity when making UI
How can I tackle the problem: `Look rotation viewing vector is zero`?

Here is how I get it:

1. I add an Image from UI.
2. When the Image is added I click on it in the Hierarchy view.
3. When focus is on an Image I take the Canvas border and move it left.
4. I get the Exception.

Here are some screenshots of the process which takes place:

In the last screenshot I selected the Canvas and tried to focus on it by pressing `F` in the Scene view. As you can see I am not able to resize the canvas anymore. That means that I would have to create a new Canvas and copy everything into it, which is pretty tiresome and error prone. That is a reason I am concerned with the Exception. Will appreciate any attention.

# Answer
I have recreated your problem and have found a way to fix it that may work for you. I believe the error is occurring because of the size of your Canvas being set to zero when you try to resize it in Overlay mode.

**Firstly:** You need to set your Canvas *Render Mode* to World Space, or else resizing the Canvas will not be possible (and will result in the error you received) as it will overlay the screen at a set size.

**Secondly:** To return to a view in which resizing the Canvas is possible you need to switch from Sprite mode to Position mode. Then move the Canvas a bit with one of the three axis. This is the way I was able to return to editing the Canvas' size. (I do not know why this works.)
> 1 votes

---
Tags: unity, gui, editors, exceptions
---


# Question
Title: How to achieve this kind of look of a cube in a most efficient way?
It might be a trivial question, but I couldn't come up with a simple solution. I need to create a cube like on the image below in `Unity`.

As always, I target mobile so it would be nice if it was made on a `mobile/diffuse` shader.

I was playing with lights a little bit, but in order to achieve this kind of look, I'd need to stack multiple lights because one shadow is not enough. Also, I tried adjusting the angles of the lighting - with no luck.

Do you have any tips, how could I make one in a most efficient way?

# Answer
> 3 votes
I will be giving you two answers, The one for your actuall problem,and another one with a cube that has faces colored based on how much they are facing top:

---

## To simply create a Cube like that:

* Create an image, and color it like the left half should be COLOR\_X and the other half, COLOR\_Y, save it; (paint will do it)
* create a cube inside blender, and go to UV/Unwrapp;
* place the face you want to be COLOR\_X in the left, the others in the right;
* Export to Unity;
* Inside Unity create a simple Unlit/Texture Material;
* Set the image you created as the Texture;
* Apply the material to the UV/mapped cube;

---

## Faces should have a color depending of the normal angle;

```
    Shader "Unlit/NormalColored"
    {
        Properties
        {
            _NormalColor ("Color facing TOP", Color) = (1,.5,0,1)
        }
        SubShader
        {
            Pass
            {
                CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag
                // include file that contains UnityObjectToWorldNormal helper function
                #include "UnityCG.cginc"

                struct v2f {
                    // we'll output world space normal as one of regular ("texcoord") interpolators
                    half3 worldNormal : TEXCOORD0;
                    float4 pos : SV_POSITION;
                };

                // vertex shader: takes object space normal as input too
                v2f vert (float4 vertex : POSITION, float3 normal : NORMAL)
                {
                    v2f o;
                    o.pos = UnityObjectToClipPos(vertex);
                    // UnityCG.cginc file contains function to transform
                    // normal from object to world space, use that
                    o.worldNormal = UnityObjectToWorldNormal(normal);
                    return o;
                }

                float4 _NormalColor;
                float _ShadeColor;

                fixed4 frag (v2f i) : SV_Target
                {
                    // The Y component is TOP direction
                    float normal_y = (i.worldNormal).y/2 + .5;
                    float normal_y_2 = (i.worldNormal).y;
                    return (normal_y_2 * _NormalColor);
                }
                ENDCG
            }
        }
    }

```
* only a face pointing EXACTLY TOP should be colored, change the Frag function to this;

```
fixed4 frag (v2f i) : SV_Target
            {
                // The Y component is TOP direction
                float normal_y = (i.worldNormal).y/2 + .5;
                if (normal_y >= .999) // THIS VALUE CAN BE SET AS A PROPERTY SO U CAN PLAY AROUND WITH IT
                    return _NormalColor;
                return 0;
            }

```

---
Tags: unity, lighting, models, color
---


# Question
Title: Writing and reading Computebuffer in a Shader
I'm trying to write into a Computebuffer in the fragment shader, but it doesn't work. Its pretty hard to get the Depth-Value in the Compute Buffer, so it would be so easy to just use the Pixel/Fragment Shader instead the ComputeShader. But it doesn't seem to work.

Here is what this code is doing: First I'm creating a new Computebuffer and writing into a Computebuffer inside my C# code (a red screen)

After it's been written, I'm reading that buffer from a shader (works)

Next I'm using another shader to fill the buffer with some gradient. This should work - but it doesn't work.

When I'm reading the buffer again - I'm still seeing the red screen.

Does anyone here have an idea why? And how I can get to write things into the Computebuffer while I'm in the Fragment Shader?

My Code: (bufferscript.cs) (bind to Main Camera to test)

```
using UnityEngine;
using System.Collections;
using System.IO;

[ExecuteInEditMode]
public class bufferScript : MonoBehaviour
{
    public bool writeBufferOn;
    public bool readBufferOn;
    public ComputeBuffer myBuffer;
    public Material writeBufferMat;
    public Material readBufferMat;

    void Update()
    {
        if (readBufferMat == null)
        {
            readBufferMat = Resources.Load<Material>("readBufferMat") as Material;
        }
        if (readBufferMat.shader == null)
        {
            readBufferMat.shader = Resources.Load<Shader>("readBufferShader") as Shader;
        }
        if (writeBufferMat == null)
        {
            writeBufferMat = Resources.Load<Material>("writeBufferMat") as Material;
        }
        if (writeBufferMat.shader == null)
        {
            writeBufferMat.shader = Resources.Load<Shader>("writeBufferShader") as Shader;
        }
        if (myBuffer == null)
        {
            // initial fill buffer with red pixels
            myBuffer = new ComputeBuffer(Camera.main.pixelWidth * Camera.main.pixelHeight, 3*sizeof(float), ComputeBufferType.Default);
            float[] v = new float[Camera.main.pixelWidth * Camera.main.pixelHeight * 3];
            for (int c = 0; c < Camera.main.pixelWidth * Camera.main.pixelHeight * 3; c+=3)
            {
                v[c+0] = 1.0f;
                v[c+1] = 0.0f;
                v[c+2] = 0.0f;
            }
            myBuffer.SetData(v);
        }
    }

    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        if (writeBufferOn == true)
        {
            Graphics.ClearRandomWriteTargets();
            writeBufferMat.SetPass(0);
            writeBufferMat.SetInt("_width", Camera.main.pixelWidth);
            writeBufferMat.SetInt("_height", Camera.main.pixelHeight);
            writeBufferMat.SetBuffer("_myBuffer", myBuffer);
            Graphics.SetRandomWriteTarget(1, myBuffer);
            Graphics.Blit(source, destination, writeBufferMat);
            Graphics.ClearRandomWriteTargets();

            // expecting red/blue to be 0 and green with gradient from 0 to 1 across screen width
            float[] v = new float[Camera.main.pixelWidth * Camera.main.pixelHeight * 3];
            myBuffer.GetData(v);
            if (v[3 * 0 + 0] != 0.0f)
            {
                print("Still red, write to compute buffer failed!");
            }
        }
        if (readBufferOn == true)
        {
            Graphics.ClearRandomWriteTargets();
            readBufferMat.SetPass(0);
            readBufferMat.SetInt("_width", Camera.main.pixelWidth);
            readBufferMat.SetInt("_height", Camera.main.pixelHeight);
            readBufferMat.SetBuffer("_myBuffer", myBuffer);
            Graphics.Blit(source, destination, readBufferMat);
        }
    }

    //garbage collector extra
    void OnDisable()
    {
        if (myBuffer != null)
            myBuffer.Dispose();
        myBuffer = null;
    }
}

```

My Shader (readBufferShader)

```
Shader "custom/readBufferShader"
{
    SubShader
    {

        Pass
        {
            CGPROGRAM
            #include "UnityCG.cginc"
            #pragma target 5.0
            #pragma vertex vert
            #pragma fragment frag

            struct v2f
            {
                float4 pos : SV_POSITION;
                float4 uv : TEXCOORD0;
                float4 scrPos : TEXCOORD1;
            };

            //Vertex Shader
            v2f vert(appdata_base v)
            {
                v2f o;
                o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
                o.scrPos = ComputeScreenPos(o.pos);
                o.uv = float4(v.texcoord.xy, v.texcoord.z, 1);
                return o;
            }

            //Fragment Shader
            int _width;
            int _height;
            StructuredBuffer<float3> _myBuffer : register(u1);

            half4 frag(v2f i) : COLOR
            {
                int x = int(i.scrPos.x * _width);
                int y = int(i.scrPos.y * _height);
                float3 value = _myBuffer[(y * _width) + x]; // reading the buffer works
                return half4(value, 1);
            }

            ENDCG
        }
    }
}

```

My other Shader (writeBufferShader)

```
Shader "custom/writeBufferShader"
{
    SubShader
    {

        Pass
        {
            CGPROGRAM
            #include "UnityCG.cginc"
            #pragma target 5.0
            #pragma vertex vert
            #pragma fragment frag

            struct v2f
            {
                float4 pos : SV_POSITION;
                float4 uv : TEXCOORD0;
                float4 scrPos : TEXCOORD1;
            };

            //Vertex Shader
            v2f vert(appdata_base v)
            {
                v2f o;
                o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
                o.scrPos = ComputeScreenPos(o.pos);
                o.uv = float4(v.texcoord.xy, v.texcoord.z, 1);
                return o;
            }

            //Fragment Shader
            int _width;
            int _height;
            RWStructuredBuffer<float3> _myBuffer : register(u1);

            half4 frag(v2f i) : COLOR
            {
                int x = int(i.scrPos.x * _width);
                int y = int(i.scrPos.y * _height);
                _myBuffer[(y * _width) + x] = float3(0, i.scrPos.x, 0); // buffer should be written here, but nothing happens!
                return half4(1,1,1,1);
            }

            ENDCG
        }
    }
}

```

# Answer
> 1 votes
Well- it doesnt seem to work. Im not sure. After weeks, i gave up and I did a workaround. My Solution was:

1. Graphics.Blit() everything you need from the pixel shader into a RenderTexture
2. Put the RenderTexture inside a ComputeShader (Texture2D)
3. Inside the ComputeShader you can finally write into a buffer.

anyway, if anyone has a better solution for this problem- i would be glad to hear it.

# Answer
> 1 votes
Try to add `Graphics.SetRandomWriteTarget(1, myComputeBuffer, true);` in C# after you create your ComputeBuffer. The "1" represents the target index ie `u1`.

The other important part you already got right: `RWStructuredBuffer<MyStruct> _MyBuffer : register(u1);`

https://docs.unity3d.com/ScriptReference/Graphics.SetRandomWriteTarget.html

When you do `StructuredBuffer<MyStruct> _MyBuffer : register(t1);` then it's a read only buffer and it works. But a `RWStructuredBuffer`, requires `SetRandomWriteTarget` to work at all in a non-compute-shader. This is all Unity API magic which in some ways is convenient but at the same time doesn't help you figure it out, or figure the actual DirectX API out.

---
Tags: unity, shaders
---


# Question
Title: Determine the bullet / particle reflection off of a circle in node js using SAT lib functions
I can see how the calculation should occur from other examples such as: How to bounce a 2d point particle off of a circular edge.

But I could use some help with the specifics for my inputs given during a game loop that is progressing / moving the bullet each game loop tick, and then detecting and handling collisions.

I've tried to mock up an example nodejs script using the SAT lib http://requirebin.com/?gist=4a5c208dc39d3c3be262abb05fa791a3 .. with the console logs tracing a few variables, including the output target vector.

My question essentially lies in understanding how I can use the SAT vector functions like dot() or reflect() to produce the reflection?

https://github.com/jriecken/sat-js#classes

Even pseudo code would help me understand what exactly the operation needed to determine the reflection point (not just the angle, but the bullets new target vector) given my inputs of a bullet x,y position colliding with and a circular wall.

# Answer
No need to use dot() or reflect(). Use the conservation of energy to calculate the new velocity of the ball after collision with a stationary object.

A ball hitting a circle acts as if it hit a line tangent to the point on the circle. We actually use the normal vector to this tangent line (the collision normal), so there's no need to even calculate the tangent line!

The collision normal is simply the normalized vector that starts at the center of the circle and extends to the point of collision (on the circle.)

Given the collision normal n, we can calculate the new velocity of the ball using this pseudo-code:

```
function resolveFixedCollision(obj, n)
  set c to componentVector(obj.velocity, n)
  set obj.velocity to v-2*c
end function

```

**And explained in words:**

> ...split the vector v into two components, one in the direction n(the normal component) and the other in the direction of the wall (the tangential component). Because there are no forces acting on the ball in the tangential direction, its velocity in that direction remains unchanged. In the other direction, the velocity is simply reversed. This way, the energy of the ball, the only moving object in the collision, remains unchanged. The end result of this is that you can find the new velocity by simply subtracting twice the normal component.

Source: Mathematics and Physics for Programmers, p. 200-201

**Finally, I have implemented the above algorithm using SAT vector functions, as requested.** Click "Run code snippet" to see how the bullet moves. The meat of the logic is inside reflectBullet(). I also modified the representations of `a_beam_of_light` and `a_curved_mirror`:

* velocity and position changed to SAT.Vectors with x and y components
* moved the initial position of the bullet so its path before collision is more visible
* Used SAT.Circle instead of creating new SAT.Circles each time testCircleCollision() is called

```
var reflectBullet = function(bullet, wall, sat_response) {

  function resolveFixedCollision(obj, n) {
    // Set c to componentVector(obj.velocity, n).
    var c = new SAT.Vector();
    c.copy(obj.v);
    c.project(n);

    //set obj.velocity to v-2*c
    c.scale(2, 2);
    obj.v.sub(c);
  }

  // The collision normal
  var n = new SAT.Vector(wall.c.pos.x - bullet.c.pos.x,
                         wall.c.pos.y - bullet.c.pos.y).normalize();

  // Calculate new velocity of bullet after collision
  resolveFixedCollision(bullet, n);

  // Move bullet to point of collision (if it went through wall)
  bullet.c.pos.sub(sat_response.response.overlapV);
}

var testCircleCollision = function(a, b) {
  var response = new SAT.Response();
  var collided = SAT.testCircleCircle(a.c, b.c, response);

  return {
    collided: collided,
    response: response
  };
};

var a_beam_of_light = {
  c: new SAT.Circle(new SAT.Vector(25 - 15, 40), 1),
  // x: 25,
  // y: 40,
  // r: 1,

  v: new SAT.Vector(1, 0)
  // v: 1,
  // origX: 0,
  // origY: 40,
  // targetX: 50,
  // targetY: 40,
}

var a_curved_mirror = {
  c: new SAT.Circle(new SAT.Vector(50, 50), 25)
  // x: 50,
  // y: 50,
  // r: 25
}

var step_world = function() {
  // step the world forward, moving the bullet towards it's target
  a_beam_of_light.c.pos = a_beam_of_light.c.pos.add(a_beam_of_light.v)
  // a_beam_of_light.x = a_beam_of_light.x + a_beam_of_light.v;

  // console.log(a_beam_of_light, a_curved_mirror)
  var test_results = testCircleCollision(a_beam_of_light, a_curved_mirror);
  if (test_results.collided) {
    reflectBullet(a_beam_of_light, a_curved_mirror, test_results);
  }
}

var el = document.getElementById('c');
var ctx = el.getContext('2d');

// draw a SAT.Circle
function renderCircle(c) {
  ctx.beginPath();
  ctx.arc(c.pos.x, c.pos.y, c.r, 0, 2 * Math.PI);
  ctx.stroke();
}

renderCircle(a_curved_mirror.c);
renderCircle(a_beam_of_light.c);
for (var x = 0; x < 40; x++) {
  step_world();
  if (x % 5 == 0) {
    renderCircle(a_beam_of_light.c);
  }
}
```

```
canvas {
  border: 1px solid #ccc
}
```

```
<script src="https://cdnjs.cloudflare.com/ajax/libs/sat/0.6.0/SAT.min.js"></script>
<canvas id="c" width="500" height="150"></canvas>
```
> 1 votes

---
Tags: collision-detection, physics, geometry
---


# Question
Title: game physics: contact constraint and relative velocity
For two rigidbodies (2D boxes), A and B, I have been colliding A with B and finding the collision normal pointing towards A i.e. the direction that would separate A from B. When it comes to calculating the relative velocity for the contact constraint, does it matter which body has the edge that the collision normal is perpendicular in terms of which velocity to subtract from which?

# Answer
If I understood the quesion, NO.

Here follows a simple resolvecollision , from How to Create a Custom 2D Physics Engine: The Basics and Impulse Resolution , as you can see you put yourself in object A frame of reference , then subtract collision impulse from A and add it to B.

```
void ResolveCollision( Object A, Object B )
{
  // Calculate relative velocity
  Vec2 rv = B.velocity - A.velocity

  // Calculate relative velocity in terms of the normal direction
  float velAlongNormal = DotProduct( rv, normal )

  // Do not resolve if velocities are separating
  if(velAlongNormal > 0)
    return;

  // Calculate restitution
  float e = min( A.restitution, B.restitution)

  // Calculate impulse scalar
  float j = -(1 + e) * velAlongNormal
  j /= 1 / A.mass + 1 / B.mass

  // Apply impulse
  Vec2 impulse = j * normal
  A.velocity -= 1 / A.mass * impulse
  B.velocity += 1 / B.mass * impulse
}

```

Be carefull not to re-execute resolvecollision(B,A) as you has already execuitetd resolvecollision(A,B), even if :

```
  // Do not resolve if velocities are separating
  if(velAlongNormal > 0)
    return;

```

may prevent this.
> 2 votes

---
Tags: physics, collision-resolution
---


# Question
Title: The value of animation parameter is not changing?
Code:

```
var click=false;
var anmtr:Animator;

function Update () {

if(Input.GetButtonDown("Fire1")){

    click=!click;
    anmtr.SetBool("clk",click);
}

if(Input.GetButtonUp("Fire1")){

     click=!click;
}

```

}

The value of click variable in inspector is changing as I click and release the mouse button.But the value of the Animation parameter is changed from false to true on first button down event and then it stays true forever even after releasing the mouse. No matter how many times I click the mouse button it stays true. But not the variable click it changes as expected.

# Answer
> 0 votes
The reason is, when you release the button, you don't update the anmtr; Since you are just toggling the bool in both if's, you could simply do this:

```
if(Input.GetButtonDown("Fire1") || Input.GetButtonUp("Fire1") ){
    click=!click;
    anmtr.SetBool("clk",click);
}

```

Why? Easier to read.

---
Tags: unity, unityscript
---


title: Bezier curve arc length

text:
# Question
Title: Bezier curve arc length
> **See also:** same question on Math.SE

How can I find the arclength of a Bezier curve? For example, a linear Bezier curve has the length:

```
length = sqrt(pow(x[1] - x[0], 2) + pow(y[1] - y[0], 2));

```

But what about quadratic, cubic, or n-degree Bezier curves?

(My goal was to estimate a sampling resolution beforehand, so I don't have to waste time checking if the next point is touching the previous point.)

# Answer
A simple way for cubic Beziers is to split the curve into N segments and sum the segments' lengths.

However, as soon as you need the length of only part of the curve (e.g. up to a point 30% of the length along), *arc-length parameterization* will come into play. I posted a fairly long answer on one of my own questions about Béziers, with simple sample code.
> 11 votes

# Answer
Arc lengths for Bezier curves are only closed form for linear and quadratic ones. For cubics, it is not guaranteed to have a closed solution. The reason is arc length is defined by a radical integral, for which has a closed for only 2nd degree polynomials.

Just for reference: The length of a quadratic Bezier for the points (a,p) (b,q) and (c,r) is

$$ \frac{(a^2(q^2 - 2qr + r^2) + 2a(r - q)(b(p - r) + c(q - p)) + (b(p- r) + c(q - p))^2)\ln{\frac{\sqrt{a^2 - 2ab + b^2 + p^2 - 2pq + q^2} \sqrt{a^2 + 2a(c - 2b) + 4b^2 - 4bc + c^2 + (p - 2q + r)^2} \+ a^2 + a(c - 3b) + 2b^2 - bc + (p - q)(p - 2q + r) }{\sqrt{a^2 + 2a(c - 2b) + 4b^2 - 4bc + c^2 + (p - 2q + r)^2} \sqrt{b^2 - 2bc + c^2 + q^2 - 2qr + r^2} + a(b - c) - 2b^2 + 3bc - c^2 + (p - 2q + r)(q - r)}}}{a^2 + 2a(c - 2b) + 4b^2 - 4bc + c^2 + (p - 2q + r)^2}^\frac{3}{2} + \frac{\sqrt{(a^2 - 2ab + b^2 + p^2 - 2pq + q^2) (a^2 + a(c - 3b) + 2b^2 - bc + (p - q)(p - 2q + r)) - \sqrt{b^2 - 2bc + c^2 + q^2 - 2qr + r^2} (a(b - c) - 2b^2 + 3bc - c^2 + (p - 2q + r)(q - r))}}{a^2 + 2a(c - 2b) + 4b^2 - 4bc + c^2 + (p - 2q + r)^2} $$

Hence, it should be easier and cheaper approximate the arc by some other rule, like a polygon or an integration scheme like Simpson's rule, because square roots the LN are expensive operations.
> 9 votes

# Answer
While I am d'accord with the answers you got already, I want to add a simple but powerful approximation mechanism which you can use for any degree Bézier curves: You continually subdivide the curve using de Casteljau subdivision until the maximum distance of the control points of a sub-curve to the sub-curve's baseline is below some constant *epsilon*. In that case the sub-curve can be approximated by its baseline.

In fact, I believe this is the approach usually taken when a graphics subsystem has to draw a Bézier curve. But do not quote me on this, I do not have references at hand at the moment.

In practice it will look like this: (except the language is irrelevant)

```
public static Line[] toLineStrip(BezierCurve bezierCurve, double epsilon) {
    ArrayList<Line> lines = new ArrayList<Line>();

    Stack<BezierCurve> parts = new Stack<BezierCurve>();
    parts.push(bezierCurve);

    while (!parts.isEmpty()) {
        BezierCurve curve = parts.pop();
        if (distanceToBaseline(curve) < epsilon) {
            lines.add(new Line(curve.get(0), curve.get(1)));
        } else {
            parts.addAll(curve.split(0.5));
        }
    }

    return lines.toArray(new Line[0]);
}

```
> 4 votes

# Answer
I worked out the closed form expression of length for a 3 point Bezier (below). I've not attempted to work out a closed form for 4+ points. This would most likely be difficult or complicated to represent and handle. However, a numerical approximation technique such as a Runge-Kutta integration algorithm would work quite well by integrating using the arc length formula. My Q&A on RK45 on MSE may help with RK45 implementation.

Here is some Java code for the arc length of a 3 point Bezier, with points `a`,`b`, and `c`.

```
    v.x = 2*(b.x - a.x);
    v.y = 2*(b.y - a.y);
    w.x = c.x - 2*b.x + a.x;
    w.y = c.y - 2*b.y + a.y;

    uu = 4*(w.x*w.x + w.y*w.y);

    if(uu < 0.00001)
    {
        return (float) Math.sqrt((c.x - a.x)*(c.x - a.x) + (c.y - a.y)*(c.y - a.y));
    }

    vv = 4*(v.x*w.x + v.y*w.y);
    ww = v.x*v.x + v.y*v.y;

    t1 = (float) (2*Math.sqrt(uu*(uu + vv + ww)));
    t2 = 2*uu+vv;
    t3 = vv*vv - 4*uu*ww;
    t4 = (float) (2*Math.sqrt(uu*ww));

    return (float) ((t1*t2 - t3*Math.log(t2+t1) -(vv*t4 - t3*Math.log(vv+t4))) / (8*Math.pow(uu, 1.5)));

```
> 2 votes

---
Tags: mathematics, graphics, beziers, heuristics
---


# Question
Title: How do we generate overhangs with simplex noise 3d?
Now I use a simplex noise 2d function with x( voxel's x location ) and y(voxel's y location) to generate heightmap. How do we use simplex noise 3d to generate overhangs? What should the x y z inputs be? Pseudo code would help a lot.

# Answer
2D Perlin noise is used to generate a heightmap. This heightmap is then converted to a mesh for the renderer.

```
float[,] heights;
// initialize the map using some 2D height function.
foreach (i, j):
    heights[i,j] = noise2D(i, j);
// convert the data to a mesh
foreach(cell in heights):
    generate a square with corners at (x,y,heights[x,y]), (x+1,y,heights[x+1,y]), (x,y+1,heights[x,y+1]), (x+1,y+1,heights[x+1,y+1])

```

3D Perlin noise is used to generate basically a density map. If the "density" at a 3D point is greater than a threshold, you "generate" a block at that point

```
// for the sake of the demo, this is a bool.
// Realistically you'd have some struct that allows for different block types
bool[,,] isSolid;
// initialize the map using some 3D density function
foreach (i, j, k):
    isSolid(i, j, k) = noise3D(i, j, k) > 0.5
// convert the data to a mesh
foreach i,j,k:
    if isSolid[i,j,k]:
        generate a unit cube centered at i, j, k.

```

Of course, the above code simplifies some things -- you could use less naive meshing strategies like marching cubes or dual contouring. the density function gets more dense with depth if you want "ground at the bottom, sky at the top, etc."
> 2 votes

---
Tags: terrain, voxels
---