# Question
Title: opengl - flickering of fragments even with disabled depth test
I'm trying to render a quad with a coloured border. I'm using texture coordinates to detect whether the fragment should be considered part of border or not. If it is part of border, then render it with green colour or else with black colour.

Here are my vertices / normals / tex coordinates.

```
    float vertices[] = {
        // posistions          // normals           // texture coords
      -0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f,  0.0f,
       0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f,  0.0f,
       0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f,  1.0f,
       0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f,  1.0f,
      -0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f,  1.0f,
      -0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f,  0.0f,
    }

```

Here's my fragment shader

```
#version 330 core

in vec3 frag_pos;
in vec3 frag_nor;
in vec2 frag_tex;

out vec4 frag_color;

void main()
{
    vec2 origin = vec2(0.01, 0.01);

    float width =  1.0 - origin.x * 2.0;
    float height = 1.0 - origin.y * 2.0;

    if( (frag_tex.x >= origin.x && frag_tex.x < origin.x + width) &&
        (frag_tex.y >= origin.y && frag_tex.y < origin.y + height) )
    {
        frag_color = vec4(0.0);
    }
    else
    {
        frag_color = vec4(0.0, 1.0, 0.0, 0.0);
    }
}

```

And this is how I'm rendering

```
glDisable(GL_DEPTH_TEST);
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, 6);

```

In right, I'm drawing the same quad with another pass-through fragment shader in wireframe mode.

As you can see the left quad is flickering while moving the camera. Any ideas how to fix this.

# Answer
> 2 votes
I think your problem is that your border checking is too exact. You should use an epsilon value, which looks like, rather than saying `x = 0`, `abs(x) < EPSILON`. In your case, that would look like

```
if(
  abs(frag_tex.x - origin.x) >= EPSILON &&
  abs(frag_tex.x - origin.x - width) < EPSILON) &&
  abs(frag_tex.y - origin.y) >= EPSILON &&
  abs(frag_tex.y - origin.y - height) < EPSILON
)

```

(Unless I've made a typo. I would advise retyping this in an IDE to avoid a potentially missing parenthesis or something).

Then, at the top of the shader, just add the line `float EPSILON = 0.1;`. Now `EPSILON` controls how thick the borders are! If they're too big, just make `EPSILON` smaller.

---
Tags: opengl, shaders, textures
---


# Question
Title: How can I use Unity Assets made by Unity in a commercial project?
I know you can't use starter and training etc.. assets made by Unity for commercial purposes, but according to this every Unity asset made by Unity is restricted for commercial use. So that means I can't use Post Processing Stack? That would be disappointing.

# Answer
> 3 votes
Re-reading the page you linked to, we can see that you *can* use the assets from the assets store in a commercial game.

> You can purchase assets from the Asset Store and use them personally and commercially in your game.

and

> Once you have purchased an asset from the store, it becomes yours to do with as you like within your games and apps. You will be able to use them in your game for commercial use with no extra payments.

Now, as you mention *Restricted*, so here is what is says about *restricted*:

> Unity "Restricted Assets" are subject to restrictions that others are not. These are only valid for personal and non-commercial use only. No other use is permitted, and these Unity assets must not be used in your commercial games.

**This means that *Restricted Assets* can't be used in your commercial game, while others can, paid or not.**

Since there is no "license" sections on these Assets Store pages, it's a bit hard to know at a glance which one is a *Restricted Asset*, and which one is not. Searching around, you'll notice that the restriction is written in the asset description. You can see a couple examples searching via Google.

The asset you want, Post Processing Stack, does not have such restriction, while some others do, such as Windridge City, Melodrive Lite Beta or ADAM EP2/EP3 - Alembic Timeline Sample.

---
Tags: unity, assets, licensing
---


# Question
Title: Is it legal to imitate a game without publishing it
If you're developing a game that's very similar to a game that's already published, both the game mechanics and the graphics but you're not publishing it, instead you're keeping it in your own computer. Is it legal to do so?

# Answer
> 3 votes
Generally speaking, copyright law does not have an exclusion for "private use" or similar (depending, perhaps, on your jurisdiction). Violating copyright is violating copyright, regardless of whether or not you then *further* redistribute the work by making additional copies for "publication."

So no, it is not legal.

Of course, that doesn't stop people from doing it. From a practical perspective, of course, it's unlikely anybody could discover your violation. That doesn't make it "okay," but it significantly decreases the risk factor in many peoples' minds. Often you will not see entire games copied, but people using bits and pieces of artwork as "placeholders," et cetera.

Personally I wouldn't recommend this - it's *very* easy to accidentally keep a piece of copyrighted artwork in a game when you actually ship it, for example.

There's also "fair use" doctrine in some places, like the US, which is a defense for certain limited kinds of use such as parody or education. It's important to note that this is a *defense*, which means you have to be taken to court to prove your case, so it's not something you should rely on if your goal is to *avoid* being sued.

Note that none of this applies to imitating "game mechanics" or ideas. Those cannot be covered by copyright. Copyright covers work in fixed form, such as art and sound.

# Answer
> -1 votes
I don't see why not. If you are keeping the game to yourself (not publishing it) it would be fine. Some companies may even allow you to publish an imitated copy of their game as long as you aren't making money off of it (ad revenue, making the game cost money, etc). It would be helpful if you could edit your question so that we know what game you are planning to imitate, but overall it should be legal, as long as you don't publish it.

---
Tags: legal, copyright
---


# Question
Title: One VAO takes more time than more than 40 put together despite being simpler
I was running visual studio's CPU profiling tool when I noticed that of my RenderScene call, my skybox was taking up 30% of the frame time.

This is particularly weird, as as you can see the Object3D::draw call is much less, and I have just one Skybox and 35 Object3Ds.

I went in further and found that glBindVertexArray was taking all of the time. What could be causing this? The VAO in question is defined here:

```
    glGenVertexArrays(1, &thisVAO);
glBindVertexArray(thisVAO);

//Setup the Vertex buffer
glGenBuffers(1, &vertsVBO);
glBindBuffer(GL_ARRAY_BUFFER, vertsVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*36, skyboxVertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)0);
glEnableVertexAttribArray(0);

```

and the Skybox Draw call here:

```
//Shader uniform setting....
    glUseProgram(thisConfig.skyboxShaders->getProgramID());
// ... set view and projection matrix

thisConfig.skyboxShaders->setMats(rs->angle, thisConfig.currLighting->persp);

thisConfig.skyboxShaders->setClipPlane(rs->clipPlane, rs->useClipPlane);

//Actually draw the skybox
glBindVertexArray(thisVAO);

glActiveTexture(GL_TEXTURE0);

glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);

glDrawArrays(GL_TRIANGLES, 0, 36);

```

Here is visual studio's take on the draw call:

VAOs for Object3D have 5 VBOs and an elements buffer, as opposed to skybox's one VBO, and skyboxVerticies has 96 entries in it for 36 verticies. Most meshes for object3Ds are 1000+ verticies plus, and the Terrain has 48,000. Anything obvious I am missing? The vertex co-ordinates are very large, would that affect the call time for glBindVertexArray()?

Edit : skybox shader

```
#version 330 core
layout (location = 0) in vec3 aPos;

out of TexCoords;

uniform mat4 projection;
uniform mat4 view;
uniform vec4 clipPlane; // The Plane Clipping
uniform int usePlane; // PLane bool

void main ()
{
    TexCoords = aPos;
    gl_Position = view * vec4 (aPos, 1.0);
}

```

Edit : Changing the order has changed things completely, It appears the first glBindVertexArray() per frame has significant overhead (30% of each frame), regardless of shader or vertex array size. Why is this? How can I fix it?

# Answer
> 1 votes
Could just be some flush that gets triggered.

What happens if you switch the order or drawing? First drawing sky then objects, versus first the objects and then the sky?

Also, what does the fragment shader look like for the sky? Maybe it takes a lot of texture samples? Are the objects textured as well?

Last, the skybox covers a lot of pixels, so the fragment shader will be busier than the fragment shader of an object that is small on screen.

---
Tags: opengl, c++
---


# Question
Title: Isometric Game World Boundaries Equation
I ran into a problem last night and I can't solve it since. I'm making an isometric game based on tiles with equal rows and columns. Now I made moving entities which should turn whenever they reach the boundaries of the world. As I illustrated on the picture they are turning back on the upper boundaries (green) , but not on the lower ones (red). I tried various equations on the lower part, but i cannot figure out for the life of me what is the lower parts code. What would be an appropriate solution for the shrinking lines?

`boolean checkBounds(){
 float absX = Math.abs(getX());
 float absY = Math.abs(getY());
 if(absY*2-absX<0 || ??? ) return false
 else return true;
 }`

# Answer
> 0 votes
To elaborate on what DMGregory said... you don't want to imagine them moving on diamond tiles, but rather imagine them moving on the ordinary grid you've set up as a 2D array in memory. *That* is what you do your movement and collision detection / resolution on; at least at this early stage.

This way your transition between (unoccupied) tiles becomes a simple fractional value, for example, `xFractionToNextCell == 0.4` means you're 40% of the way on your movement to the next tile, in `x`. You can do the same for `y`. Once it hits `1.0` AND you are at the edge of the map, you can turn.

Using the view-transformed grid just unnecessarily complicates things in this regard. So rather work in the original 2D array co-ordinates.

---
Tags: libgdx, isometric, tiles
---


# Question
Title: Is there a way to automatically group tiles in a A* pathfinding grid to find the largest areas?
I'm making an RTS game using html canvas. I've made a program that randomly generates levels in order to test my pathfinding script. it divides the pathable blocks into squares so that you can apply A\* pathfinding to it.

While this is all well and good, I'm more fond of Navmeshes, as the movement in them is more natural, and units move directly to their goal instead of taking jagged routes across blocks.

Mike West has the best implementation of this in HTML, which you can find here: JS navmesh

In this script, however, navmeshes cannot be generated on the fly. with this in mind, I'd like to create a script that analyses the entire level and groups together the largest possible areas in the entire map while **only** using rectangles and squares.

Ideally, it would look like this:

So far, I have yet to come up with a solution. the script would have to scan the level and then look at it objectively to find the largest areas. I'm sure something like this has yet to be done before, though I can find no trace of it. what do you think?

```
var Tile = [[1, 1, 1, 1, 1, 1, 1, 1],
            [1, 0, 0, 0, 0, 0, 0, 1],
            [1, 0, 0, 0, 0, 0, 0, 1],
            [1, 0, 0, 0, 0, 0, 0, 1],
            [1, 0, 0, 0, 0, 0, 0, 1],
            [1, 0, 0, 0, 0, 0, 0, 1],
            [1, 0, 0, 0, 0, 0, 0, 1],
            [1, 1, 1, 1, 1, 1, 1, 1]];

$( document ).ready(function(){
  $('#GenerateButton').click(function() {
    GenTiles();
    CreateNavMesh();
  });
});

function GenTiles(){
  $('#window').html('');

  var terrainString ="";
   for (var x = 0; x < Tile.length; x++){
    terrainString += '<div class="row">';
    for (var y = 0; y < Tile[x].length; y++){
        var dirt = '<div class="tileGround" id='+ x + '|' + y +'></div>';
        var wall = '<div class="tileWall"  id='+ x + '|' + y +'></div>';
        switch(Tile[x][y]){
      case 0:

            if (Math.random() > 0.3){
              terrainString += dirt;
            }
            else {
              terrainString += wall;
            }

      break;

      case 1:
       terrainString += wall;
      break;
     }

    }
    terrainString+='</div>';
   }
   $('#window').append(terrainString);
}

function CreateNavMesh(){
  /*

  var mainDiv = $("#window").children().toArray();
  console.log(mainDiv[0][0]);
  for (var x = 0; x < mainDiv.length ; x++){
    console.log(mainDiv[x].children().toArray());
    for (var y = 0; y < mainDiv[x].length; y++){
      console.log(mainDiv[x],[y]);
      if(mainDiv[x],[y] == 0){
          mainDiv[x],[y].addClass('.highLight');
      }
      else {
        chosCol = back[Math.floor(Math.random() * back.length)];
      }

    }
      }
    */
    var back = ["#ff0000","blue","gray", "purple"];
    var rand = back[Math.floor(Math.random() * back.length)];
    var chosCol = rand;
    $( ".row" ).each(function() {
      $(this).children().each(function(){
          console.log($( this ));
          if($(this).hasClass("tileGround")){
              $(this).css("background-color", chosCol);;
          }
          else {
            //chosCol = getRandomColor();
          }
      });
    });
  }

  function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}
```

```
#window{
  width: 240px;
  height: 240px;
  overFlow: auto;
}

.row{
  display: block;
  float: none;
  position: relative;
  height: 30px;
}

.tile{
  background-color: #ddd;
  width: 30px;
  height: 30px;
  float: left;
}

.tileWall{
  background-color: #333;
  width: 30px;
  height: 30px;
  float: left;
}

.tileGround{
  background-color: #fff;
  width: 30px;
  height: 30px;
  float: left;
}

.highLight{
  background-color: #444;
}
```

```
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="code.js" type="text/javascript"></script>
  </head>

  <body>
    <div id="window">
    </div>
    <button id="GenerateButton">Generate Grid</button>
  </body>

</html>
```

# Answer
> 1 votes
I've heard this called "Room Generation" when used as an optimization to speed up A\*. The only algorithm I know of is **Rectangular Symmetry Reduction** *(though there are probably more)*

It is described in these two papers1,2. Daniel Harabor *(one of the creators of both RSR and the more well-known "Jump Point Search")* has a blog post about it here, which is where I took the image from.

I don't know enough about it to describe its implementation here, but this should get you started.

---

1. D. Harabor, A. Botea and P. Kilby. 2011. Path Symmetries in Uniform-cost Grid Maps.
2. D. Harabor and A. Botea. 2010. Breaking Path Symmetries in 4-connected Grid Maps.

---
Tags: path-finding, html5, html-canvas, navmesh, html
---


title: libgdx custom shape overlap detecting

text:
# Question
Title: libgdx custom shape overlap detecting
I'm writing my game on libgdx w/o any of those extensions like box2d and whatsoever. But right now I'm forcing problem with overlapping detection. I need to detect if bullet (which is always in different degree) overlapped my rocket. At first I was using Rectangle, but it sometimes is giving me false overlap.

I have visualized it.

How it is now:

My goal:

as you see I also want to make bullets rectangle rotated so it was more accurate. And as I said earlier I need to detect collision/overlapping between these polygons. Do I need to use that box2d extension??? Because right now I've written working prototype entirely w/o it.

# Answer
> 1 votes
Polygon A is overlapping polygon B if any of its vertices is inside B and vice versa.

```
bool isOverlap(Polygon A, Polygon B){
  foreach(Vertex v in A)
  {
    if(isInside(v, B))
      return true;
  }
  foreach(Vertex v in B)
  {
    if(isInside(v, A ))
      return true;
  }
  return false
}

bool isInside(Vertex v, Polygon p)
{ //you can choose either Crossing Number or Winding Numer, you can google implementation
}

```

if you use Winding Number, the collision will be even for complex polygons. However I advice you to stick axis-aligned to bounding boxes as detection is fast and simple, plus you can make the boxes smaller then you sprite. That would give you nearly same results(from player perspective) as polygon-perfect algorithm.

# Answer
> 0 votes
There's a faster way to accomplish this nowadays, you will need to be using the `com.badlogic.gdx.math.Polygon` class for your game entities' collision shapes.

```
Intersector.overlapConvexPolygons(polygonA, polygonB);

```

The `Polygon` class also has a `rotate(float degrees)` method, as well as getters and setters for rotation.
Polygon LibGDX API Reference
Intersector LibGDX API Reference

---
Tags: libgdx, collision-detection
---


# Question
Title: Is it legal to use a generic celebrity names in a card game?
Before tagging this as a duplicate to Legality of using names in a game?, please be aware that it is a more special case than that generic question

So I am working on a card game similar to Cards Against Humanity, where some cards would have celebrities names, the case I am interested in is if the celebrity name is too generic that they can't really claim that this name can only be them, specially there is no context where their field of famous is referred to to confirm the identity.

Example

Lady Gaga - no one can argue that this name doesn't refer to the known celebrity.

But

Will Smith - is too generic, searching linkedin or facebook you will find thousands of people called Will Smith.

I guess if the card says the actor Will Smith then that is different.

Am I wrong in this assumption?

# Answer
Remember that the law is not interpreted by an inflexible computer program or robot, but by human lawyers and judges. Reasoning, intelligent people who are entirely capable of calling you on it if you try to fool them.

In this case, if your game was as engaging to play using names of nobodies, you wouldn't even need to ask this question. You could just use completely generic names with not even a coincidental link to famous people.

The reason you want to use recognizable names like "Will Smith" is that you're counting on name recognition — you can reasonably expect players will interpret this to mean *the* Will Smith, the famous actor, not one of the randos you found on LinkedIn. Associating this known person, and things players think & know about them, with the cards and events in your game, is a source of amusement that helps make your game more entertaining.

This is obvious to you, it's obvious to us, and it will be obvious to Will Smith's agent and legal representation. If they decide they don't approve of your use of his identity and brand and decide to take you to court, it will also be obvious to the judge presiding over the case that you're drawing benefit from unauthorized use of this famous person's identity.

In some jurisdictions you might be able to claim "fair use" or "parody," but it's important to note that this is a *defense* you could try to use in court, not a way to prevent being sued in the first place. You could still lose, or pay a substantial amount of time and money arguing your case even if you win.

So, the safest bet is to seek permission when you want to use anything that belongs to someone else — including their name.
> 2 votes

# Answer
Some names are too generic or common but even then, if the card has he's face on it or something like that you can get into trouble. Also if your game doesn't become famous and stuff, you will hardly get any problems. It's basically a matter of common sense, although some rights knowledge can keep you safe
> 0 votes

---
Tags: copyright
---


# Question
Title: Programmatically generated mesh vertex colors not showing up in Unity?
I'm sorry if this is an obvious thing to solve but I just can't figure it out...did I miss something...I've generated a mesh and during vertices generation I've also set its colors (and colors32 just in case) by reading those values from a ply file, and afterwards I've added a number of vertex color shaders but none of them will show the vertex point colors in play mode, it's either solid black or just like I added no material to the mesh (which I've tried doing manually in play mode too).

Did I miss something please?

# Answer
> 0 votes
Welcome, it's hard to tell with you not showing any code or explaining further what you've done :)

Does your shader handles vertex colors ?

If not then here's a quick example:

```
Shader "Unlit Vertex Color"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            // make fog work
            #pragma multi_compile_fog

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
                float4 color : COLOR;
            };

            struct v2f
            {
                float4 color : COLOR;
                float2 uv : TEXCOORD0;
                UNITY_FOG_COORDS(1)
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            fixed _Brightness;
            fixed _Gamma;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                o.color = v.color;
                o.color.w = 1.0;
                //UNITY_TRANSFER_FOG(o,o.vertex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // sample the texture
                fixed4 col = tex2D(_MainTex, i.uv);
                col *= i.color;
                // apply fog
                UNITY_APPLY_FOG(i.fogCoord, col);
                return col;
            }
            ENDCG
        }
    }
}

```

I just pass `COLOR` semantic to where necessary and blend the result with the pixel.

You can get started writing your own by templating some of the shaders from the builtin ones:

https://unity3d.com/get-unity/download/archive

If you want Standard shader with vertex colors (unofficial):

https://forum.unity.com/threads/standard-shader-with-vertex-colors.316529/

Also, Unity is apparently going to release an official standard shader with vertex colors.

---
Tags: unity, vertex, color
---


# Question
Title: Moving panel between two positions smoothly?
I'm trying to make my panel moving from one position to another one smoothly. What I get is more faster no matter what I did to make it slower never get slow !! Both Vector3.Lerp and Vector3.MoveTowards did not give me a slow movement. Here is my script:

```
public GameObject gunsWindow;
private Vector3 a, b;
public bool open; // use inspector
void Start()
{
    a = gunsWindow.transform.position;
    b = new Vector3(100.0f, gunsWindow.transform.position.y, gunsWindow.transform.position.z);
}

void Update()
{

    if(open)
    {
        gunsWindow.transform.position = Vector3.MoveTowards(a, b, Time.deltaTime * 1);
        //weaponPlane.transform.position =  Vector3.Lerp(a, b, Time.deltaTime); // panel shaking
    }
    else
    {
        gunsWindow.transform.position = Vector3.MoveTowards(b, a, Time.deltaTime * 1);
        //weaponPlane.transform.position =  Vector3.Lerp(b, a, Time.deltaTime); // shaking
    }

}

```

# Answer
> 3 votes
You're using both of these functions incorrectly.

## Using MovePosition

```
gunsWindow.transform.position = Vector3.MoveTowards(a, b, Time.deltaTime * 1);

```

Here, the first argument is where we want to start from *this frame*. So we don't want to pass `a` here, we want the current value of `gunsWindow.transform.position`. That gives us the memory of the movement accomplished thus far, that we can add onto with this frame's increment.

Your last argument is the distance to travel, so you can make the motion faster or slower by changing the coefficient `1` to a speed variable.

## Using Lerp

```
weaponPlane.transform.position = Vector3.Lerp(a, b, Time.deltaTime);

```

Here, the last argument is your total progress from `a` to `b`, not the incremental movement to apply this frame.

So you'll want to set aside a member variable to accumulate this progress from frame to frame (outside your function):

```
float slideProgress = 0f;

```

This gives us the memory of movement accomplished thus far. We then increase it each frame in update:

```
slideProgress = Mathf.Clamp01(slideProgress + Time.deltaTime / slideDuration);

```

And finally, do the linear interpolation using this progress measure:

```
weaponPlane.transform.position = Vector3.Lerp(a, b, slideProgress);

```

Or, you can use the `Lerp` function to perform an exponential ease-out as described in this answer.

---

As general advice, don't neglect to read the docs for the methods you're using, to ensure you're calling them with the correct arguments for your desired outcome.

# Answer
> 2 votes
To make your panel move slower, you just need to make the last number you pass `MoveTowards` smaller. Add a public variable at the top, then replace the `1` in your code with it. Something like this:

```
public GameObject gunsWindow;
public float moveSpeed;
public bool open;

private Vector3 a, b;

void Start()
{
    a = gunsWindow.transform.position;
    b = new Vector3(100.0f, gunsWindow.transform.position.y, gunsWindow.transform.position.z);
}

void Update()
{

    if(open)
    {
        gunsWindow.transform.position = Vector3.MoveTowards(gunsWindow.transform.position, b, Time.deltaTime * moveSpeed);
    }
    else
    {
        gunsWindow.transform.position = Vector3.MoveTowards(gunsWindow.transform.position, a, Time.deltaTime * moveSpeed);
    }

}

```

Now, using the inspector, you should make moveSpeed very small. This number is how many units you want to move per **frame**, so if it's 0.05 (1/20), your panel will be moving at three units per second. That said, your panel is moving 100 units, so maybe you want something more like 30 units per second, or 0.5.

---
Tags: unity, gui
---


# Question
Title: How can I make a spline that does not overshoot?
I have a list of line segments that run through a track model and I am looking to achieve two things:

* smooth the overall shape of the path
* being able to evaluate a position by querying from `0.0` to `1.0`

I have implemented Catmull-Rom spline using the `TreeSpline` class from Unity (it's not explicitly in the docs but you can see it here), it does work except for one thing: some places have overshoot:

Legend

* purple: original line segments
* white: result of the `TreeSpline` evaluation

After searching for a bit, it appears that Monotone cubic interpolation would be a solution to my problem. However, the formulas only show on how to do with 2D points, not with 3D points which I'm using.

**Question:**

How can I adapt the formulas in the Wikipedia article to 3D points instead ?

(I am also open to alternative approaches)

**Edit:**

Thanks to @Jay it's better now:

# Answer
Catmull-Rom splines are easy to use because they automatically generate a smooth line, or tangent, at each node. The tangent is computed from the position of neighbouring nodes which can cause weird issues in certain cases.

If the nodes are very far apart then the tangents will be very wide. If the nodes are close then the tangents will be short. If the nodes are far on one side and close on the other then the spline will have to loop around to remain smooth at both nodes.

This is kind of a long explanation of what you found in the image but it's how this kind of spline works.

Possible solutions are

* To have even spacing between each of the spline points. There are tools to generate this if there are too many.
* Use a different kind of spline. For example, a cubic b-spline is similar but allows you to manually adjust the tangents.
* Add dummy nodes. If you can't fix the spacing issue completely, then try adding a few extra nodes that transition from a straight section to a corner.
> 1 votes

---
Tags: splines
---


title: Make Build and Run faster

text:
# Question
Title: Make Build and Run faster
Is there a way to build an apk faster? (by disabling some shader compilation, for example Hidden/Post FX/Uber Shader takes most of the build time)

p.s. Yes I know about Unity Remote and use it - this time I need exactly Build and Run.

# Answer
Compilation in Unity can be broken down into a few steps:

First is resource compilation. Basically, this is where Unity takes all of your scenes and packages them up. It is during this part that shaders are compiled. However, shaders only need to be compiled when they change. If you make multiple builds in a row, without making any changes to materials that might cause a shader to compile differently, and you don’t change targets to, for example, standalone PC, or clear the library, then the shader compilation is not something you need to worry about.

You can shorten this section of compilation further by simply removing scenes you aren't testing from the build temporarily (uncheck the checkbox in the build settings). These scenes will not be included in the build (and any resources or shaders only used in these scenes will not be compiled) until you re-add them by checking the checkbox again.

The second part of the compilation is compiling code. If you are using il2cpp, this can be quite time consuming. However, you can temporarily switch to target Mono instead of il2cpp for faster compile times (at the expense of slower runtime). Just don't forget to switch back later.

You also have the option to do a script-only build, which skips the first step entirely, assuming you have only made changes to code, and not to any assets, since your last build.

The third part of compilation is simply running the apk compilation. There's not a whole lot I can suggest to make this section faster.
> 2 votes

---
Tags: unity
---


title: Minimum Viable Product for RTS game?

text:
# Question
Title: Minimum Viable Product for RTS game?
I'm in pre-production on a strategy game and am trying to determine if the core gameplay will be fun. A good technique to determine this is to strip the game down to its minimum viable product (MVP) and see if that is fun. If the MVP isn't fun, then no amount of extra content or features will make it fun.

I'm having difficulty determining the MVP for a strategy game as I'm a little too far into the weeds to see which of the many design features are core mechanics and which are unnecessary.

Purely as an example, lets just say StarCraft2 is the strategy game I want to make. What would be the MVP for SC2 to prove out that its core gameplay is fun?

# Answer
Real-Time Strategy is a genre which actually combines multiple games in one. You have a management game (resource management and build orders), a puzzle game (building a base with a functional yet easy to defend layout), two different kinds of exploration games (exploring the map and exploring which units beat which other units), and a tactics game (controlling your units in battle). You obviously can't create all these five games at once, so you should just focus on one of them at first.

In this answer I am focusing on two of these games which I consider most essential to the genre: Unit controlling and base building.

# Unit Controlling MVP

1. Create a player-controlled "tank" game object (represented as an untextured cube) on an empty plane which moves to a new position when the player clicks there.
2. Add immobile AI targets (represented by a cube in a different color) which get deleted when their HP go below 0, and the ability for the tank to fire on the closest target to reduce its HP.
3. Add the ability for the targets to shoot back when the player-tank is in range.

Now you have a playable strategy/puzzle game: Navigate your tank from target to target in a way that it doesn't fight more than one at a time and destroys them all before itself gets destroyed. This is basically how you attack a base with defensive turrets in an RTS game.

Next steps to pursue in no particular order:

* Add a simple AI to the opponents so they can move and not just shoot back
* Add multiple player units to control and the UI for selecting units
* Add buildings (see "Base Building MVP" for details)
* Add more types of units with different ranges, weapon strengths and hit points
* Add blocking terrain to the map and route finding to the unit AI so they can navigate around it.
* Replace the units with properly animated graphics
* Add win and lose conditions

# Base Building MVP

1. Create an empty plane and allow the player to place a building on that plane by clicking
2. Add different kinds of buildings and an UI which allows the player to choose which building to build
3. Add construction times and resource counters
4. Add buildings which create resources in regular intervals (I wouldn't implement worker-units yet because they require too much AI programming to work) and a ruleset for when you can build which building ("can only build a factory when you have at least one finished barracks").

Now you've implemented the first few minutes of a Starcraft game: Figuring out the ideal build order to get the buildings you want as fast as possible.

In fact you could stay here and polish it, and you have a simple resource management game. But if you are still sure you want to create an RTS, then the next steps would be in no particular order:

* Add an AI which builds its own buildings
* Add terrain features which prevent buildings from being built (or are a requirement for placing certain buildings, like "farms can only be built on fertile terrain")
* Add mobile units (see "Unit Controlling MVP" for details) which can destroy enemy buildings
* Add construction jobs to individual buildings which can be started, take a certain time to complete and can be aborted by the player.
* Create building types which interact with each other in some way (in Starcraft, these would be Terran addons or Protoss pylons, for example)

I am looking forward to playing your game.
> 35 votes

# Answer
> What would be the MVP for SC2...?

If the answer were generally known, don't you think there would be a lot more competition to SC2 out there? SC2 is the product of countless hours of design decisions; every patch that was released to SC1, SC1's initial design, the lessons from WC and WC2 that went into the SC1 design, and so on.

Game design isn't an exact science. Game design is working with infinite possibilities. Sure, there are fairly standard features in RTS, but the question here isn't *What is an RTS to everyone?* because *everyone* isn't building your game, *you* are. So it is rather, *What is an RTS to you?* (and why?)

Analysing the work of others is important; but getting started on your own work is far more important. Research *is* important; but don't let it bog you down. *Start creating fun.*

MVP is a brilliant idea, but you're missing the spirit of it: MVPs are about actively prototyping your ideas, not about over-thinking yours and everyone else's work. Getting your hands dirty is more important than worrying about what the supposed minimum mechanics for an RTS are. Many games can be considered RTS which fall largely outside the usual definition of that genre. Get a demo out and have people start playing it; and *they* will decide whether your product is viable, as well as genre.

> I'm a little too far into the weeds to see

Until you start prototyping, that will be the case, and many questions will remain difficult to answer.
> 14 votes

# Answer
**What makes your game unique**

The key reason for developing an MVP is that you can test your idea early, and release if you need to. That is, you ensure you always finish development with a "something", rather than a nothing.

However, that doesn't mean simply making the most basic version of an RTS you can. It means making the most basic version of **your** RTS that you can.

Figuring out exactly which features and assets are needed is an art itself. However, your goal should be to minimise re-creating things you know work and including as much stuff that you don't. That is, you should only include things that are generic to other games - if you **need** it to properly test your specific ideas:

* Do you need sophisticated AI? (For a one-level MVP, you might get away with just a fixed build-order the opposition always uses.)
* Do you need more than one faction? (Maybe your game focuses on the synergy between two races and that's key. But maybe it's actually just a "nice to have")
* Do you need to have unit building and resources at all? (Maybe all you need is a pre-made battle scene with a set number of units, perhaps all your key ideas are actually focused on the skills and tactics side of things)
* Do you need to have multiplayer at all? (If the aim of the game is to make a 6000 player MMORTS; then yes - you probably do)

This of course also includes art assets:

* Do you actually need it to run in 3D? (perhaps you have non-flat terrain features)
* Do you actually need multiple character models? (maybe you do, maybe each unit has a personal story and that's important to you)
* Do you actually need icons for the tech tree? (again, maybe you've got ideas to innovate the UI for RTS games and that's your selling point).

But again; you want to only include things you **need** \- and leave anything you don't for a later date.
> 6 votes

# Answer
Some aspects i would say are quite easy to decide what you need for an RTS in generel. Depending on your concept, you need one "unit", that can be build, ordered or the game just starts with it.

Starting with Starcraft as your example, implement maybe a worker unit, one building and one fighting unit. Your building should be able to build both of them. General i wouldnt even add a resource to harvest, but since Starcraft heavily depends on it, in that case you should do that.

The hard part is, what features do you need to implement aswell. Your fighting unit needs to be able to "fight". So can it shoot? can it attack in cc? What are the enemies? Do you need more different units (e.g. air?)

Yes, you should only start with one race, so you basicly only got mirror matches so to speak. Additionaly, you dont need a map (if that doesnt hinder any very important features), just a square to move on. What is the objective? Destruction of the enemy or victory points, controlling capture points?

I think the problem with RTS is, that you basically got so many important features and basic elements, you still need to implement to have a MVP, while it is really hard to say, what core elements of your games are.

In my opinion it comes down to compare your base game to other RTS, and there are a lot of them, and even continued in a sequel, they are not the same.

* C&C Tiberium and Red Alert Series: Starting with main building, construct buildings by menu without a building unit, construct units in menu when corresponding building exists, different types of individual units (by foot, ground vehicle or air)
* Dawn of War 1 & 3, Company of Heroes: Base building with bulding units, no active resource gathering (passive generation by controlling points), most units are group based
* Battlefleet Gothic: No Buildings, no resouces, different types of units, not replaceable, skills are extremely important

All these differences make RTSs so vastly different. Trying to strip down a game to these basics are wastly more complicated than the example Extra Credit gave with racing games: Accelerating blocks, collision, thats it.
> 5 votes

# Answer
Not every genre is conducive to a "minimally viable product". Or at least, not in the same way and they won't achieve the same purpose.

Consider a level-based 2D platformer. An MVP for such a thing is primarily about finding good jumping mechanics. You don't get to change your character's jumping physics once you start designing levels, so you need to nail that down early. So you pick some jumping physics, build a couple of test levels, and work out what kinds of physics feel good. You also try some mechanics, like tossing in a few enemies and working out how you want that to work, and/or specialized terrain and abilities (carrying items, etc).

The end of that process is what would be considered the MVP.

An RTS doesn't really do that. Or at least, it never really *stops*. Every aspect of an RTS feeds into other aspects of it. While it is true that there are some things you just don't change past a certain point in development, overall development is much more fluid. Here's an example.

Towards the end of StarCraft I's development, Blizzard made what I would consider to be a pretty earth-shaking change. In earlier builds, every Zerg building that made units available produced its own larva, which was used only to produce those units. Basically, in that build, larva was an alternate form of unit queuing. This was changed into the mechanic we know the Zerg for today: all Zerg units come from larva produced at a central structure.

That one change *fundamentally* changed the nature of the Zerg as a race. For other races, tech-switching (changing your primary unit producing building) is a process that necessitates a substantial investment. For the Zerg, you just throw down one building, and your entire production infrastructure can build them.

But this fed into the dynamic of the Zerg in terms of unit design. See, SC1's Zerg were basically built around three fundamental units: Zerglings, Hydralisks, and Mutalisks. These are your basic unit, and everything else is essentially a support unit for them. So Zerg don't really tech-switch like other races; they add a few extra X's to their existing army composition. Big tech-switches for the Zerg were mainly about which fundamental unit the core of your army is built around.

Each design element feeds the other. If you change your production model, you now have to change your unit design to compensate.

A "minimally viable product" for an RTS just doesn't work in general; all of an RTS's mechanics interact in too many ways for a "minimal" product to be anything more than, essentially, a full game.

So I would suggest that you make a small-scale RTS as your MVP. A *complete* RTS. It doesn't need all the graphics there, but it does need all of the stuff an RTS actually possesses. That will be able to serve the function of an MVP: to figure out how to go about making the game you want to make.
> 3 votes

# Answer
The MVP principle does not always work well with an RTS, because it is the gestalt of all of your design choices that make it fun, but there are some key points you can aim for when you understand what makes an RTS fun.

The general rules of thumb for making an RTS fun are:

**1- Make as many tactics viable as possible. META tactics should require you to use multiple unit types together.**

This requires a flushed out list of unit classes to choose from with their final special abilities to be able to test for, but you don't need each unit type. A unit class is a unit that serves a general role in your army and/or has a special ability. If your plan is for each faction to have similar units with different skins and only slightly modified stats, just make one faction. If each faction will have several levels of some of their units that are just improved versions of one another, just make one level of that unit. If each faction has a unique set of units, you may need to build them all out. Just be mindful that you want to test as many classes as you can early on, because adding new classes later can completely disrupt the balance of the game.

**2- Make META tactics change as the game progresses. This can be done either by introducing new units over time or by changing the circumstances of your battles.**

Much like #1, this can require a mostly built out unit class list, but this is more about how you test your MVP. Your MVP should be able to restrict what units are at your disposal so you can make sure the early levels are still fun without all the endgame content to flush it out.

**3- Balance the time it takes to manage your base with the going to war. A common mistake with RTS games is too little base automation meaning your production goes to hell if you have to stop to control a battle.**

This requires a fully flushed out economic system to test for. A MVP test with 5 building types may play well, but a final product with 30 buildings might bog the player down with economic tasks and force you to revisit the drawing board how you manage/automate your economy. The best choice here is to make all of your buildings you plan to have so that you can get a feel for what a base at full scale feels like. Here the best you can do is just hold off on fancy graphics until your economy is finalized.

**4- Make the environment affect your tactical choices.**

This is where MVP testing will give you the most benefit. Adding environmental factors such as high-ground advantages, flanking, special weapons, troop moral, weather, and various levels of open landscapes have both the most potential to set your game apart and make it extra fun, or completely ruin the experience because you made your night-time missions are so dark that players get frustrated every time they have to play one. You can do these tests pretty early on before you have a fully flushed out list of units or economy; so, this would actually be my first testing goal. Also, knowing what environments your units will have to deal with will speak a lot to how you need to design and balance them. It's a lot easier to build your units the first time with all of their needed properties than to go back latter and give them all a coefficient for some new game mechanic.
> 2 votes

# Answer
There are several answers here tailored to RTSs, but I wanted to point out something that's universal to the concept of a Minimally Viable Product (MVP).

MVP is a concept that's been around a long time, but became very popular as Agile development took the scene. The concept is quite simple at it's core: it's the smallest product which is "good enough." That's it.

What makes MVP tricky is that it is subjective, and context dependent. If you are working on the last milestones of a military contract, MVP is nothing less than "product passes qual tests." Qualification of your product will involve testing every single one of the requirement laid out for you at the start of the contract (perhaps years ago). Nothing short of that qualifies as MVP.

Early on in a project, MVP is a much lower bar (thank goodness!). However, it is also still subjective. What I think is the minimum product as a developer is very different than that of the product owner, and different still from what the VP of my company may think. You have to pick which actor's perspective you are using when defining a MVP.

The most critical voice, in my opinion, is that of the person managing finite resources: your time and your money. In a corporation, that may be a project leader or someone in finance. It might be a VP. If you're a small indie company, or someone who is writing games solo, that person might be *you*. But it isn't the normal game developer *you*. It's the *you* that closes the coding tools and art software and pulls up Excel to make sure you can pay the bills this month. Its the *you* that has to weigh the balance between spending another night coding on your little passion project versus going out with friends.

Since we're talking about small MVP's (that's what the video you linked was talking about), we can start to use Agile's approach to the concept. I would phrase it this way:

> The MVP for any iteration/sprint/phase is the minimum product which justifies the expenditure of resources in the time spent building that product.

This definition is why the military definition of MVP I used earlier is valid: for them, the only thing which can justify the millions spent on a military contract is a successful product which does everything that was promised. But for you, you might be justifying a week or a month of time. The bar is lower.

So for this, take off your developer cap, put on your suit and tailored pants, and let's talk about what happens next. Developer you finishes putting out a product. What are you going to do with it?

Later in the process, one option will be to ship it -- to make money by releasing the game. And indeed, that is one key definition of MVP that should never be ignored. If a product *could* be shipped, it is a candidate MVP, because making money justifies a *lot* of development resources. But early on, you're not going to release it. So the MVP is more nuanced:

> In early development, the MVP is the minimum product which permits you to learn something worth the time it took to produce it.

Note: this may not be what you intended to learn. If the thing you learn is "this game is never going to make it, so we should quit now... but damn was it worth our time trying to make it," then you won. You did some work, and felt it was worth your time. On the other hand, if you decide to can the game and you think "damnit, we just wasted how many months of our lives?!?" then that's a strong suggestion that you weren't doing a good job of limiting yourself to MVP. If you were limiting yourself to MVP properly, the past iterations would already have been deemed as paying for themselves -- no regret.

So now we can get to the examples which other people wrote here. These are answers which explore what is the minimum amount you need to learn something. But they all miss one overarching detail: what is your next move?

The MVP depends on what you plan to do with that MVP once it is created. Take Philipp's great answer and bxk21's comment. Philipp's answer argued for two "minigames," one of unit control and one of base building. bxk21 argued that those arne't as important as the time management aspect. So who is right?

That's a trick question. They're both right, in certain environments. Presumably you are about to hand the released MVP to some playtesters to get feedback. What kind of playtesters are you planning to use? Are they RTS pro's? If your playtesters aren't experts at RTSs, then Philipp's answer is probably spot on. You're looking at the small concrete pieces of the game. They will have enough background to be able to comment on those sorts of things.

Now let's say you somehow get playtesters like TLO, Day\[9\], or MVP. These are pro level RTS players (or in the case of Day\[9\], at least an honorable mention, as I do not believe he plays professionally). If these are your playtesters, then bxk21's opinion is probably the right one. They aren't going to care about the little details about whether you build buildings or whether the buildings build themselves. They're going to care about subtle nuanced thing, like time management and balancability. Now you won't have these sorts of things nailed down in early testing, but you should be able to let the *flavor* of them show through. You should concentrate on making a game which demonstrates the feel you want the game to portray at a high level of skill.

So figure out what you want your next move to be. What do you want to do with your product. Then figure out what your MVP is with respect to that goal.
> 1 votes

# Answer
The key word in “Minimum Viable Product” is **product.**

A product is *something that you charge money for with the expectation that someone will buy it.* If the thing you want is an MVP, it has to be just good enough for whatever price point you have in mind. That is, it can be limited in scope, but it must be *complete* enough to be fit for merchantability.

I’m guessing you probably don’t actually want an MVP, because you’re at the point where you have some idea but don’t even know if it’s worth making into a product. It sounds like what you want to build is a **demo** or some other prototype. The typical way to do this is to make a single vertical slice of the game that includes all of the mechanics you want to test. In an SC2 type RTS, that might be a single mission (if you’re doing single player) or a single multiplayer map.
> -3 votes

---
Tags: game-design, rts, pre-production
---


# Question
Title: Handling localization strings in a performant game engine c++
I'm wondering what's the approach for handling localization in a modern game engine. Typically I'd reference a string that would serve as a tag (say: AURA\_POISON\_CLOUD) in the code and then later in my UI I'd look it up in the language of my choice.

Considering that strapping a full-on string to my gameplay Status struct (ECS architecture) seems a bit inefficient, I could hash the string and then in my UI I would have to first get the original string and then do the localization look up. How would you handle the hashing though when it needs to be reversible? By definition it seems impossible, so an alternative would be two dictionaries: strings=\>ints and ints=\>strings for the reverse lookup. Is there something I'm missing here?

How do you approach this problem in your games?

# Answer
> 4 votes
You don't need your hash to be reversible.

At runtime, all your lookups to recover an actual string should be done using the an integer ID value, so you might have a function called `getLocalizedString` to perform such a lookup. Given storage for all the strings for the active language that looks something like

```
std::unordered_map<int, std::string> localizedStrings;

```

that function can be simply

```
std::string getLocalizedString(int id) {
  return localizedStrings[id];
}

```

Naturally, you don't actually want to write code like `getLocalizedString(892)`, you want to use a human-readable token like `AURA_POISON_CLOUD` in place of 892. The simple approach is just define all such tokens

```
constexpr int AURA_POISON_CLOUD = 892;

```

but that's also a maintenance headache, so a common approach is to hash the token itself into an integer value using a macro and/or `constexpr` function. For example:

```
#define LOCSTR(token) hash(#token)

constexpr int hash(const char* string) {
  return string % 0xFFFF; // replace with a real hash function though
}

```

The Fowler-Noll-Vo hash function is simple to implement as a `constexpr` function in C++ and works well for this purpose.

With this, you can call `getLocalizedString(LOCSTR(AURA_POISON_CLOUD))` as well as using `LOCSTR(AURA_POISON_CLOUD)` all over your code to refer to the string. The hash value will be computed at compile-time; the *runtime* will still see a call to `getLocalizedString(892)`.

Just like you don't want to write `892` all over the place in code, you don't want the translation team to see `892` anywhere. You want them to see `AURA_POISON_CLOUD`. The file you give them should be something that associates the original English strings with those identifiers, as a `.csv` or spreadsheet or text file. The latter might look like this:

```
AURA_POISON_CLOUD Cloud of Poison
AURA_FLAME_CLOUD Cloud of Flame
UI_CHOOSE_CHAR Choose Your Character
UI_PLAYER_DIED You have died!
...

```

You give them the source file, they returning it to you having replaced the English text with whatever translations. Your game then has to load that file, and when it does, it iterates through every pair of (token, translation) and adds them to `localizedStrings`:

```
// pseudo-code
foreach(pair in the file) {
  localizedStrings.insert(hash(pair.token), pair.translation)
}

```

Having populated that database of translated text, `getLocalizedString` will now work fine. At no point will you need to expose the *actual hashed ID* to a translator or person writing code. They're all able to use the human-readable token.

(Note this approach still works if you don't have `constexpr` functions, you just pay the hash cost at runtime, so you might write your code a little differently, but it should generally be fine.)

(Also note that while you don't *need* to perform the reverse lookup ever, keeping the information for the reverse lookup around in *debug* builds can be helpful, but while stepping through the code in the debugger, you *will* see the raw hash results and having the ability to reverse the lookup in the watch window or something can be useful; you don't need this for shipping builds at all, though.)

---

You may also be interested in reading an approach to localization described on the Our Machinery blog.

---
Tags: c++, architecture, localization
---


# Question
Title: Too many objects to update in db too often
We are creating a RTS mobile game and we face some problem dealing with updating a lot of object in db too often.

Our game is a RTS in which players can attack enemies cities an take them. The world is procedural and potentially infinite, when players spawn we extend the map if needed (no city left). Our map is reset every month. Each city hold an army and produce an amount of army based on the city level. We also have some items that the player can equip and unequip. Those items may give some army production bonus.

At the biginning most of players had around 30-50 cities. But since the player number increased some players now have over 1000 cities.

Our data structure look like this (mongodb)

```
City:
- id (ObjectId)
- location [x(int), y(int)]
- level (int)
- armyAmount (double)
- lastArmyUpdate (Date)
- armyProductionMultiplier (double)

Player:
- id (ObjectId)
- Name (string)
- Items [key (int), equiped(bool)]
- Cities [cityId (ObjectId)]

```

When a city is attacked we refresh the army based on the last update and the city production.

```
army = oldArmy + cityProduction*armyProductionMultiplier*TimeSinceLastUpdate

```

It works well as we only update the value when needed.

But when players equip an item that give them army production bonus we need to update the multiplier on each city the player own and to update the army amount considering the old multiplier before applying the new one. If the player only change his item once per day it's ok but if he swap every minutes it will make a lot of database query and waste a lot of cpu time.

We could set a timer between items swap but it would be frustrating for the player.

QUESTION: Is there a db pattern or a better way to reduce the cost of the item swapping.

Thank you!

# Answer
Have you profiled to be sure what the actual problem is? You might find that there is something as "simple" as a Mongo configuration causing poor performance. There's also of course questions of whether Mongo is the best storage to use for something with high-frequency writes. I know RDBMS isn't hip these days, but it's a *lot* easier to optimize and scale for these kinds of use cases, and RDBMS systems like Postgres are doing a pretty good job of obviating Mongo by adding mixed-mode document storage while still allowing relational indices and keys.

However, in terms of your design, this bit in particular stands out to me:

> But when players equip an item that give them army production bonus we need to update the multiplier on each city the player own and to update the army amount considering the old multiplier before applying the new one.

You're imposing N writes for 1 operation, where N is the number of cities. This is clearly going to be a scaling problem. For 1 operation (equip item), there should ideally be only 1 write.

Perhaps instead of caching this production bonus, calculate it on demand from the player's inventory when needed. This would of course shift some computational overhead into (potentially high-frequency) reads, but that is sometimes worth it compared to writes (esp. as reads can be distributed in ways that writes cannot).

Typically, you want to write as rarely as possible, and you don't want to write to multiple records for a single change (e.g., equipping an item should just write the equipment state and not need to modify a bunch of city records). If there's something you can calculate on demand, prefer that over a write. You can still cache these values in a more transient storage (e.d. Reddis, or in memory, or in a local Mongo "shard") if they're used often.

From a game design perspective, hiding technical latencies is one of the reasons games introduce cooldowns, animations, and other delays. In real-time games, you'll see these techniques used to mask network latency, A\* path-finding queries, "slow" server tick rates, level loading/streaming, and so on, though you might not even realize these techniques are in play if you're not really looking for them. :)
> 3 votes

---
Tags: architecture, multiplayer, performance, optimization
---


# Question
Title: Converting eulerAngles to "Inspector rotation"
The inspector shows certain rotation values for Game Objects.

I would like to work with these instead of the eulerAngles (which are the rotation values that I can access by a script).

To get these rotation values shown by the Inspector, I found out that the eulerAngles of the game object's localRotation could be of help.

I'm not sure if my approach is correct.

Can somebody tell me what I'm actually trying to do here (I guess there is a name for it) and how to do that correctly?

My current approach is this:

```
private float EulerToRotation(float value)
{
    if (value > 180)
    {
        return value - 360f;
    }
    else if (value < -180)
    {
        return value + 360f;
    }
    else
    {
        return value;
    }
}

```

# Answer
> 2 votes
The angles shown in the Unity inspector are Euler angles, relative to the parent's coordinate space. They correspond to:

```
transform.localEulerAngles

```

As long as you're using these to represent an orientation, then differences in the exact numbers you get aren't significant. As explained in this answer, there's an infinite number of ways to represent a given orientation as an Euler angle triplet, all equivalent in effect. So adding / subtracting 360 degrees doesn't make a difference to the net orientation that the triplet represents.

If you're in a situation where the exact numeric value of two equivalent Euler angle triplets makes a difference in your application, then you're probably using the wrong rotation representation for that situation.

For instance, if you want to compare whether an orientation matches a reference orientation, don't compare angles: compute the difference as a quaternion, something like this...

```
bool RotationMatch(Quaternion a, Quaternion b) {
    return Math.Approximately(Quaternion.Angle(a, b), 0f);
}

```

Or, without the trig, using the fact that the quaternion dot product is the cosine of the half the angle between the rotations:

```
bool RotationsMatch(Quaternion a, Quaternion b) {
    return Mathf.Approximately(Mathf.Abs(Quaternion.Dot(a, b)), 1f));
}

```

---
Tags: unity
---


# Question
Title: Unity HDRP Testing - Scene View Issues / Lighting / Shaders / Shadows
Yo Guys.

Makings this dope, GlassChess Game, Wanted to try out the new HDPR in unity 2018, add the package and volia, its working. (done all settings)

So I used custom glass shader before trying out HDRP. which is not need now because of the HDRP lit (not the slang word) shader (pretty nice for making glass)

However In my scene viewport it its all funny?

But my Game View (With 1 Camera) is fine?

also as you can see I can't get the glass to work with the chessboard, even without the checkered pattern, the alpha for both are set to 30 out of 255 (30/255)

Unity 2018 (Latest Stable)

please help!

# Answer
Solved this for HDRP by Creating a Scene Setting.

Gameobject \> Create \> Rendering \> Scene Settings
> 1 votes

---
Tags: unity, shaders, materials, scene, view
---


# Question
Title: How to allow free download of a paid game to specific users
if I am a game developer, how can I allow some selected users to download it for free? The options I am aware of are the following:

* Use the built-in functionalities of play store and iTunes connect. This is not an option for me because they restricts the number of coupons I can create
* Use some deep linking framework to unlock paid features for users coming from some specific link. This could be an options, but it can means the need of too many changes to my codebase

Are there any other options than these?

Thank you

# Answer
If you have a free game with some paid features, then it's up to you how you can give them for free to specific users. Maybe you ask for an e-mail when purchasing or something similar, and check if that e-mail is entitled for a free feature.

If you have a paid game that you want to give for free to specific users, the only way I can think of is using Store-specific features. For example on Play Store you can allow specific e-mails to get your game for free, on Steam you can generate keys that you can hand out, etc.

> Use the built-in functionalities of play store and iTunes connect. This is not an option for me because they restricts the number of coupons I can create

I'm not sure what you mean by that. I've used just the Play Store and Steam in the past, but from what I remember, the limit is high enough to not really matter. Unless you plan to give the game for free on a massive group of people, in which case it becomes tricky.
> 1 votes

---
Tags: google-play, appstore, in-app-purchase, free-to-play
---


# Question
Title: How to make an OnCollision reset level script?
I am making a game and I want to make a script that if a player collides with the resetting object the scene will reset/reload.

# Answer
> 2 votes
Code should be like:

```
void OnTriggerEnter(Collider other)
{
 if(other.tag == "setting_object_tag")
 {
  Application.LoadLevel(Application.loadedLevel);
 }
}

```

Make the colliding object as trigger and not using gravity as it will not effect surroundings. `Application.loadedLevel` is the current scene.

# Answer
> 0 votes
Instead of (**depricated**)

```
Application.Load(Application.loadedLevel);

```

use

```
SceneManager.LoadScene(sceneBuildIndex);

```

or

```
SceneManager.LoadScene(sceneName);

```

You can also get current active `Scene`with `SceneManager.GetActiveScene()`.

# Answer
> 0 votes
You should note that the code suggested by SP is only if the collision is set to trigger(it doesn't actually stop a rigidbody, it just triggers when the object is in it). if it isn't a trigger, then change

```
OnTriggerEnter

```

to

```
OnCollisionEnter

```

# Answer
> 0 votes
```
private void OnTriggerEnter2D(Collider2D Respawn)
{
    if (Respawn.tag.Equals("Respawn"))

    {
        StartCoroutine("ReloadScene");
        Time.timeScale = 0f;
    }
}

IEnumerator ReloadScene()
{
    yield return new WaitForSecondsRealtime(0.5f);
    SceneManager.LoadScene("SampleScene");

}

```

and tag object at respawn TAG

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


# Question
Title: How are one-to-many relationships usually expressed in ECS architecture?
I'm trying to implement a simple ECS to help understand the concepts, and I am having a bit of trouble wrapping my head around how it would be used in cases where there is not a 1-to-1 mapping between entities and components.

For instance, an example of ECS, as I understand it, is that you might have a "drawable" component defined, which contains a mesh ID and a material ID required for drawing. This is easy to understand in the case you want a game like Super Mario, where each character is represented by exactly one sprite at any time, but what if you need more than one mesh to draw some characters?

Is it common to allow more than one component of the same type on an entity? Or else would you typically have an entity for each drawable component, and implement some kind of "join table" to map sub-components to a parent?

# Answer
There are a multitude of solutions that each have their associated cost in performance, maintainability and complexity.

This is my favorite solution for entities which consist of multiple sprites, like tanks with their turret. I use this in a 2.5D isometric RTS for the aforementioned use case.

---

You create an **entity per sub-sprite** and **parent them to your main entity** which holds the absolute position from which the sub-entities are offset. **The "Parent-System" solves the absolute positions and rotations of the child sprites** in a bottom (first child) to top (last child of child of ...) order.

---

Pros:

* **Rendering-System remains untouched.**
* Sub-Sprites can have **individual modifications (shaders, particle-spawner, etc)** to their behavior.
* **In line with ECS philosophy and design**, which may give you some peace of mind.
* **Simplified/Unified rendering** process is easier to optimize.
* Parenting overhead is small since it only applies to visible entities.

Cons:

* The overhead because of increased entity count may actually be significant if you abuse this solution, since **having more entities always cause more overhead when managing entities.**
* The Parenting-System (position solving) needs to execute before the Rending-System and after any system that changes the parents position. This may create a conflict but is unlikely to actually affect you, since it's the natural order anyway.
* You need to handle deleting stuff very competently, otherwise some **entities might be left dangling around** or worse

You might see how you can apply this to other problems as well, but it's not the only solution.

---

**It's equally valid to create a special multi-data component if it saves you lot's of overhead and/or makes the whole thing cleaner overall.** For example: You probably shouldn't create an entity per particle unless each particle needs some kind of special behavior and even then it's debatable. Having a component that holds an array of particle-data will have less overhead and fits the concept of particles always being in a group. You also probably want an rendering system that does only particle rendering (or treat particles differently), so it's not that bad to not reuse the sprite component.

---

A third solution would be to actually have ECS-level support for components being present more than once per entity, this has serious performance and design implications though and shouldn't be taken lightly. What if your sprite component needs an offset or a special shader? How do you associate multiple offset components to the multiple sprite components, with their order of creation? Do you group this data then? Is this better than having a component which stores multiple sprites in the first place?
> 1 votes

# Answer
There is not one recipe to build an ECS, but several ways to implement it. The gist is that you got Components that are sort of related to Entities and System working on the same time of Components over and over again.

So to get back to your question, if you want to have entities with several meshes for rendering, you either set your ECS to work with several components of the same type to your entities (e.G: Entities have lists for each component type) or have one mesh component with several meshes in it (this would need identifier in this component, when to use what kind of mesh etc.).

The Problem with several components of the same type for one entity might be, that you need to make clear, which component is the active one for the entity. If that is not clear, you might draw several models on top of each other for the same entity. Same would be problematic for different "types" of physics (water physics applied, and then falling physics etc.)
> 0 votes

---
Tags: entity-component-system
---


# Question
Title: How should rendering be structured using SDL?
This question is probably well documented but I can't find any resources.

Basically I'm not sure how to structure rendering with SDL in my code.

I made a render class which calls the api and the game loop contains this:

```
while(running) {
    renderer->RenderClear();
    map->DrawMap();
    player->render();
    renderer->RenderPresent();
}

```

Everything is rendering properly however I'm not sure how I should structure my code if there's many more things that need rendering. I want to draw a box on the screen with `SDL_RenderDrawLine` but the line will only draw for one frame before RenderPresent in the main loop clears it. I don't think I should have everything placed in the loop that may need rendering.

What is the proper code structure in which objects should use the render api? An array which contains everything to render in the loop? Separate instances of Render() which call their own draw and render? Something else?

# Answer
> 2 votes
Everything **has** to be in the loop, otherwise they can't be rendered. The question is, should they be there by themselves or hidden behind function/classes? This is an organisation question, as in, all results work, but what's "better" depends on you.

One way to solve this, is to have an `abstract class` that implements some functions like `update` and `draw`. This class represents a "Scene" inside your game. It can represent the main menu, or the character selection screen, etc. Now create subclasses for each of these scenes, that implement those functions and now how to draw themselves.

Now create one object, with the type of the abstract class, and initialise it with one of the subclasses. That object is the current scene of your game. Each loop iteration, call its `update` and then its `draw` functions. Whenever the user does a specific action (for example select "start game" from the main menu), re-initialise this object with another subclass of the appropriate scene. Your loop doesn't need to change, and now the new scene is being updated/drawn.

Note that this is not the only way to do this, but as far as I know its quite well-known. There might be better ways out there, but that's up to you to experiment and find the right one for you.

---
Tags: c++, rendering, sdl
---


title: Game Metrics for Achievements

text:
# Question
Title: Game Metrics for Achievements
So I posted not too long ago looking for an alternative system to what I'm using for game metrics, meaning information I post each update when something specific happens (enemy damaged, killed, a wave starts, player taking damage, etc). I got suggestions to implement something more similar to "events" instead, where I could have a general interface to define events and create derivative classes to represent specific cases. This would be fine, but I'm having a hard time figuring out how to define achievements now in terms of these new events.

My current system, I have long values for each type of metric: player, enemy, kill, damage, damage types, weapons, and various other pieces of information. Each value is a single bit and I compose them together so I can later check specific bits to see if a certain metric was posted and apply it to my achievement progress tracker.

For example, let's say ENEMY = 1, DAMAGE = 2, PISTOL = 4. I compose these together to indicate that an enemy was damaged by the pistol this update and the resultant value is 7. I can later look at the individual bits for different cases. Say I have a general achievement for tracking number of kills regardless of enemy type, I could extract the bit relevant to KILL and ENEMY and see if one of those was posted, and if so, increment the milestone. However, I can also use this same metric to apply to an achievement that's tracking kill counts for specific enemies if I wanted to.

I also have more complicated achievements that use a rudimentary state machine with logic deciding what each state does with the metrics that are posted and determine the next state.

The reason this was problematic is because even though this system is great and works well, it means I only have 64 values I can use to compose together, and with the number of weapons and enemies I'm adding, I'm going to run out fairly quickly.

When I tried implementing "metric events" instead, I found that defining milestone achievements (and likely state machine achievements) was impossible because I could only take the metric events with all the information composing that class, and couldn't "compose" them together and then pick them apart. It also made it a lot more difficult to figure out how to save that information to a file for keeping track of achievements in save files.

Does anyone have a suggestion as to how I could approach this? If it helps, you can find my current implementation of my achievement system here:

Achievements System

You can also find the AchievementController class under the controllers package one level up. This controller defines the achievements themselves, if you want to take a look at how I define my achievements.

I really appreciate any insight people may have. Links to articles detailing how to properly implement an achievement and metrics system would be very helpful, or if anyone has their own examples of systems they've implemented, that would be awesome.

# Answer
> 1 votes
When you have singular events which should generate an achievement as soon as they occur, like "player killed themselves with the EN cannon", then you might want to have a method for each Achievement which receives an event and then returns whether that event fulfills the condition for that achievement or not. Example:

```
 AchievementEMCannonSelfKill extends Achievement {
      // ...
      @Override public bool check(AchievementEvent event) {
          if (event instanceof KillEvent) {
              KillEvent killEvent = (KillEvent)event;
              return (killEvent.victim == player && killEvent.weapon = EN_CANNON );
           else {
               return false;
          }
      }
 }

```

Your class which processes all achievement events would have a list of not yet awarded `Achievement`s and call the `.check` method on each of them to check if the event it just received fulfills that achievement.

Now what about those achievements which don't just check *one* event but events *over a period of time*, like the "Killed boss using only the nailgun"?

When you store all events over a period of time in a Collection (like an `ArrayList`), you can easily filter it to get only the events you need. A good way to check if something did or did not happen within a given time frame is the Java Stream API. For example, the method `stream.anyMatch` and `stream.noneMatch` can be used to find if there is any event in your event collection which can be cast to a `WeaponDamageEvent` where the conditions `victim == finalBoss && inflictor == player && weapon != NAIL_GUN`.

You could also implement achievements like this as a kind of state machine. The `AchievementBossKilledOnlyWithNailGun` could be switched to the "on" state when it checks the event which says that the boss game object is created, get switched to "off" when it receives an event which says that the player damaged the boss with the wrong weapon, and returns `true` if it receives the boss kill event while in the "on" state.

---
Tags: architecture, software-engineering, achievements
---


# Question
Title: Libgdx clicklistener of Image Actor not recognising click
So I am attempting to make a an image of a closed door for a ship. On clicking this door, it would then change to an open door. However, I am struggling to get the click listener to work for the Image. Weirdly, if i use a textbutton instead it works, with pretty much the same code. Below is the class in which a stage is created and the Image actor added to it.

```
    public class battleScreenActorOverlay implements Disposable {

public battleScreenActorOverlay(World world, SpriteBatch sb, battleShipScreen syst, float bottomButsH, float viewportWidth, float viewportHeight, List<Float> testDoor) {

    viewport = new ExtendViewport(viewportWidth,viewportHeight, new OrthographicCamera());
    stage = new Stage(viewport, sb);
    Gdx.input.setInputProcessor(stage);
    shipObjsAt = new TextureAtlas("batScreen/objects/shipObjects.atlas");
    Skin skin2 = new Skin(shipObjsAt);

    Image img = new Image(skin2.getDrawable("doorV"));
    img.setTouchable(Touchable.enabled);
    img.addListener(new ClickListener() {
        @Override
        public void clicked(InputEvent event, float x, float y) {
            System.out.println("clicked");
        }
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("touch down");
            return true;
        }
        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("touch up");
        }
    });

    // set Image position and dimensions, then boundaries
    img.setPosition(testDoor.get(2),testDoor.get(3));
    img.setSize(testDoor.get(1)*6, testDoor.get(0)*6);
    System.out.println("gabriel "+img.getX()+" "+img.getY()+" "+img.getWidth()+" "+img.getHeight());
    img.setBounds(img.getX(),img.getY(),img.getWidth(),img.getHeight());

    // add to stage which is then rendered in main class
    stage.addActor(img);
    stage.act();
}

```

Then the main class basically does some stuff like this:

```
public class battleShipScreen implements Screen {

// a load of variable declarations here

public battleShipScreen(MyGdxGame game){

    // create viewport etc

    genShip();

}

public void genShip(){
    // basically method for setting door positions
    batScreenActs = new battleScreenActorOverlay(world,game.batch,this,margin,gameport.getWorldWidth(),gameport.getWorldHeight(),testDoor); // calls class which creates stage and adds door

}

@Override
public void show() {

}

public void update(float dt){
    world.step(1/60f,6,2);
    handleInput(dt);
    gamecam.update();
    renderer.setView(gamecam);

}

public void handleInput(float dt) {
 // classic handle input
}

@Override
public void render(float delta) {

    update(delta);
    Gdx.gl.glClearColor((float) 60/255, (float) 181/255, (float) 0/255, (float) 0);    // clears screen
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);                       // clears screen
    // render game map
    renderer.render();
    game.batch.setProjectionMatrix(gamecam.combined);

    game.batch.setProjectionMatrix(batScreenHUD.stage.getCamera().combined);

   game.batch.setProjectionMatrix(batScreenActs.stage.getCamera().combined);
    batScreenActs.stage.act(Gdx.graphics.getDeltaTime());
    batScreenActs.stage.draw();
}

@Override
public void resize(int width, int height) {
    System.out.println("resizing "+height+" by "+width);
    gameport.update(width,height);
    gamecam.update();
}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void hide() {

}

@Override
public void dispose() {

}

```

Sorry for the long post, but I have been trying to sort this out for a few days now and have literally no idea what i am doing wrong. Any help working out how to make an Image actor click listener work would be much appreciated!

# Answer
In libgdx each actor should belongs to a parent (for example a stage). in each frame (render method) you should call stage.act() for running touch and stuff for each actor in stage. and for drawing you can call stage.draw(). you call stage.act() one time when you are on init stage. just add stage.act() on render method and it should fix your problem.
> 0 votes

---
Tags: libgdx
---


# Question
Title: Instantiate prefabs at particular vectors using text file
I need to read a text file containing two pieces of information on each line, and use that information to instantiate a prefab at the correct location in a Unity game (using a C# script). The locations are either North, South, East, or West (each a particular vector).

For example, the first line of the text file might read: landmark1, North

In a script, I need to instantiate landmark1 and assign it to case North vector.

The below script is what I've got so far. Basically, I can read from the text file but I don't know how to assign that information to different cases. I'm guessing I need to use an array somehow but I'm not sure how to do that here.

Any help would be appreciated. Thanks!

```
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
using System.Linq;
using System.IO;
using System;

public class Landmarks : MonoBehaviour {

    //spawnable prefab gameobjects
    public GameObject castle;

    // Use this for initialization
    void Start()
    {

        StreamReader reader = new StreamReader(@"C:/Users/.../landmarks.txt"); //insert full path here
        String textContents = reader.ReadToEnd();

        // string[] dataArray =

        for (int i = 0; i < (textContents.Length); i++)
        {

            //set case if first line = "castle, North" then instantiate object castle at vector 'north';

        }
    }
}

```

# Answer
Here's how I'd approach an issue like this.

1. Define an `enum` for each set of special keywords you want to reference in your file. eg.

```
[System.Serializable]
public enum Landmark : int {
   Castle,
   Mountain,
   Forest,
   Temple
}

[System.Serializable]
public enum Site : int {
   North,
   East,
   South,
   West
}
```
2. Associate these enumeration values with their corresponding prefabs / vectors inside your game.

In this answer, I show a method to create a friendly, inspector-editable list with entries for each enumeration value, that automatically adjusts if you add / remove / re-order values in your enumeration.
3. Use a structured data format for your input file - I'd recommend something standard and in common use like JSON or XML.

There are existing deserialization libraries for these data formats that will do the text parsing for you. So instead of manipulating strings of text yourself, you can let the deserializer digest it into a structured format something like this:

```
[System.Serializable]
public struct LandmarkLocation {
    public Landmark landmark;
    public Site site;
}
```
4. Now you can iterate over a collection of structured entries like the one above returned by the deserializer, look up the corresponding prefab / location from your table, and perform the instantiation. It'll look something like this:

```
LandmarkLocation[] locations = MyDeserializer.Deserialize(text);

foreach(var location in locations) {
    Transform prefab = landmarkIndex.GetPrefab(location.landmark);
    Vector3 position = siteIndex.GetVector(location.site);
    Instantiate(prefab, position, Quaternion.identity);
}
```

The advantage of this style is clean, readable code, without a lot of messy string parsing fussing in the middle of your gameplay logic. It lets the battle-tested deserializer do what it's good at, with a clear contract established by the `enum` and `struct` types to ensure your data is clean and conforms to the expected structure. If it doesn't, the deserializer can handle detecting & generating the appropriate errors.
> 0 votes

---
Tags: unity, c#, algorithm, loading, serialization
---


# Question
Title: Simplify Matrix math code- Sun billboarding
If was trying to set the correct position of my sun billboard in my 3d game. I tried long until it worked correctly, but I wonder why this code must be so complicated:

```
sun.sprite.Position = Vector3.Transform(Vector3.Transform(-sun.lightDir,
Quaternion.Inverse(world.Rotation)), Quaternion.Inverse(myRelativeRotation));

```

Can I simplify this expression? I tried changing it at least to this:

```
sun.sprite.Position = Vector3.Transform(-sun.lightDir,
Quaternion.Inverse(world.Rotation) * Quaternion.Inverse(myRelativeRotation))

```

But this is giving me different results, so the sun is at the wrong position.

# Answer
In the end I found a solution and made it even simpler:

```
sun.sprite.Position = Vector3.Transform(-sun.lightDir,
    Quaternion.Inverse(myRelativeRotation * world.Rotation));

```

Because according to this explanation is:

```
A^-1 * B^-1 = (B * A)^-1

```
> 0 votes

---
Tags: xna, monogame, matrix, optimization, billboarding
---


title: ShapeRenderer efficiency on games

text:
# Question
Title: ShapeRenderer efficiency on games
I want to draw a rectangle box to use as a text background for a visual novel library I'm writing, I wanted some flexibility of color and transparency and the `ShapeRenderer` class seems to fit the need but the doc brings this disclaimer:

**This class is not meant to be used for performance sensitive applications but more oriented towards debugging.**

If I use it as background the most action on screen would probably be the text scrolling over it. Can someone more experient on the engine tell me if it is viable to use it under those premises, or it is really for debug only?

# Answer
> 4 votes
It is probably fine for a desktop-only game if you don't draw too many shapes, but it can produce FPS stutter on *some* mobile GPUs and, iirc, doesn't cache any of the shapes between frames.

A better approach might be to allocate a Sprite with a small white texture that you upscale to the appropriate size. Set tint and alpha with Sprite#setColor

**update:**

It is possible to manually create a texture by using a pixmap. It is probably easier grabbing the background texture from a texture atlas, if you're using it - allowing libgdx to automatically manage the texture for you. Otherwise:

```
public static Texture createBgTexture()
{
        Pixmap pixmap = new Pixmap(1, 1, Format.RGBA4444); // or RGBA8888
        pixmap.setColor(Color.WHITE);
        pixmap.fill();
        Texture texture = new Texture(pixmap); // must be manually disposed
        pixmap.dispose();

        return texture;
}

```

You can scale the texture by using Image class, and then add it to your Stage, or you can get its Drawable using Image#getDrawable to draw in the SpriteBatch.

# Answer
> 2 votes
A lot has changed, this needs an update: **The ShapeRenderer got overhauled some time ago and got decently fast.** The API reflects this as the disclaimer of it not being "meant to be used for performance sensitive applications" has since been removed.

The new javadoc mentions batching: ShapeRenderer (libgdx API)

> Shapes are rendered in batches to increase performance.

I use the ShapeRenderer for ingame performance graphs, drawing thousands of small shapes, i can see no large impact on desktop. It will certainly trump drawing scaled tinted sprites unless you can replace tens/hundreds of shapes with a single pre-rendered sprite.

The space between two white horizontal lines represents one millisecond.

I've used it some time ago on mobile to draw some circles as placeholders for units. It had no problem drawing hundreds of circles afaik. That was around three years ago already.

---
Tags: libgdx
---


title: Identify button from script?

text:
# Question
Title: Identify button from script?
I want from my script to change the color of the button that identify from the Function OnClick. It's possible ?

```
public float Money;
public GameObject[] upgrade_health_level;
public int[] Player1_heal;

void Start()
{
    Money = 60;
    Player1_heal = new int[6];

}

// Update is called once per frame
void Update()
{

} // END UPDATE

public void upgrade_HEAL() // button OnClick
{

        if (Player1_heal[0] == 0 && Money >= 10)
        {
            Money -= 10;
            Player1_heal[0]++;
            upgrade_health_level[0].transform.localPosition = new Vector3(10, 0, 0);
        }
        else if (Player1_heal[0] == 1 && Money >= 10)
        {
            Money -= 10;
            Player1_heal[0]++;
            upgrade_health_level[0].transform.localPosition = new Vector3(20, 0, 0);
            // Change the button color that use this function
        }

}

```

# Answer
# Sure. Two options.

1. Pass the button as a parameter to the method. You can do this by adding `Button b` as a parameter, telling the method in the inspector (which is how I assuming its wired up already), and then dragging the button into the new parameter field that shows up.
2. Doing everything through code instead.

```
Button btn = SomeGo.GetComponent<Button>();
btn.onClick.AddEventListener(delegate () {
    //code here
    //btn is accessible
})

```
> 1 votes

---
Tags: unity, gui
---


title: Difference between 2 quaternions

text:
# Question
Title: Difference between 2 quaternions
I need to patch an animation during LateUpdate.

I'm rotating the "chest" bone according to the mouse delta. This is to mimic aiming a pistol.

During this aiming, the "neck" bone should stay relatively still. As changing the chest bone's location rotation yaw automatically changes the "neck" bone's local yaw rotation, I store the chest bone's rotation BEFORE I apply a new rotation to it. Then I calculate the difference between the old and the new rotation. Then I apply this rotation yaw difference to the neck bone.

The inspector gives me nice values to work with. When I inspect the rotation values by script, I get reprensations that I can not easily work with.

Here is an example:

While the Inspector shows "15.4", the localEulerAngle shows "344.6".

If I use "344.6", the neck rotation goes Berzerk of course.

How should this be solved?

For completeness, here is the entire void:

```
private void pHandle_LateUpdate_Aim()
{
    Vector3 nOldChestRotation = Chest.localRotation.eulerAngles;

    // Fade old input before capturing new, so we don't dull the freshest data.
    float yawBlend = Mathf.Pow(1.0f - Aim_yawInputFalloff, referenceFramerate * Time.deltaTime);
    // A Lerp toward zero is just the same as a multiplication by the blend factor.
    Chest_yawRate *= yawBlend;
    // Accelerate by mouse movement over the past frame.
    // (May need adjustment for display resolution).
    Chest_yawRate += Input.GetAxis("Mouse X");

    float yawDelta = Chest_yawSpeed * Chest_yawRate * Time.deltaTime;
    float offCenterYaw = Chest_currentYaw - Chest_yawCenter;

    float fDesiredChestYaw = Chest_currentYaw + yawDelta;
    float fHeroRotation = 0f;

    if (fDesiredChestYaw > Chest_rotateRange)
    {
        fHeroRotation = fDesiredChestYaw - Chest_rotateRange;
        //we don't rotate the chest beyond the allowed "Chest_rotateRange", so simply act like the user didn't move the mouse
        Chest_yawRate = 0;
        yawDelta = Chest_yawSpeed * Chest_yawRate * Time.deltaTime;
    }
    else if (fDesiredChestYaw < -Chest_rotateRange)
    {
        fHeroRotation = (Chest_rotateRange + fDesiredChestYaw);
        Chest_yawRate = 0;
        yawDelta = Chest_yawSpeed * Chest_yawRate * Time.deltaTime;
    }

    // If we're moving away from the center, slow down as we approach the edge.
    if (yawDelta * offCenterYaw > 0)
    {
        float extremityYaw = offCenterYaw / Aim_yawMaxRange;
        yawDelta *= 1.0f - extremityYaw * extremityYaw;
    }

    this.transform.Rotate(0, fHeroRotation, 0);

    // Ensure we never overshoot the allowed range.
    Chest_currentYaw = Mathf.Clamp(Chest_currentYaw + yawDelta,
                              Chest_yawCenter - Aim_yawMaxRange,
                              Chest_yawCenter + Aim_yawMaxRange);

    Vector3 nNewChestRotation = new Vector3(Chest.localEulerAngles.x, Chest_currentYaw, Chest.localEulerAngles.z);
    Chest.localRotation = Quaternion.Euler(nNewChestRotation);

    float fChestRotationDifference = nNewChestRotation.y - nOldChestRotation.y;

    //the neck should not rotate with the chest. So I first counter-rotate it against the new chest rotation, then rotate it a little towards the chest rotation
    Neck.transform.localRotation = Quaternion.Euler(0, Aim_NeckYaw - fChestRotationDifference + (fChestRotationDifference * 0.5f), 0);

}

```

# Answer
Changing just a yaw is one of the few times it's reasonably safe to do math directly on Euler angles. Because the yaw is applied at the most-global end of the chain, it interacts in fairly consistent & predictable ways with the other angles. So you just need to take into account the potential for angle wraparound.

Replace:

```
float fChestRotationDifference = nNewChestRotation.y - nOldChestRotation.y;

```

With:

```
float fChestRotationDifference = Mathf.DeltaAngle(nOldChestRotation.y, nNewChestRotation.y);

```

---

Or, we can avoid fiddling with angles and just blend our quaternions instead:

```
// At the top, where you're currently caching nOldChestRotation:
Quaternion oldNeckRotation = Neck.transform.rotation;

// ...do your modifications to the chest rotation...

Quaternion newNeckRotation = Neck.transform.rotation;

Neck.transform.rotation = Quaternion.Lerp(oldNeckRotation, newNeckRotation, neckFollowChest);

```

Here you can vary the float `neckFollowChest` from 0 to 1 to control whether you want the neck to keep its original rotation exactly (0), turn with the chest (1), or any blend in-between.

---

In future, I recommend phrasing your question to ask about what you want to accomplish, rather than what you think the solution might be, so we avoid the X/Y Problem. eg. "How to apply a portion of one object's yaw to another" or "Fixing neck rotation after rotating the chest"describes what you're actually trying to do better than "Converting eulerAngles to 'Inspector rotation'" or "Difference between 2 quaternions" (there's no visible attempt to use quaternions in the code you've shown here, and as you can see above we never need to compute a quaternion difference to solve this, so it's a bit of a red herring in this case).
> 1 votes

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