# Question
Title: How to slow down my Variable Timestep Loop in Java
I am currently developing a game in Java and I ran into a problem

At first, I thought my game loop was working well as it was giving a similar amount of FPS as the tutorial I was following

Then I reach to the phase where I started implementing input from the user. When the user entered in the W key the sprite would move very rapidly to the bottom of the screen and then back up to the top for no explained reason

I think it is something to do with my game loop. As I did my research I deduced that my game loop is running way to fast. The only problem is that I haven't been able to slow down the loop. Or maybe it is a totally different problem

Can anyone please help

Run method of my game:

```
public void run() {
    long lastTime = System.nanoTime();
    double amountOfTicks = 60.0;
    double ns = 1000000000 / amountOfTicks;
    double delta = 0;
    long timer = System.currentTimeMillis();
    int frames = 0 ;

    /*  Game loop use:
     *      From timer calls to while loops to recursive function calls to keep the game alive
     *      Until a certain condition is meet (The loop)
     *
     *      A way to delay the length of each loop iteration so you get a stable frame rate (The timing mechanism)
     *
     *      A way to make the game speed remain independent of the speed of the loop (The interpolation)*/

    //This is a variable timestep loop
    while (running) {
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        while (delta >= 1) {
            tick();
            delta--;
        }
        if(running)
            render();
        frames++;

        if(System.currentTimeMillis() - timer > 1000) {
            timer += 1000;
            System.out.println("FPS: " + frames);
            frames = 0;
            //While times updated per second is greater than one (allowing updates to be seen) call tick method of Handler class

            /* Fixed timestep loops vs Variable timestep loops:
             *
             *      Variable timestep loops: Great because the game will seem consistent regardless of how fast the players's computer is
             *          Allowing it to work on a variety of machines and update the game logic with very high attention to details happening in the game
             *          Graphics latency is not a problem as things are drawn as they change
             *
             *
             *
             *      Fixed timestep loops: You know that every single timestep
             *          will take up the exact same length of time. Allows for consistent gameplay
             *          regardless of how fast a machine is as you know the tick rate of your machine
             *          Works wonderfully for math-heavy games with physics operations. Also good for networked games as packets are going and coming at a generally constant speed.
             *          Keeps game logic running at a very low rate while the frame rate can still and frame rate really high
             *                                                            */
        }
        stop();
    }
}

```

'''

Thanks!!!

# Answer
A game loop is *meant* to run as fast as it can - whether 30 fps or 1000fps. So your loop code is fine.

The problem is that your move function is meant to run only on that frame where the key *goes* down, not on every single frame where the key *is* down (which, even if you tapped the key very lightly, would typically still be several frames, meaning several moves would be made, in very quick succession).

Since you don't share your input function, I cannot advise directly, but most frameworks have `onKeyDown` vs `isKeyDown` (names may differ) functionality for you to choose between. `onKeyDown` is typically an event handler that will only fire **once** \- on that frame where the key first goes down.
> 1 votes

---
Tags: game-loop
---


# Question
Title: How can I modify a static humanoid asset?
I am new to Unity 3D. I bought an asset from the Unity Asset Store recently. It came in a "walking" stance. I was wondering if it was possible to modify this stance to become fully supine; so can I modify the legs so that they are straight and next to each other?

I am not sure if I can do this or not in Unity, or if I have to download Blender or Maya to do this.

I have already tried forcing a stance change, through vertex snapping, but I am not having any luck with that. I have also tried editing the Character Joint settings, but I think that is if I wanted to animate the model, which I don't.

This is what my character looks like currently:

I edited the character as per DMGregory's suggestion, but I am having trouble reimporting it back into my scene:

# Answer
I figured out how to make the humanoid static and usable in my project. As a summary of the steps I took to solve this problem:

1. I had to get to the Skeleton of my imported prefab, so I clicked on my imported prefab, selected the Rig tab, changed Animation Type to "Humanoid", and selected "Apply".
2. In the Transform menu, I rotated the Left and Right Upper Shoulder bones until the model was supine.
3. I saved that new mesh into my Project as a prefab.
4. I was able to drag that prefab into my scene.
> 1 votes

---
Tags: unity, 3d, graphics
---


# Question
Title: UV mapping. Texture blurry and overlapping. Unity3d
In my voxel game, this is how I'm calculating UV coordinates for my cubes' faces:

```
public static Vector2[] faceUVs(Direction dir)
{

    Vector2[] sideUV = new Vector2[4]{
        new Vector2(0, 1),
        new Vector2(1f/3, 1),
        new Vector2(1f/3, 0),
        new Vector2(0, 0)
    };
    Vector2[] topUV = new Vector2[4]{
        new Vector2(1f/3, 0),
        new Vector2(1f/3, 1),
        new Vector2(2f/3, 1),
        new Vector2(2f/3, 0)
    };
    Vector2[] bottomUV = new Vector2[4]{
        new Vector2(2f/3, 0),
        new Vector2(2f/3, 1),
        new Vector2(1, 1),
        new Vector2(1, 0)
    };
    if ((int)dir == 4)
    {
        return topUV;
    }
    if ((int)dir == 5)
    {
        return bottomUV;
    }

    return sideUV;
}

```

Then depending on which face is being generated, I return appropriate UV coordinates for it.

This is the texture itself(pretty clean, each block is exactly 16 pixels wide and 16 pixels tall. Total length of picture is 48 pixels):

But the result is terrible(Faces are almost correctly aligned with appropriate texture part, but the annoying keyword here is "almost"):

As you can see, edges of side faces contain few pixels of what should have been the texture of top face.

I've set filter mode to point too.

If I instead use 16x16 pixel texture, for example only side, then I get good result:

I suspect the problem here could be floating point precision. In that case, how do i resolve this error?

# Answer
Problem was that 1/3 can't be represented as finite and accurate decimal, so it caused miss-alignments on the face.

I fixed it by increasing width of whole texture to next closest power of 2(Both width and height need to be power of 2, but I already had 16 as height), which was 64 for me.

New texture:

Result:
> 1 votes

---
Tags: unity, voxels, uv-mapping
---


# Question
Title: Why do game engines convert models to triangles instead of using quads?
I've worked using Maya for animation and more film orientated projects however I am also focusing on my studies on video game development. Anyways, I was talking with one of my professor and we couldn't figure out why all game engines (that I know of) convert to triangles.

Anyone happen to know why game engines convert to triangles compared to leaving the models as four sided polygons? Also what are the pros and cons (if any) of doing this?

# Answer
> 64 votes
The bottom line is Triangle Rasterization, which is how computers render objects to the screen. Though others say it more elquently than I:

> All 3D objects that we see on the computer screen are actually made of tiny little geometrical objects often called primitives. Quadrilaterals, triangles, n-gons etc. are example of primitives. We will concentrate on triangles mostly because of one main reason: **every object can be split into triangles but a triangle cannot be split into anything else than triangles.** Because of this, drawing triangles is a lot simpler than drawing polygons of higher order; less things to deal with. This is why those triangles are so commonly used in computer graphics.

Emphasis mine. Source: http://www.devmaster.net/articles/software-rendering/part3.php

# Answer
> 60 votes
Triangles have many properties that make them easier, and therefore faster, to draw.

Four points or more may not be on the same plane, but three points always are (ignoring degenerate cases). This has the interesting property that scalar values vary linearly over the surface of the triangle. Even when the triangle is projected on the screen, scalar values still vary linearly respect to x'/z and y'/z.

This, in turn, means most if not all of what's needed to shade, texture map, and depth filter a triangle can be calculated using linear interpolation which can be done extremely fast in specialized hardware.

tl;dr: triangles are the simplest primitive, so algorithms dealing with triangles can be heavily optimized.

# Answer
> 10 votes
It's not "game engines" that do this - all the 3D software you use does this. It just doesn't tell you about it, and your professor seems fairly under-qualified if he doesn't know this. They exist in the computer's memory even if the software is hiding them from you. All 3D programs have an option that will make the triangles visible. They will also have an option that splits them into editable edges, so you can play with them. But they were always there to begin with and it's naive of your proffessor to be teaching this subject and still wondering "what triangles are for".

A triangle is the only way to arrange verts and guarantee a flat surface. When you have a quad, you can arrange the verts in a way that it must bend. But it's already made of triangles and it's those triangles that allow the bend.

# Answer
> 8 votes
Three points (a triangle) ALWAYS define a flat plane. In other words, given any three points, you can always create a flat plane that can cut through all three points. However the same is not always true of four points. You can have four points all on a plane, but you can also have four points that aren't on a plane.

# Answer
> 3 votes
A triangle is the simplest primitive that can be described ***in isolation*** because it has three points, fewer than which do not describe a surface in 3D.

Because a triangle can be considered in isolation, it is possible to make a piece of code or silicon that is capable of rendering only a single triangle, which via the power of repetition can render any surface at all.

Therefore, the first computer system which succeeded at rendering "any surface at all" naturally did so by rendering many triangles independently.

If one thinks of triangles and quads as "primitives" (i.e. as completely isolated bits of geometry with no context) the triangle is the more primitive, and so it will tend to "win."

However, once entertainment-grade computers exceeded a certain level of sophistication in the 1980s, the simplicity of considering "primitives" in isolation became less important. If graphics are to be mass-produced, then economies of scale favor processing groups of related vertices, much as they favor assembling a hundred near-identical cars at once.

This is why in the 1980s, movies adopted the "quad," which is a misnomer because it refers to a 2D grid of vertices in 3D space, and not an isolated quadrilateral.

The same shift from triangles to "quads" has not happened yet in the realm of interactive entertainment, but it is likely to happen, fairly soon, and for the same reasons it happened in the movie business.

# Answer
> 2 votes
There's only one way to triangulate a triangle vs. 'n - 2' ways for an n sided polygon. So, triangles are ultimately the least ambiguous way to define a polyhedral shape. Also, as other posters have indicated, there are lots of ways to accelerate triangle (rather than quad or higher) rasterization (constant z is one of my favourites). Also, it's easier to optimize ray-triangle intersection tests than it is for ray-arbitrary polygon intersection tests. In fact, many operations on n-sided polygons benefit from having a triangulated representation to hand. That isn't to say that n-sided polygon representations are 'bad' - they are very useful but ultimately, you're going to want to work with triangles for many mesh operations.

# Answer
> 2 votes
As long as the triangle is defined by three non-colinear vertices (read: none of the angles are exactly Pi), then the vertices define a unique plane.

A quad is, of course defined by four vertices. It's perfectly possible for those vertices to be non-coplanar. In that case, your quad would really be two triangles divided by a diagonal on the quad. That's two planes, two sets of surface normals, etc.

Every available modeling tool, every algorithm for texturing, lighting, etc all assume that a model is made of plane segments, and every formula we have (cross products for normal calculation is the first one we have) use the absolute minimum input dataset - three vertices define a plane, and the plane is what we need to do all of the fancy stuff.

You could certainly write an engine to work with quads, but you'd find yourself ignoring the forth vertex in just about every case, except for when you (frequently) would need to make sure it's coplanar with the other three that define the quad. And, the most logical solution to the case where it is *not* coplanar would be to split the quad into two triangles. So, why not just do that to start with?

What on earth would be the point of working with quads?

If you want a quad, put two triangles together.

# Answer
> 2 votes
If we assume that getting 4 points to be co-planar is not a problem (it is, as the others have pointed out, but bear with me) then you find that rendering an arbitrary trapezium (which is what a quadrilateral will usually look like when transformed into screen space) is not particularly different from rendering a triangle - in fact, it pretty much works out the same once you perform clipping as that can introduce extra vertices. (At least in a software model - hardware may well have a simpler brute force way of doing the clipping.)

The remaining issue therefore is one of representational efficiency. - you can easily represent a quad with 2 triangles, and without any extra vertices if you use a triangle strip (3 verts for the 1st triangle, then an extra vert for the 2nd triangle). On the other hand, if you try and represent a triangle with a quad, you need to use 4 vertices and have a degenerate one that is identical to another. This is not ideal in terms of efficiency.

# Answer
> -1 votes
Because of using Opengl, DirectX.. Engine. In Opengl, if programmers want use textures, shadows,.... They should know normal vector of each surface element of objects . By triangles, you can easily find these vectors using "Vectors Cross Production"!!!!!!

---
Tags: graphics-programming
---


# Question
Title: Draw onto an object's texture based on a raycast hit position in world space
I am trying to get the world position of a pixel inside a fragmented shader.

Let me explain. I have followed a tutorial for a fragmented shader that let's me paint on objects. Right now it works through texture coordinates but I want it to work through pixel's world position. So when I click on a 3D model to be able to compare the Vector3 position (where the click happended) to the pixel Vector3 position and if the distance is small enough to lerp the color.

This is the setup I have. I created a new 3D project just for making the shader with the intent to export it later into my main project. In the scene I have the default main camera, directional light, a object with a script that shows me the fps and a default 3D cube with a mesh collider. I created a new material and a new Standard Surface Shader and added it to the cube. After that I assigned the next C# script to the cube with the shader and a camera reference.

If you want you can download the sample project here

**Update:** The problem right now is that the blit doesn't work as expected. If you change the shader script as how DMGregory said, remove the blit from the c# script and change the shader from the 3D model material to be the Draw shader, it will work as expected, but without any lighting. For my purposes I had to change *distance(\_Mouse.**xyz**, i.worldPos.**xyz**);* to *distance(\_Mouse.**xz**, i.worldPos.**xz**);* so it will paint a all the way through the other side. I also had to change a line in Gregory's shader from \*o.vertex = float4(v.uv * 2.0f - 1.0f, 1, 1);\* **to** *o.vertex = UnityObjectToClipPos(v.vertex);* because the blit was completely black. But before changing the o.vertex the uv was correctly unwrapped on the screen and the paint was applied as it should have been. So maybe there is a way save that on c#. For debugging I created a RenderTexture and every frame I am using Blit to update the texture and see what is going on. The render texture does not hold the right position as the object is colored. The 3D model I have has lot of geometry and as the paint goes to the other side it should be all over the place on the render texture...but right now it is just on line from the top to the bottom of the texture. Also I try to paint on the bottom half of the object and the render texture doesn't show anything. Only when I paint on the top half I can see red lines (the default painting color).

This is the code I am using.

**Draw.shader**

```
Shader "Unlit/Draw"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Coordinate("Coordinate",Vector)=(0,0,0,0)
        _Color("Paint Color",Color)=(1,1,1,1)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

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

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            fixed4 _Coordinate,_Color;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // sample the texture
                fixed4 col = tex2D(_MainTex, i.uv);
                float draw =pow(saturate(1-distance(i.uv,_Coordinate.xy)),100);
                fixed4 drawcol = _Color * (draw * 1);
                return saturate(col + drawcol);
            }
            ENDCG
        }
    }
}
```

**Draw.cs**

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

public class Draw : MonoBehaviour
{
    public Camera cam;
    public Shader paintShader;

    RenderTexture splatMap;
    Material snowMaterial,drawMaterial;

    RaycastHit hit;

    private void Awake()
    {
        Application.targetFrameRate = 200;
    }
    void Start()
    {
        drawMaterial = new Material(paintShader);
        drawMaterial.SetVector("_Color", Color.red);

        snowMaterial = GetComponent<MeshRenderer>().material;
        splatMap = new RenderTexture(1024, 1024, 0, RenderTextureFormat.ARGBFloat);
        snowMaterial.mainTexture = splatMap;
    }
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            if(Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition),out hit))
            {
                drawMaterial.SetVector("_Coordinate", new Vector4(hit.textureCoord.x, hit.textureCoord.y, 0, 0));
                RenderTexture temp = RenderTexture.GetTemporary(splatMap.width, splatMap.height, 0, RenderTextureFormat.ARGBFloat);
                Graphics.Blit(splatMap, temp);
                Graphics.Blit(temp, splatMap, drawMaterial);
                RenderTexture.ReleaseTemporary(temp);
            }
        }
    }
}
```

Thank you!

# Answer
First, if we want to get the object's world position, we need its world matrix. That's passed in automatically as `unity_ObjectToWorld` when rendering normally, but since we're drawing with `Graphics.Blit` we need to provide it ourselves.

Add a uniform like this above your vertex shader, where you're defining your `_Coordinate` uniform (which should be a `float4`, not a `fixed4`, or you're likely to have too little precision for your needs):

```
float4x4 _WorldMatrix;

```

Then you'll need to populate it in your `Update` script:

```
if(Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition),out hit))
{
    // Pass the world position, not the texture coordinate.
    drawMaterial.SetVector("_Coordinate", hit.point);
    drawMaterial.SetMatrix("_WorldMatrix", transform.localToWorldMatrix);

    // You don't need the temporary or the first blit if you just draw transparently
    // onto your texture, keeping what's there and adding instead of replacing.
    RenderTexture temp = RenderTexture.GetTemporary(splatMap.width, splatMap.height, 0, RenderTextureFormat.ARGBFloat);
    Graphics.Blit(splatMap, temp);
    Graphics.Blit(temp, splatMap, drawMaterial);
    RenderTexture.ReleaseTemporary(temp);
}

```

Now we need a member to pass our world position from the vertex shader to the fragment shader:

```
struct v2f
{
    float2 uv : TEXCOORD0;
    float4 vertex : SV_POSITION;
    float3 worldPos : TEXCOORD1;
};

```

Our vertex shader should spit out vertices in texture space, not clip space, and save the world position to pass down to the fragment shader.

```
v2f vert (appdata v)
{
    v2f o;
    o.worldPos = mul(_WorldMatrix, v.vertex);

    // Convert 0...1 UV space to -1...1 clip space.
    // Depending on the platform you might need to flip the y direction,
    // or flip your culling winding to get this to draw over your UV net correctly.
    o.vertex = float4(v.uv * 2.0f - 1.0f, 1, 1);

    o.uv = v.uv;
    return o;
}

```

Lastly, you want to compute your distance in world space:

```
fixed4 frag (v2f i) : SV_Target
{
    // sample the texture
    fixed4 col = tex2D(_MainTex, i.uv);
    float draw =pow(saturate(1-distance(i.worldPos,_Coordinate.xy)),100);
    fixed4 drawcol = _Color * (draw * 1);
    return saturate(col + drawcol);
}

```

Note that since you're doing this every frame, `col + drawcol` will increase very quickly, and saturate toward 1. But I'll trust that you're aware of that behaviour and it's intentional.
> 1 votes

---
Tags: unity, 3d, shaders, textures, rendering
---


title: Dividing coordinate into unit cube

text:
# Question
Title: Dividing coordinate into unit cube
I'm trying to write a Java class to generate Perlin Noise from a Cartesian coordinate. I'm trying to follow this tutorial but I am struggling to understand the theory.

Specifically, how do you divide coordinates into a unit square or unit cube?

My original though was to a find which was higher the X or Y, then divide one by the other, So either X = 1, y \< 1, or Y = 1, X \< 1. But doing this doesn't really make sense as the point would always lie on one of the cube/square vertices.

Can someone explain the math to me please.

# Answer
> First, we divide the x, y, and z coordinates into unit cubes. In other words, find `[x,y,z] % 1.0` to find the coordinate's location within the cube.

What that means is you perform the `value % 1.0` operation for each member of the `[x,y,z]` vector (*the position*):

`[x', y', z'] = [x % 1.0, y % 1.0, z % 1.0]`

`x'`, `y'`, and `z'` are the remainders of dividing each **floating-point** coordinate by 1.0.

In other words, they are the amount you "chop off" of each coordinate when you round towards zero.

`[x', y', z']` represents the position inside a unit cube, from 0.0 to 1.0 on each axis.
But you can also imagine that unit cube is actually positioned in 3D space at the rounded (*towards zero*) coordinates of `[(int)x, (int)y, (int)z]`.

Another way to visualize what `[x', y', z']` means is to imagine a 1x1x1 grid superimposed over your game world. Each cell in the grid is a unit cube. If you have a point *anywhere* in that game world, it must be inside of of those cubes. `[x', y', z']` is telling you where the point is *inside* that cube.

The original position can be recovered by adding the position *of* the unit cube and the position *inside* the unit cube:
`[x, y, z] = [(int)x, (int)y, (int)z] + [x % 1.0, y % 1.0, z % 1.0]`
> 1 votes

# Answer
Usually 3D Perlin noise would look a bit like this:

```
float PerlinNoise(Vector3 point) {

    Vector3Int root = new Vector3Int(
         FloorToInt(point.x),
         FloorToInt(point.y),
         FloorToInt(point.z));

    for(int i = 0; i < 8; i++) {
        Vector3Int corner = root + cornerOffset[i];
        Vector3 gradient = GetPerlinGradient(corner);
        contribution[i] = Vector3.Dot(gradient, point - corner);
     }

     Vector3 pointInCell = point - root;

     return Interpolate(
         Interpolate(
              Interpolate(
                   contribution[0],
                   contribution[1],
                   pointInCell.x
              ),
              Interpolate(
                   contribution[4],
                   contribution[5],
                   pointInCell.x
              ),
              pointInCell.y
         ),
         Interpolate(
              Interpolate(
                   contribution[3],
                   contribution[2],
                   pointInCell.x
              ),
              Interpolate(
                   contribution[7],
                   contribution[6],
                   pointInCell.x
              ),
              pointInCell.y
         ),
         pointInCell.z
     );
}

```

So dividing space into repeated cubes is just a matter of rounding/flooring the coordinate. The position within this cell is just the fraction left over.
> 0 votes

---
Tags: java, coordinates, perlin-noise
---


# Question
Title: How can I make sure all army compositions are counterable in an RTS game?
Most RTS games I played have some kind of rock-paper-scissors system that ensure that there is no single best unit you can mass and win with all the time.

However this breaks down when players start to combine different kinds of units. Just make one unit type then make the counter of its counters to protect it. Eventually players will find the best pairing that mutually protect each other, then everyone will copy that and all other combinations become inferior to that and won't see play.

We can see this in Empire Earth 1 for example, where up to middle ages all you need to do is just mass chariot/cavalry archers and swordsmen. Although spearmen and knights wreck the swords, they are destroyed by arrows. And archers are destroyed by swords, but your swords are blocked by enemy swords so you'll have hard time reach enemy archers... So all you can do is just try to make more swords and archers than the enemy. You can also use area of effect siege weapons against archers, but they are expensive and totally wrecked by swords. So all players use just swords and archers against everything - including buildings. This what I would like to avoid and I would like to make sure other units also see play.

So the question is: How can I make sure that not just individual unit types but but all possible combinations of them have a counter combination that costs less resources than the opponent's army? Is there a mathematical framework for that?

# Answer
There is another way to get a balanced unit lineup than just to design units to counter other units. Design units to work better or worse in certain situations.

* Units which use the terrain. Perhaps there is a unit which is weaker on open terrain but stronger in closed spaces? Or units which can move through terrain other units can't and thus attack from unexpected directions?
* Units with utility features. Healers? Terrain changers? Buffers/Debuffers? Mind controllers? Transports?
* Units with area-of-effect attacks which are weak against single targets but devastating against tightly packed groups (always a popular counter against the strategy of just overwhelming the enemy with superior numbers).
* Units which synergize with each others, like a melee tank and a ranged damage dealer.
* Units which are weak if left to themselves but have powerful abilities which need to be activated through micro-management.

The *Starcraft* games are great examples of RTS games which do that pretty well.

Another RTS game which is less well known but uses a design with lots of generalist units and very few overspecialized ones is *Wargame: European Escalation*. Its gameplay is more based on how you use your units, not on which units you use. A tank will easily beat an infantry squad on open terrain, but will get destroyed if the infantry has cover and gets close enough to use their RPGs and hand grenades. The game also makes very good use of stealth and fog-of-war. A unit can't fire back if it can't see the attacker, which makes scouting units very important.

Unfortunately all these features make the game far more complex than a simple rock-paper-scissors system. So a mathematical approach to balancing will usually fail. You have to do actual playtesting to figure out which units are over- or underpowered. And as your player community develops the game meta, you will have to release regular balance patches to make sure the game doesn't become too one-sided due to strategies your playtesters didn't think of.
> 2 votes

# Answer
In meantime one thing I'm thinking about is that a rock-paper-scissors (RPS) system can be split into two things: RPS damage and RPS armor. For example rock armor takes extra damage from paper, and reduced damage from scissors, unchanged damage to rock. Apply same logic to other types.

In a pure RPS system the unit that has rock damage must have rock armor and so on. But if we allow other damage types for each armor type, then 6 new unit types possible.

Each of these unit types have:

* Exactly one hard counter: the one it inflicts reduced damage to and takes extra damage from.
* Two soft counters: one it takes extra damage from and inflicts neutral damage to, or one it inflicts reduced damage to and takes neutral damage from.
* And three neutrals: ones it mutually inflict the same damage to each other.

For example: Consider a paper damage / scissor armor (P/S unit):

* Hard counter of: P/R
* Soft counter of: P/P, S/R
* Neutral: S/P, R/R, P/S
* Soft countered by: R/P, S/S
* Hard countered by: R/S

And same applies to all 9 types.

So the counter strategy the player can use:

1. If your opponent masses only 1 kind of unit: you can always make and hit him hard with its hard counter.
2. If your opponent masses 2 kinds of unit: Pick armor that is not countered by their damage type, then pick damage that is not countered by their armor. For any combination of two unit types there is one unit type that can counter both or at least counter one of them and neutral to the other.
3. In case of 3 different kinds of units: if there are two kinds of attacks, then point 2 apply for armor, in case of only two different kinds of armor than the the damage part of point 2 applies. So in this case the interesting combinations is when all the 3 combinations present of the battlefield. In this case there isn't a single unit counter that can reliably trample the whole thing.

So point 3 needs more analysis. I'll continue my answer once I find out what kind of equilibrium that can result in and have more information.
> 1 votes

# Answer
I believe the key is having a single measurement to decide how strong a unit is. I recommend using game seconds. Here are my 3 basic metrics:

**How long should the median unit stay alive while taking damage?**

**How much time should the player spend on creating the median unit?**

**How late in the game do I want to introduce the unit?**

Let's say I want my unit to survive for 10 seconds, and spend 5 seconds of resource gathering/development to create it. I want it to be available after the first 30 seconds of the game, not before.

This gives you a lot of numbers to play with: health, damage, attack speed, range, movement speed, cost, etc.

Example: The median unit has 100 HP and it will have 10DPS. If 2 of these units fight each other, they will both die in exactly 10 seconds. It also has the average range and average movement speed, say a meter a second for movement and 10 meters range.

It costs 400 gold to create. On average, it would take 1 second to generate 100 gold. It will also take 1 second to build, so this gives us 5 seconds of manufacture cost.

To build it you need a specific building or tech developed. It will cost 2000 gold to build the base and another 10 seconds to developed. So it cannot be created before the first 30 seconds.

**So how does this help us?** Once we have a metric for a single unit, we can start giving a value to a synergy.

In your example the synergy is this: a unit takes physical space, therefore it extends the life of any unit behind it, assuming its big enough to

A) hide the unit behind it

B) cover the enemy range in its size

How do we use this to fix our swordsmen - archers problem? here are some options

* If the archers are 3 times the size of the swordsman, you will need 3 times the number of swordsman to "hide" the archers, otherwise the enemy can go around the swordsmen. This can break the cost effectiveness of the synergy.
* If the average unit is faster, it can close in the distance to the swordsmen quicker, effectively spending less time in the deadzone where they take damage by arrows and not hitting the swordsman. This means that the swordsmen will eventually die and the archers will be vulnerable.
* Create more units with varying ranges - let's say the archers have 10 meter range and stand 5 meter behind the swordsmen. That means that they form a 5 meter deadzone, but any unit with more than 6 meter range can hit them, regardless of the swordsman. If the move them closer - bigger deadzone, more units that can hit them. Farther, the opposite.

This helps us fix these problems, **How do we predict them?**

Tricky, but you want to quantify this synergy value. In my example, I would say that a unit that survives 10 seconds, and has the size of 2, will extend the life of any unit behind it for 12 seconds (10 to kill, 2 to reach), and can hide 2 units behind it (if the average is 1).

The protected unit has an additional 12 seconds of life which is 12 seconds worth of damage **if it has a range of more than 2**, otherwise it cannot hit the enemy while staying behind its protector.

So your job is to make sure every unit stays as close as possible to the median worth. The differences between them will stills show, because depending on the play-style, the advantages and disadvantages will have different weight. A player that is very good at clicking fast will suffer more from a slow attacking/moving unit than a player that is not so good at it.
> 1 votes

# Answer
It may help to determine a list of attribute points for each of your units to get an idea of their contribution to a group of units

For Example:

* Survivability
(Combination of Health + Armor + Shields + Dodge, etc.)
* DPS
(You want to measure DPS so that fast and slow attack rates can be compared fairly.)
* Skill/Special/Utility
(The special factor that attempts to put a number to some qualitative value of the unit.)

You'll also want to determine the build costs in terms of time and resources. This one will be tricky to calculate in a way that equates fast & cheap with slow & expensive units though.

Make sure that there's no overlap between the meaning of each attribute or else you're counting part of its overall value more than once.

If one unit has more total points than another it is likely to be a superior choice than the other unit and would make that other unit obsolete. That's a good way to set up tech tiers though, and ensure that different factions/races/teams have similarly weighted attributes on each tier.

Then consider hypothetical groups of units and the sum of all points in that group.
If you can come up with groups that cost less (time + resources) than another group to produce then it's probably going to have an advantage.

If you enter these attributes into the unit data, you could automate a bunch of fake "battles" where you give each team a time/resource budget and assemble armies until the budget is spent. If one army has a higher sum of attributes than the other, it's a sign that the composition could win a battle against the other.

Every time you add or rebalance a unit you could run these automated tests to see how much balance has been thrown off for thousands of possible army match ups.
> 1 votes

# Answer
sounds more like a design issue, no need for mathematical equations. if they use the strategy you described, there should be some consequence - balance things out, add more complexity so each combination offers different positives and negatives.
> -3 votes

---
Tags: game-design, rts, balance, rock-paper-scissors
---


# Question
Title: no intellisense visual studio code in Unity windows
It doesn't recognize object types and I can't use reference-finding. I have the Omnisharp plugin installed and updated.

# Answer
> 1 votes
* 1.install ms Sdk
* unity-\>preferences-\>External tools-\> Use your Code editor
* install .net 4.7
* restart every thing And You are good to go

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


# Question
Title: "Instantiate" function in Unity spawns enemy but it doesn't show up
So, I'm making a top down shooter (2D) and I already made an enemy prefab. It walks to the player and damages it, and reacts to bullets physically until it eventually dies. The prefab itself is ok, because I can spawn it manually and it works as intended. The problem comes when I want to automate the spawn process with a script. So I made a script to do so, here it is:

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

public class GameController : MonoBehaviour
{

    public GameObject enemy;

    private float spawnPositionX;
    private float spawnPositionY;

    Vector2 spawnVector;

    // Start is called before the first frame update
    void Start()
    {
        SpawnEnemy();
    }

    void SpawnEnemy()
    {
        spawnPositionX = Random.Range(-630f, 630f);
        spawnPositionY = Random.Range(-340f, 340f);

        spawnVector = new Vector2(spawnPositionX, spawnPositionY);

        Instantiate(enemy, spawnVector, Quaternion.identity);
    }
}

```

As you can see, it's nothing too complex. I just refer to a game object (which I linked by the way) and then create some variables that will hold the x and y positions in which the enemy will spawn at random. Then when I call the function, those positions get set and stored into a bi-dimensional vector to then be used with the instantiate function.

This... works... kinda? When I run the game, the instance of the enemy gets made, I can see the clone in the hierarchy and I can select it and see that it's indeed moving, but it's like... not there? I can't actually see it on the screen and it's not invisible as I can't interact with it either. It's really weird and I have no idea what's going on.

I tried to put the script on the camera, on the canvas, on a new empty object, nothing. I also checked that the prefab and the instance that's being spawned are indeed active. I thought about the coordinates being out of bounds, but when I check my player coordinates they are inbounds, so that can't be it either. I'm completely lost on this one, thoughts? Thanks.

# Answer
Using a canvas to display gameplay content probably isn’t a good idea, canvases are pretty inefficient and are designed mostly for UI display.

You probably want to look into the Sprite class and other 2d classes (assuming you’re game is 2d). There’s also some great tutorials on official unity learn website to get you started on 2D objects and spawning. Also, Jason Weimann has some great tutorials on YouTube for getting started on 2D games.
> 1 votes

# Answer
Select the spawned enemies in the Hierarchy, and then press F on your keyboard. Now if you check your Scene view, you should see what your enemies doing, where they are, etc.
> 0 votes

---
Tags: unity, c#, 2d, shooter
---


# Question
Title: How can I create an exclusive asset for multiple clients who all want basically the same thing?
This is more of a legal question than for example a coding question, but I hope that it's allowed as well. I recently started working as a freelance VFX Artist and do a lot of work with shaders and particle systems. Now, I am currently working on some dynamic shader, which creates cartoon-ish flames. I signed a contract with one of my clients, which states that I do not re-sell the work I did for them. But, I wonder what I should do when my next client gives me the exact same task and wants a dynamic cartoon fire shader, which is something almost every (cartoon) project needs at some point.

Would it be enough to just use a couple different nodes in Shader Graph, which would still basically do the same? Even then, let's say I get 5 more clients, who want the same from me. There are only so many variations I can do to the shader when the task was to make it dynamic. With particle systems I could just paint a different material and it would be a piece of art asset, but how does that translate to shader work?

# Answer
When a client tells you they don't want you to resell the asset you made for them, then what they really want is to not see a game which obviously uses the exact same asset.

So if you get a very similar request from another customer, then what really matters is that you create an asset which isn't recognizable. They won't care if it uses the same technical base. Just that it doesn't look the same.

You could of course just randomly tweak a couple parameters in your shader graph. But if you want to create the best work possible for the client, then it might be worth looking at the unique aesthetic of their game. "Cartoon style" is a very general description. Different artists interpret it very differently. So ask them for some of the artwork they already have and create something that harmonizes with it as best as possible.

Another approach could be to create one generic cartoon fire shader from scratch. And then when the next customer wants one, you tell them: "Listen, you could pay me $much for $many hour to create an unique effect just for you. But what you want is very generic. I could just sell you this effect I made a while ago non-exclusively for $cheap. Yes, it's in a bunch of other games, but no player will notice".
> 49 votes

---
Tags: shaders, legal
---


# Question
Title: How can I economically check if a UI DropDown is open or closed?
I've recently come across a problem with the UI DropDown component. I would like to resize other UI components depending on whether the dropdown is opened or closed. Unfortunately, the dropdown dynamically creates and destroys its own "Dropdown List" component, making it difficult to check whether it is open or not, without having to check with Update or FixedUpdate (both being expensive on the performance).

I have tried to implement a solution with event handlers, but it seems as if the even handler triggers before the "Dropdown List" is created. Thus this does not work.

Am I simply missing an easy way to check whether the dropdown is open or closed?

# Answer
I have managed to find an surprisingly easy way to solve this issue. The "Dropdown List" that is dynamically created, is created from the "Template" object in the dropdown object's hierarchy. I added a small script to that template object, with a public GameObject variable pointing to my main script component as well as a a public GameObject pointing to itself. When the script is started, it checks its own object name, and if that is "Dropdown List", it sets a bool flag in my main script. When it is destroyed, it does the same. See the code in the script below:

using UnityEngine;

public class DropdownOpenScript : Monobehaviour
{
    // Public variables
    public GameObject self;
    public GameObject controller;      //This is the object containing my controller script

    // Start is called before the first frame update
    void Start()
    {
        if (self.name == "Dropdown List")
        {
            //ControllScript is my main script controlling my program opperation.
            //It contains a public boolean bDropdownOpen to indicate whether the
            //dropdown list is open or not
            controller.GetComponent<ControllScript>().bDropdownOpen = true;
        }
    }

    private void OnDestroy()
    {
        if (self.name == "Dropdown List")
        {
            controller.GetComponent<ControllScript>().bDropdownOpen = false;
        }
    }
}
```

> 0 votes

---
Tags: unity, ui-design
---


# Question
Title: Algorithm for units to attack each other in strategy games
I am creating a strategy game with many objects, in which the objects will be able to attack each other.

If an object is within attack range of another object, it will be attacked. But I only know one way is to loop through all objects to see if it is within the scope of this object's attack. Therefore the complexity of the algorithm is O (n ^ 2). Can someone give me a better algorithm or preferably a book about algorithms like this.

Thanks !

# Answer
You can optimize this using spatial partitioning. The basic idea ist that you only compare those objects with each other which are within areas which are close enought to have a chance to collide.

1. Divide your game world into sections.
2. Store those sections in a data-structure optimized for directly accessing a section at a specific location. When your sections are a square grid, then you can use a 2-dimensional array. When your sections are irregular, then you might want to use something like a BSP tree.
3. Add a list of objects to each section which represents the units which currently occupy it.
4. When an object moves across a section boundary, remove it from the list of the old section and add it to the list of the new section. If your objects are large enough to overlap multiple areas, then it might make sense to allow it to be on the lists of multiple areas.
5. If you want to get all objects in a given attack area:
    1. Determine which sections are completely overlapped by the area. All objects on their lists are potential targets. Accurate collision detection for these objects is unnecessary. You already know that they are affected, because anything which touches this section is affected.
    2. Determine which sections are only partially overlapped. You have to do a proper collision detection with the objects on their lists to determine whether or not they are affected.
    3. Any sections not touched by the area can be ignored. This is where most of the performance savings come from.
6. If you allow objects to be in multiple sections at once, remove duplicate from the list of potential targets.
> 3 votes

# Answer
There are a few solutions to this:

1. limit the total number of attackable entities that can be active at any one time. This is one of the reasons why unit caps exist in RTS games.
2. create a spatial partition so you can ask of the map "in a 50m radius give me every entity that is possible in this area" and then you loop over the resulting set to eliminate the false positives.
> 2 votes

---
Tags: c++
---


title: Clamp UVs checkbox disappeared?

text:
# Question
Title: Clamp UVs checkbox disappeared?
I've run into the following problem. I'm following some tutorials for shading to the exact letter. It all works except my meshes have really bad shadowing in/on them.

I see the difference with the tutorial: the Clamp UVs checkbox in the SceneTexture nodes has disappeared from the material editor GUI.. How should I replace this function? I already have some clamps in my blueprint but they are also part of the tutorial so they aren't there to replace the checkbox that disappeared under "Scene Texture Id".

Many thanks!

# Answer
> 0 votes
Found the solution. I was dividing SceneTexture: DiffuseColor by SceneTexture: PostProcessInput0 instead of the other way around. Fixed ! (Just thought I'd post my own answer for anyone who ever stumbles unto the same issue)

---
Tags: unreal, materials
---


title: Figure out why vertices are clipped

text:
# Question
Title: Figure out why vertices are clipped
I am trying to figure out why, at sharp cutoffs in geometry, some vertices seems to be culled for some reason.

I have a heightmap for demonstrating it like this

And this is the result I get

See the red rectangles where the geometry is just cut and the skybox is shown behind.

I am not quite sure where to start looking where the problem might be. I know for a fact it's not colliding with the z-near value. Any non-steep geometry is fine. Any pointers?

**EDIT**: at certain angles, re-orienting the camera ever so slightly changes things, like this

# Answer
Thanks to Ernie for pointing me in the right direction. It was indeed frustum culling that was the problem. I am using CDLOD and built a quadtree from the heightmap to cull with. All I needed was to add one pixel extra of "smoothing".
> 2 votes

---
Tags: directx11, hlsl, vertex
---


# Question
Title: Distant objects remain fully lit at sunset, when they should be in the mountain's shadow
I'm trying to make dynamic sunrises and sunsets in my game but I have some problems. My scene is surrounded by mountains and when the sun tint is still hot the sun is not visible but, the trees that are far from the player (Around 100 meters) are lighted like if the mountains are not casting shadows, and when I get closer to theses trees they become black as they should be. If I extend the shadows distance it changes nothing. Also, when the sunrise, even if it should not be visible it should do some ambient lighting, but everything is totally black except some trees.

# Answer
> -1 votes
I would look at perhaps the shader materials, Light distance in shader.

https://forum.unity.com/threads/light-distance-in-shader.509306/

PeerPlay has great tutorials on shaders https://www.youtube.com/watch?v=t8qBCltSqV4

Custom fall-off https://docs.unity3d.com/Manual/ProgressiveLightmapper-CustomFallOff.html

Alternately the asset store might have something fun. https://assetstore.unity.com/packages/vfx/shaders/free-skybox-extended-shader-107400

https://assetstore.unity.com/packages/vfx/shaders/top-projection-shaders-pack-106862 https://www.youtube.com/watch?v=-XVxlqzcwR8

---
Tags: unity, lighting, shadow-mapping
---


title: cant add script component

text:
# Question
Title: cant add script component
So I'm just starting to *try* to learn unity development with C# using this tutorial but I cant add the script to any game object and I get the following error:

Code of the script:

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

public class NewBehaviourScript : MonoBehaviour
{
    // Start is called before the first frame update
    public Light myLight;

    void Update()
    {
        if (Input.GetKey("space"))
        {
            myLight.enabled = true;
        }
        else
        {
            myLight.enabled = false;
        }
    }
}

```

I know it's been answered before but I've done everything I read, I did my homework and I still cant get around this issue. I allready checked the name of the class and its the same as the file's name. I think it may be something regarding installation (?) I installed *unity hub* and it installed *Unity* and *Microsoft Visual Studio* by itself.

* Unity version: 2019.3.3f1
* MS Visual Studio version: 16.4.5
* MS Net Framework version: 4.7.03062

I honestly dont know what else to do people! Please help!

# Answer
> 1 votes
First of all - try these solutions especially reimporting all. I'm not sure how are you trying to add the script, but it might be helpful:

1. check if project is saved (serialization might kick in only on save)
2. select yaml serialization format for your prefabs instead of binary, save, reimport, restart unity and try to add component using Add Component button in inspector of the object (project settings\>Editor\>Asset Serialization\> Force Text)
3. if this doesn't work try selecting the script in debug mode of the inspector (inspector window has this little padlock icon, next to that is arrow with 3 bars icon, there you select debug. In any component you select the field Script to your script)
4. Create script from unity with Assets \> Create\> C# Script menu
5. make sure that files on disk and asset names in folder have the same case (windows has sometimes some weird problems if someFile is reffered to with different case as SomeFile)
6. sometimes it's also useful to clear unity log files

And try it on a completely new, blank project.

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


title: How to restart a coroutine

text:
# Question
Title: How to restart a coroutine
I want to run my code multiple times without using the Update() method, now, I could use a coroutine or an Invoke(), but since the Invoke() is not very performance friendly as a coroutine, my best option is to use a coroutine instead.

Now, my problem is, when my coroutine is completed and I want to restart it, how exactly should I do it?

Here is what I've done, but it doesn't work:

```
private void Start()
{
    StartCoroutine(DoSomething());
}

private IEnumerator DoSomething()
{
    //Does something
    yield return new WaitForSeconds(20f);
    //Does another thing
    yield return new WaitForSeconds(20f);
    StartCoroutine(DoSomething());
}

```

# Answer
> 1 votes
You can simply put an infinite loop in your coroutine.

```
private IEnumerator DoSomething()
{
    while(true) {
        //Does something
        yield return new WaitForSeconds(20f);
        //Does another thing
        yield return new WaitForSeconds(20f);
    }
}

```

You can still stop that loop by destroying the game object which started the coroutine or with `StopCoroutine`. If you have some exit condition for the loop which you want to check within the coroutine, you can either turn the infinite while-loop into a while-loop with a condition or break out of the loop with the `break;` keyword.

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


# Question
Title: What do you call the logic gates visual programming of PS4 Dreams?
The PlayStation 4's Dreams app has a visual programming framework made up of sensors (detect touch, a person etc.), logic gates (AND, NOT, splitters etc.), wires, and action outputs (move somewhere, execute keyframe, teleport etc.). Through these flows energy which is usually a value between (presumably) 0.0 to 1.0. This in turn is used to create full games logic, movies and more.

Is there a name for this type of programming UI? I can think of a general "logic gates" programming or so, but maybe there's something more specific. Thanks!

# Answer
> 2 votes
Programming in a point&click interface is usually called "visual scripting". A system like this which uses nodes with connections is often called graph-based visual scripting.

In a more abstract sense, you could categorize this as a declarative programming approach. The programmer declares that *this* value is derived from *that* value which is calculated from *those* values. But declarative programming is not necessarily visual programming.

Another visual scripting methodology is block-based visual scripting which you can see in tools like Scratch. This visualization model is usually used for imperative programming.

# Answer
> 3 votes
This reminds me of LabVIEW. Wikipedia describes LabVIEW as both "graphical programming" (referring to how the code is entered and displayed using graphical blocks) and "dataflow programming" (referring to how the code is executed).

---
Tags: playstation4
---


# Question
Title: What is the game design rationale behind forcing MMO players into gameplay styles they do not enjoy?
Most MMOs have a varied assortment of content. However, not everyone enjoys particular content styles. There are a lot of PvE players who don't like PvP, and vice versa. There are players who only want to do small group content or large group content, but not the other type. There is always an argument among the playerbase on whether it's a good idea to encourage players to participate in content styles they do not enjoy. The most common argument is that it makes the world feel more alive if there's more to do. However, I personally am of the opinion that forcing players to do content that they do not enjoy, for example through exclusive player power rewards or cosmetic rewards, will make them enjoy the rest of the game less and in turn stop playing sooner.

What is the potential game design rationale for an MMO to force PvE players into PvP and vice versa, or to force players who prefer to play in small groups to do large group content?

# Answer
I think its more of a general 'Thing' that each player tries to find his place in every game, not just MMOs. While in MMOs, you have PvP, PvE, Collectors or players who enjoy the story, in Shooter you have Competitive players FFA, Teambased, Fun Maps etc. Going to sandbox like Minecraft, you got player that like to explore, build houses, villages, traps or even working redstone computers.

Mark Rosewater said in his GDC talk in his seventh point, that players will seek their niche to make the game more personal. This way the players can make the game 'their own'.

To go back to your question, i would give an example in Elite Dangerous. I love to explore the galaxy, but for that you need a ship that has a certain jump range, fuel capacity, fuel scoop etc. For that, i need to make money to buy the bests parts, grind upgrade material etc.

This is time consuming, stressing and certainly not as fun as what i would like to do. BUT after all said and done, i upgrade my ship with new and better parts. All i did was to persue my interest in the game. So although you got other interests in the game, you are encouraged to try something new and even if you dont enjoy it as much as the other way of playing, you still got something to look out for.

The alternative would be, that i would just explore and explore and explore... and might get bored. Its like you got a new favorite song and you listen to it 200+ times in a row, and then you would like to never hear it again. So instead you only listen to it on a playlist and you are happy everytime it comes up.
> 1 votes

---
Tags: game-design, mmo
---


# Question
Title: How to set the value of each index in a uniform array
I am currently implementing "instancing" into my game engine to allow the drawing of 1000 tree models following the tutorial found here: https://learnopengl.com/Advanced-OpenGL/Instancing.

I have the draw call:

```
glDrawElementsInstanced(GL_TRIANGLES, m_drawCount, GL_UNSIGNED_INT, 0, 100);

```

Then in my shader I have the uniform:

```
uniform vec3 A_offsets[100];

```

This uniform is then used like so:

```
vec3 offset = A_offsets[gl_InstanceID];
gl_Position = T_MVP * vec4(position + offset, 1.0);

```

`A_offsets` up to this point is empty, so my 100 models (I am testing with 100 first, then when it works I can make this 1000) are draw successfully but in the same position, this was just to test the setup at least works, which it does.

But now I need to fill each index of `A_offsets` array and I am a little confused on how to do that. My engine stores the name and type of all uniforms using a parser on my shader files (`.glsl`), and in my game loop I get the uniforms by name or type and set values to them in a `updateUniforms()` call before the above `draw()` call. A simple `vec3` uniform is being filled like so:

```
if(uniformType == "vec3")
                SetUniformVector3f(uniformName, material.GetVector3f(uniformName));

```

The `setUnifromVector3f` function is as follows:

```
void Shader::SetUniformVector3f(const std::string& uniformName, const Vector3f& value) const
{
    glUniform3f(m_shaderData->GetUniformMap().at(uniformName), value.GetX(), value.GetY(), value.GetZ());
}

```

This would set the value of a `vec3` unifrom before the `draw()` call, my question is this - how would I do the equivalent to set the value of each element (index) in my `vec3` array uniform `A_offsets`? Ultimately I would want to assign each index of an array (`std::vector<Vector3f>`) I have already defined to each index of `A_offsets` array. I am yet to find an example online that uses perhaps `glUniform3fv(...)` to fill each index of a uniform that is an array.

***UPDATE(One day after asking original question):***

I have made some progress since asking this question and did not know quite how to convey this, creating a completely new GDSE question seemed silly and commenting on or answering the original question is not really what either of those features are for if all I am doing is giving an update on the problem, so I am just continuing the original question, in a way.

I have made developments that in my opinion have gotten instancing to work! I can see what looks like 1000 tree models drawn in my game with very low frame rate (16ms per frame draw), however, the rest of my game world (the terrain model, water model etc) are definitely "off", their positions are strange and my collision with them is way out of whack.

My slightly updated code is as follows:

Draw call:

```
glDrawElementsInstanced(GL_TRIANGLES, m_drawCount, GL_UNSIGNED_INT, 0, 1000);

```

Shader uniform:

```
uniform vec3 A_offsets[1000];

```

Uniform in use in the shader:

```
vec3 offset = A_offsets[gl_InstanceID];
gl_Position = T_MVP * vec4(position + offset, 1.0);

```

And now the new code, the filling of the uniform array `A_offsets` \- First, I have a new variable:

```
glm::vec3 translations[1000];

```

This then gets filled when I create my simple shader program(I give a random value between a range for the x and z components of the vec3's, y component is just 0):

```
m_fileName = fileName;
    if (fileName == "forward-ambient") {
        for (int i = 0; i < 1000; i++) {
            translations[i] = glm::vec3(-550 + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (550 - (-550)))), 0, -550 + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (550 - (-550)))));
        }
    }

```

And then in my `updateUniforms()` call before the `draw()` call I pass the `translations` array to a function that passes it to the shader to set the values in uniform `A_offsets` array:

```
else if (uniformName.substr(0, 2) == "A_") {//"A_" for "A_offsets"
            SetUniformVector3fv(uniformName, translations);
        }

```

function `setUniformVector3fv(...)` is as follows:

```
void Shader::SetUniformVector3fv(const std::string& uniformName, const glm::vec3 test[]) const
{
    glUniform3fv(m_shaderData->GetUniformMap().at(uniformName), 1000, (const GLfloat *)&test[0]);
}

```

The above code (in my mind) fills each index of my uniform array `A_offsets` with the value in each index of the previously setup `translations` array. I believe this works in rendering 1000 instances of my tree model as can be seen in the following image:

The issue is now this - the rest of my meshes (the terrain and water) are all messed up, in that my collision with them is way off (you can see in the image I am floating quite high above the ground), not to mention the general position of them has changed quite a bit, and my lighting (Directional Light) is not hitting them correctly or at all by the look of it (you can see the whole scene is evenly lit very dimly almost as if only the ambient light is working).

I suspect that the issue is this line in the shader:

```
gl_Position = T_MVP * vec4(position + offset, 1.0);

```

Because I have it currently that for things that need drawn normally (the terrain and water meshes) they call this regular draw function:

```
glDrawElements(GL_TRIANGLES, m_drawCount, GL_UNSIGNED_INT, 0);

```

But for meshes that need instancing (the trees) I call the new draw function:

```
glDrawElementsInstanced(GL_TRIANGLES, m_drawCount, GL_UNSIGNED_INT, 0, 1000);

```

Because of this when the terrain and water meshes are drawn they will enter the shader and at the line of code `vec3 offset = A_offsets[gl_InstanceID];` and `gl_Position = T_MVP * vec4(position + offset, 1.0);` I have no idea what the value of `offset` will be that is effecting the `position` as `gl_InstanceID` wont even be a thing for the regular draw call (`glDrawElements`) so I have no idea what will happend at the line `vec3 offset = A_offsets[gl_InstanceID];`, and in fact for when things that dont need instancing are being drawn I dont even want them to use the uniform `A_offsets` at all. So I must assume this is effecting the position, collision and lighting of the terrain and water meshes. Ultimately for when the water and terrain meshes are being drawn the code:

```
uniform vec3 A_offsets[1000];
//...
vec3 offset = A_offsets[gl_InstanceID];
gl_Position = T_MVP * vec4(position + offset, 1.0);

```

Should just be:

```
//Not using uniform A_offsets at all
gl_Position = T_MVP * vec4(position, 1.0);

```

Does anyone have any ideas?

I think a solution could be: depending on weather I am drawing a tree model or not pass `updateUniforms()` a `bool`, `true` for the tree and `false` for every other type of mesh, then depending on the value of the bool update a `uniform` `bool` to be `true` or `false`, then in the shader depedning on that bool value (`if` `else` logic) use the following code for `true`(the model is my tree):

```
uniform vec3 A_offsets[1000];
//...
vec3 offset = A_offsets[gl_InstanceID];
gl_Position = T_MVP * vec4(position + offset, 1.0);

```

And for `false` (model is not the tree) use the follwing code:

```
//Not using uniform A_offsets at all
gl_Position = T_MVP * vec4(position, 1.0);

```

# Answer
> 0 votes
My above suggested solution at the end of the question worked. I now have a new `uniform`:

```
uniform bool B_tree;

```

Which is used in the shader file as follows:

```
if(B_tree){
        vec3 offset = A_offsets[gl_InstanceID];
        gl_Position = T_MVP * vec4(position + offset, 1.0);
}else{
        gl_Position = T_MVP * vec4(position, 1.0);
}

```

This uniform is being set as follows - `updateUniforms(...)` is now passed a `bool` `isTree`, and this new argument is used as follows:

```
else if (uniformName.substr(0, 2) == "B_") {//"B_" for B_tree uniform
        if (isTree) {
                SetUniformi(uniformName, 1);//non-zero value passed equates to true
        }
        else {
                SetUniformi(uniformName, 0);//zero value passed equates to false
        }
}

```

`setUniformi()` function is as follows:

```
void Shader::SetUniformi(const std::string& uniformName, int value) const
{
    glUniform1i(m_shaderData->GetUniformMap().at(uniformName), value);
}

```

Now everything works.

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


# Question
Title: How to animate fluid filling down a pipe of any shape?
I am working on a project where I want to model a simple flow of fluids around a circuit of pipe. I thought a simple way to do this would be to create an irregular shaped loading bar, then animating the shape as it filled up.

I have found answers for how to create regular loading bars that are rectangle shaped, as well as some for circular loading bars.

But what if want some arbitrary "circuit" of pipes, kind of like one long windey loading bar.

# Answer
Maybe overkill, but I would use a fluid simulation. They usually simulate small particles that behave like molecules in a fluid (using all the fancy adhesion and cohesion physics stuff).

Be wary though, this will cost you a little bit on the performance-side.
> 0 votes

---
Tags: unity, 2d, animation
---


title: Simplifying Camera Strafing

text:
# Question
Title: Simplifying Camera Strafing
I have a camera that follows the position and direction of the player. These are updated using spin and velocity. The velocity is updated like so:

```
auto velocity = get_velocity();
velocity += get_acceleration().x * get_right();
velocity += get_acceleration().y * get_up();
velocity -= get_acceleration().z * get_forward();

set_velocity(velocity);

```

... where acceleration is relative to the object, not the world. This is the first time I have used OpenGL and I am not sure if this is the best solution, but it does what I want. I was wondering if there is a better way to do this using OpenGL Mathematics (GLM).

Additionally, this method works like a rocket, which is good for what I am trying to do, but if I want something more like a human, I have to change it to:

```
auto velocity = get_velocity();
auto const y = velocity.y + get_acceleration().y;
velocity += get_acceleration().x * get_right();
velocity -= get_acceleration().z * get_forward();
velocity.y = y;

set_velocity(velocity);

```

... to prevent the player from being able to fly by looking up. Is there a way of simplifying this case, too?

Acceleration is defined as:

```
switch (dir) {
    case left:  return glm::vec3(-1,  0,  0);
    case right: return glm::vec3( 1,  0,  0);
    case front: return glm::vec3( 0,  0, -1);
    case back:  return glm::vec3( 0,  0,  1);
    case up:    return glm::vec3( 0,  1,  0);
    case down:  return glm::vec3( 0, -1,  0);
    default: assert(false);
}

```

# Answer
> 0 votes
3D velocity and acceleration can be represented as 3D vectors. And you should use that instead of handling each case separately. As we know, position vector changes by velocity vector times some delta time. So does the Velocity by acceleration. AKA `dv = a*dt; dPos = dv * dt`. What you want to do would be

```
// assume [wasd] is your controller, and [wasd]Pressed() return 1 if key is pressed and 0 otherwise
Vec3 forward = Camera.forward()
Vec3 right = Camera.right();

acceleration = (forward - forward.y) * (wPressed()-sPressed()) + Camera.right() * (dPressed - aPressed()); // here we build direction of acceleration
velocity += normalize(acceleration)*accel *dt;
position += velocity * dt;

```

You have to take into account that constructing velocity/accelration from separate axes will give faster movement/acceleration while moving diagonally, so you always want to normalize the vector and multiply by magnitude. This solution also takes into consideration situations when multiple keys are pressed at once (left+right would result in no sideways movement).

This solution assumes that gravity and ground is down (0,-1,0). Otherwise you have to simply subtract from the forward vector the vector that is projected onto the normal to the ground.

But this sounds like you lack the physics engine that manages gravity and collisions... ?

**@EDIT by question's author**

> Anyways, this form can be rewritten to match your second example as follows:
>
> ```
> auto const f = get_facing();
> auto const a = get_acceleration();
> auto const abs_a = a.x * get_right()
>                  + a.y * get_up()
>                  - a.z * glm::vec3(f.x, 0.0f, f.z);
> add_velocity(abs_a);
>
> ```

^ That's not true. First of all - you messed up `y` and `z` components. Second - what do `get_acceleration/facing/right/up` return? Naming of those functions is obscure and I don't understand what they return. You have to name your functions so that they names describe best their functionality, and don't be afraid of longer names like `getCameraRight()` or `getAccelerationFromInput()`.

Also don't be afraid of commenting your code. If you have `forward-forwad.y` you, of course CAN replace it by `glm::vec3(forward.x, 0, forward.y)`, but... it's longer... and harder to modify in the future... Just put a comment in code that `//zero UP acceleration to disable flying`

If your UP vector is not (0,1,0) then you have to reinvent the logic. `forward - proj(forward, UP)` would be enough for my solution. I insist that you try my solution, because it is extendable if you want to, for example, have different speeds for walking forward, backward or strafing. You would just do

```
acceleration = normalize((forward - forward.y)) * (wPressed()*wSpeed()-sPressed()*sSpeed()) + normalize(Camera.right()) * (dPressed*dSpeed() - aPressed()*aSpeed()); // here we build direction of acceleration
velocity += acceleration *dt;
position += velocity * dt;

```

Don't forget about normalizing vectors to have uniform behavior when looking at horizon and looking up.

---
Tags: opengl, mathematics, camera, glm
---


# Question
Title: How do you combine multiple meshes into one in Blender?
I need to combine multiple meshes into one in Blender 2.8 (Just make them into a single mesh that looks like all of them in their normal positions). I am doing this mostly for performance improvement in my game, since the teeth are all separate.

Does anyone know how to do this?

# Answer
> 1 votes
Havent used blender in a while but if you just need to join the objects then sure you can, see this answer on blender.se: How do I make multiple Blender objects into one?

If you want to do other kinds of joining you might have a look into booltool for blender or join the objects first and then edit the resulting object yourself.

---
Tags: blender, 3d-meshes
---


# Question
Title: Circle Square Collision Detection Simple Formula
Say I have a circle of diameter `c` and a square with a base of `s`.

Is there a simple formula to check whether they have collided?

Something like `distance(square, circle) < s / 2 + c / 2` where `distance(square, circle)` finds the distance between the centers of the objects?

I know the full solution is more complicated due to diagonals, but would my formula be OK in a fast moving game where exact precision is not required? Is there another "good enough" solution which is simple to implement?

# Answer
> 2 votes
We can think of collisions between a square and a circle as a collision between a rounded square and a point. Effectively, we strip off all the "round stuff" making up the disc, and add it onto the square instead (an operation called Minkowski addition).

If the the remaining center point of the circle is inside the rounded square, then the original square and circle collide. If there's a separation between the point and the rounded square, then the original square and circle are separated by this same distance.

We can quickly compute the signed distance of a point from a rounded rectangle (a square is just a special rectangle with equal width and height) using the formula provided by Inigo Quilez here:

```
float Separation(Rectangle rectangle, Circle circle) {

    // Here I assume the square is never rotated, and stays axis-aligned.
    Vector2 relativeCenter = circle.center - rectangle.center;

    Vector2 offsetFromCorner = abs(relativeCenter) - rectangle.halfExtents;

    return min(max(offsetFromCorner.x, offsetFromCorner.y), 0)
         + length(max(offsetFromCorner, Vector2.zero))
         - circle.radius;
}

```

If this value is negative, the circle and square overlap by this penetration distance. If it's positive, they're separated by this distance. If it's zero, they're kissing exactly edge-to-edge / edge-to-corner.

---
Tags: collision-detection
---


# Question
Title: Why do companies still use really old versions of Visual Studio?
I understand why C++ is used. That is not what this question is about.

When I install games, commonly Steam (I pretty much only use Steam these days) will install the C++ 2005 Runtime distributable.

My question is why is this the case? What is the reason a runtime released over 8 years ago is still prevalent? Some of the games I've installed recently are slightly older, so assuming a couple of years dev time you could make the case it was the tried and tested standard at the time.

Why do game companies not use a newer version of the VC++ runtime?

# Answer
Companies don't upgrade VS willy-nilly. We're using 2010SP1 for instance on a project not planning to ship for several years. Using a newer version would mean buying new licenses to the IDE, possibility buying new licenses to plugins we use, and of course risking some show-stopping bugs that haven't been worked out. We already paid for 2010 and know 2010 will work for our needs though.

I admit it annoys me at times; I really would like the newest C++11/14 support, AMP support, and improved optimizations, but that kind of "upgrade to the new shiny" mentality doesn't mesh well with larger, more serious projects.

Most corporate entities are very, very conservative about updating any piece of software, be it Visual Studio, Office, Windows, Perforce, whatever. While Visual Studio 2005 usage is pretty rare for games today, 2008 is still pretty common. Very very few are using 2012. It's quite possible that uptake of 2012 will never happen en masse and that the next popular version of Visual Studio will be 2013 or 2014.

See for instance how rapid the common enthusiast-oriented Linux distro updates versions compared to the release cadence of Redhat Enterprise or Ubuntu LTS. Home users and hobbiest can more easily justify upgrades and enthusiasts often clamor for them, but businesses typically want as little change as possible.

Another factor today is XBox 360 compatibility. It's silly to buy and install two versions of the IDE/compiler if you need one in particular for XBox compatibility. Which next version of VS becomes popular for games will depend largely on which compiler the XBox One recommends for the release versions of its devkits (2012 is used for the beta devkits used for launch games, but 2013 might be recommended down the road for post-launch titles).

In terms of the runtimes used by the compilers, these must match exactly with the compiler in use. Part of this is because of how C and C++ work. Interfaces are defined by header files, which are really just a fancy way to do cut-n-paste. Consider exhibit A:

```
void foo(char* name, int length);

```

And now consider exhibit B:

```
void foo(int length, char* name);

```

If these C functions were included in two different versions of the runtimes, they've both be symbol `_foo` but the code compiled to use one would clearly not work for the other. While the compatibility problems are generally a bit more involved and subtle, the end result is still the same: code compiled with VS2005 will have header from VS2005 which only describe how the VS2005 runtime works. VS2012 ships with entirely different headers targetting an entirely different runtime.

Microsoft does not support targetting older verions as that would really just be a pain. They'd have to ship and then continue maintaining old headers in addition to the runtimes. There's relatively little reason for it as good DLL usage practices in Windows allow developers to mix libraries using different runtimes. If you have VS2012 you can still link against libraries made with VS2005, so long as you and the library follow a few easy rules.

Platforms like GNU/Linux go through some effort to avoid these issues, but have gone through them, sometimes at a much deeper level. I still recall the libc5 to glibc transition, or the frequent libstdc++ breaks of the time (this is one reasons Linux/UNIX developers have remained relatively cold on the topic of C++ over the years).

Windows does ship with a low-level "generic" C runtime called `MSVCR.DLL`, though each version of the compiler include its own replacement e.g. `MSVCRR110.DLL`. You can go to effort to use only the generic version but it is missing a great deal of functionality, including most of the C++ support routines that change with each version of Visual Studio (and its ever evolving support of C++). It's generally not worth the effort and lost functionality unless you're really trying to make a zero-dependency application (recovery tools, OS tools, security tools, and so on sometimes fall into this class).

In short, each Visual Studio has its own runtime library, and application compiled with that version must use. Games will typically be written using less than the most cutting edge compiler and hence will require an older runtime.
> 20 votes

# Answer
As far as I know visual studio 2008 is the last version capable of building Windows Mobile and Windows CE applications.

I need to support apps running on CE devices so VS2008 is still what I use.

For my Windows Desktop apps I use VS2010 Pro for the simple reason than I own the licence. It works. I like it. and I don't see why I should fork out more money for a newer version that doesn't actually make my apps any better.
> 1 votes

---
Tags: c++, game-industry
---


# Question
Title: nullObjectException in OnDrawGizmos Function
I was studding A\* Algorithm and it is showing a `nullObjectException` in my OnDrawGizmos function whenever it finishes compiling the code.

Here is my code - can anybody tell me what I am doing wrong?

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

namespace PathFinding {
    public class Grid : MonoBehaviour {
        public Transform Startpostion;
        public LayerMask Layer_Mask;
        public Vector2 gridWorldSize;
        public float nodeRadius;
        public float Distance;

        public Node[ , ] grid;
        float NodeDiameter;
        int GridSizeX, GridSizeY;
        public List<Node> FinalPath;

        private void Start () {
            NodeDiameter = nodeRadius / 2;
            GridSizeX = Mathf.RoundToInt (gridWorldSize.x / 2);
            GridSizeX = Mathf.RoundToInt (gridWorldSize.y / 2);
            GridCreator ();

        }
        void GridCreator () {
            grid = new Node[GridSizeX, GridSizeY];
            Vector3 bottomLeft = transform.position - Vector3.right * gridWorldSize.x / 2 - Vector3.forward * gridWorldSize.y / 2;
            for (int y = 0; y < GridSizeY; y++) {
                for (int i = 0; i < GridSizeX; i++) {
                    Vector3 WorldPositionOfCurrentNode = bottomLeft + Vector3.right * (i * NodeDiameter + nodeRadius) + Vector3.forward * (y * NodeDiameter + nodeRadius);
                    bool Wall = true;

                    if (Physics.CheckSphere (WorldPositionOfCurrentNode, nodeRadius, Layer_Mask)) {
                        Wall = false;
                    }
                    grid[i, y] = new Node (Wall, WorldPositionOfCurrentNode, i, y);
                }
            }
        }
        private void OnDrawGizmos () {
            Gizmos.DrawWireCube (transform.position, new Vector3 (gridWorldSize.x, 1, gridWorldSize.y));

            foreach (Node n in grid) {
                if (n.is_Wall) {
                    Gizmos.color = Color.white;
                } else {
                    Gizmos.color = Color.yellow;
                }
                if (FinalPath != null) {
                    if (FinalPath.Contains (n)) {
                        Gizmos.color = Color.red;
                    }
                }
                Gizmos.DrawCube (n.postion, Vector3.one * (NodeDiameter - Distance));
            }
        }
    }
}

```

# Answer
Try adding this to the top of your `OnDrawGizmos` function:

```
 if(grid == null || grid[0,0] == null)
     return;

```

Remember that `OnDrawGizmos` runs in the editor, even when the game isn't running. So your `Start` method that calls `GridCreator` and populates your grid hasn't run yet.

Without this code running to provide initial values, your grid variable is `null` and contains no valid nodes to loop over.

So, you can either force initialization of your grid before trying to work with it in `OnDrawGizmos`, or abort gizmo-drawing until the data is populated.
> 1 votes

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


title: Unity Can't adjust firing rate

text:
# Question
Title: Unity Can't adjust firing rate
I need to be able to control the speed in which the gun fires. I'm trying to use the couroutine to limit the speed of update method but it doesn't work for some reason.

I've tried several fireRate values(10K etc.), none of them seem to slow the updates. How can I accomplish this feat?

```
 float fireRate = 10.1f;

        public IEnumerator CheckFireRate()
        {
            yield return new WaitForSeconds(fireRate);
        }

        void Update()
        {
            StartCoroutine(CheckFireRate());
            //Fire gun
        }

```

# Answer
> 1 votes
* `Update` is called every frame
* `StartCoroutine` starts a *new* coroutine and immediately returns control flow back to the method that called it.

It does not wait until the coroutine has run to completion (that would cause the game to freeze)

Taken together, what your code currently does:

* every frame, it starts a new copy of the coroutine waiting for `firerate`.

This means you may have dozens of coroutines all waiting in the background.
* then, every frame, it fires the gun, without waiting for anything the coroutines do.

What you want is something more like this:

```
// This is a delay period, not a rate.
// The rate of fire is 1 shot divided by this many seconds.
public float firingPeriod = 10f;

// We start our coroutine only once, when the script starts,
// not spawning a new copy of the coroutine in every frame update.
void Start() {
     StartCoroutine(FireLoop());
}

IEnumerator FireLoop() {
    // Loop this coroutine as long as the script stays active/enabled:
    while(true) {
        // Let the game run for some time.
        yield return new WaitForSeconds(firingPeriod);

         // After waiting, fire.
         FireGun();

         // Repeat.
    }
}

```

---
Tags: unity, coroutines
---


# Question
Title: Photon Realtime, StripKeysWithNullValues cause heavy GC Alloc
In our current project, we use Photon room properties to sync entities. and i noticed some heavy GC Allocs while deep profiling the game and it always ends down to this method.

Have anyone faced this issue before ? or attempted to fix it ? here is the source code of that method.

```
/// <summary>
        /// This removes all key-value pairs that have a null-reference as value.
        /// Photon properties are removed by setting their value to null.
        /// Changes the original passed IDictionary!
        /// </summary>
        /// <param name="original">The IDictionary to strip of keys with null-values.</param>
        public static void StripKeysWithNullValues(this IDictionary original)
        {
            object[] keys = new object[original.Count];
            original.Keys.CopyTo(keys, 0);

            for (int index = 0; index < keys.Length; index++)
            {
                var key = keys[index];
                if (original[key] == null)
                {
                    original.Remove(key);
                }
            }
        }

```

# Answer
> 3 votes
I don't know anything about Photon, but I suspect your keys array is very large. The `CopyTo` method is allocating all of that memory, and then it must be cleaned up.

Instead of duplicating the array, make a new list, and add all of the keys to remove to it. Then loop back through, and clean up. Something along the lines of:

```
/// <summary>
/// This removes all key-value pairs that have a null-reference as value.
/// Photon properties are removed by setting their value to null.
/// Changes the original passed IDictionary!
/// </summary>
/// <param name="original">The IDictionary to strip of keys with null-values.</param>
public static void StripKeysWithNullValues(this IDictionary original)
{
    var keysToRemove = new List<object>();
    foreach(var entry in original)
    {
        if(entry.Value == null)
        {
            keysToRemove.Add(entry.Key);
        }
    }
    foreach(var key in keysToRemove)
    {
        original.Remove(key);
    }
}

```

You can further reduce memory allocation by implementing @Ed Marty's and @DMGregory's suggestions:

```
private static List<object> keysToRemove = new List<object>();
public static void StripKeysWithNullValues(this IDictionary original)
{
    if(original.Values.Count(v => v == null) == 0)
    {
        return;
    }
    keysToRemove.Clear();
    foreach(var entry in original)
    {
        if(entry.Value == null)
        {
            keysToRemove.Add(entry.Key);
        }
    }
    foreach(var key in keysToRemove)
    {
        original.Remove(key);
    }
}

```

---
Tags: unity, photon
---


# Question
Title: Material changes to "material (instance)" on Start
Not sure why my materials started doing this, but when I press play, all materials on my models change to "materialName (Instance)".

I use the same material for several objects, and for some it adds (Instance), and for some it does not.

Turns out that since I wanted to modify the material at runtime, it created an instance, which makes a lot of sense. So then my questions is, what are the downsides of this? Does it affect performance?

I only have 1 material for my entire game, so I batch probably 95% of my draw calls, will this affect that?

# Answer
When you access a renderer's material with the `.material` getter, Unity instantiates a new copy of the material unique to this object — that's why you see an "(Instance)" added to its name.

The benefit of this is that now you can make any changes you want to this object's material, without unwanted effects on other objects that use the same material, and without inadvertently saving runtime modifications into the source material asset stored on disc / in your project's version control.

But it does come with costs:

* The new material needs to be allocated, which takes a little time
* The object using the new material won't batch together with other objects that used the same source material — even if two script instances both independently copied the material and made the same changes to it, Unity can't guarantee they're the same, so they won't batch together
* The memory used by the new material isn't automatically garbage collected when your object is destroyed. Unity usually cleans these up on scene loads (and will log a warning in the editor about "leaking materials" if you've left some to pile up this way)

These impacts aren't drastic. If you have just a few long-lived objects that need this, you're probably safe enough with this default behaviour.

But if you need a lot of objects with material variants, or you're frequently spawning and despawning objects with a modified material, then all the extra batch splits and memory allocation can add up.

Fortunately you can control when to make copies and when to avoid/get rid of them:

* You can use the `.sharedMaterial` getter to take the current material as-is, without making a copy.

Doing so, you take responsibility for sorting out when you want to make a new copy with `Instantiate(material)` before modifying it, so you don't modify a shared asset.
* You can create your own material cache that keeps track of what material variants you've instantiated this way, and re-uses the same one if several different objects want "this base material, but blue". This way you avoid redundant allocations and preserve batching between objects using the same look.
* You can `Destroy(materialInstance)` on a material copy you've created when you're done with it (say, inside your object's `OnDestroy()` method, or when your cache's ref count hits zero), so you don't leak memory until the next scene load purges unused materials. (In the editor, you'd use `DestroyImmediate(materialInstance)` instead)
* You can use `MaterialPropertyBlocks` as a more lightweight way to make small changes to materials, like just changing a colour. This still breaks batching between versions that use different properties, but has less overhead than a whole new material, and you don't need special clean-up considerations since they're garbage collected automatically when the objects using them are destroyed.

---

Note that in the new scriptable render pipelines (HDRP and URP), the SRP Batcher is better able to combine draw calls between material instances using the same compatible shader variant but with different properties, so there's no need to use Material Property Blocks in this case (in fact, they'll break this optimization).
> 5 votes

---
Tags: unity, materials
---


# Question
Title: UnrealEngine: Variables of GetGameMode are empty
I'm confronted with the following issue:

* Inside the class setup for one of my actors, I'm trying to get the value of an array which is declared, instanced and successfully populated in my GameMode's BeginPlay function. I've tested it many times over with print strings. The variable is solid.

However, inside my actor, when I go through GetGameMode, and access that value (i.e. an array), it is empty. For the life of me, I can't figure out what I'm doing wrong.

Here's the screenshot of the actor's blueprint, where the array called Players Array returns empty.

Thank you for your time :)..

# Answer
SOLVED:

If this can be useful to anyone else: All I had to do was spawn my actor from within my gamemode
> 1 votes

---
Tags: unreal, blueprints
---


title: Hinge joints chain movement (2D)

text:
# Question
Title: Hinge joints chain movement (2D)
I have some problems with hinge joint chain movement calculations...

Here is my algorithm for segments location/rotation adjustments after a previous segment update (C#):

```
void AdjustLocation()
{
    float halfWidth = Size.Width / 2;

    // Translations
    Vector parentBack = PrevSegment.Center - (halfWidth * new Vector(Cos(PrevSegment.Rotation), Sin(PrevSegment.Rotation))); // Green on the pic
    Vector front = this.Center + (halfWidth * new Vector(Cos(this.Rotation), Sin(this.Rotation))); // Blue on the pic

    // Const spacing between segments
    float spacing = *some_value*;

    Vector dv = parentBack - front;
    float k = spacing / dv.Length;

    // New front location
    front = parentBack - (dv * k);
    // New rotation
    dv = front - this.Center;
    this.Rotation = Atan2(dv.Y, dv.X);

    // Translate back to the center
    this.Center = front - (halfWidth * new Vector(Cos(this.Rotation), Sin(this.Rotation)));

    NextSegment?.AdjustLocation();
}

```

It's working (partially), but it seems I'm missing something as it doesn't behave like a chain. Segments always move one by another although they should not always do this. Also overlapped sections of a long chain form a "knot" going all the way to the end of the chain before its "untangling". What am I missing?

Btw: everything screws up with negative spacing values.

P.S. Tried to visualize the algorithm on the picture:

# Answer
I figured it out myself.

```
void AdjustLocation()
{
    float halfWidth = Size.Width / 2;

    // Current segment back positions
    Vector offset = (halfWidth * new Vector(Cos(this.Rotation), Sin(this.Rotation)));
    Vector backPos = this.Center - offset;

    Vector newFrontPos;
    if (SegmentsSpacing > 0)
    {
        // Current segment front position
        Vector frontPos = this.Center + offset;

        // Parent segment back position
        offset = (halfWidth * new Vector(Cos(PrevSegment.Rotation), Sin(PrevSegment.Rotation)));
        Vector parentBackPos = PrevSegment.Center - offset;

        // Find delta
        Vector dv = parentBackPos - frontPos;
        float k = SegmentsSpacing / dv.Length;

        // Calculate new front position
        newFrontPos = parentBackPos - (dv * k);
    }
    else
    {
        // Calculate new front position
        offset = ((halfWidth + SegmentsSpacing) * new Vector(Cos(PrevSegment.Rotation), Sin(PrevSegment.Rotation)));
        newFrontPos = PrevSegment.Center - offset;
    }

    // Calculate new rotation
    Vector dv = newFrontPos - backPos;
    this.Rotation = Atan2(dv.Y, dv.X);
    // Translate back to center
    this.Center = newFrontPos - (halfWidth * new Vector(Cos(this.Rotation), Sin(this.Rotation)));

    NextSegment?.AdjustLocation();
}

```

My mistake was that I calculated the rotation using wrong points (it should be equal to the angle between the new front position and the old back position of a segment).
As for spacing, everything's much simplier with negative values (because you can simply move the front position of a segment to the joint position), otherwise, you must find the correct point on the line between the front position of a segment and the back position of its parent segment.
> 1 votes

---
Tags: physics, movement
---


title: Pinball flippers: Joints or not?

text:
# Question
Title: Pinball flippers: Joints or not?
When making pinball flippers in Unity C#, what would be the pros and cons of using a simple mesh transform -- where the mesh is properly centered around the wanted pivot, so its rigidbody could be torque force rotated -- vs creating the flipper with a joint? Thanks!

# Answer
> 1 votes
Hinge joints with a spring and motor work well. `hinge.useMotor` is being turned on when `Input.GetKeyDown()`, and off when `Input.GetKeyUp()`.

The **Flipper joint settings**, inspired by this asset:

```
Axis 0, 1, 0
Use Spring
    Spring 2
Motor
    Target Velocity 3000
    Force 100
Use Limits
    Max 55
    Bounce Min Velocity 0.2

```

And **Project Time settings** -- handle with care as it may affect framerate:

```
Fixed Timestep 0.002
Maximum Allowed Timestep 0.03333333

```

Flipper, ball and bumpers all have respective Physic Materials to lower friction and more.

---
Tags: unity
---