# Question
Title: Draw multiple times same object but translated and rotated
I want to draw lots of spheres in different locations and orientations with Opengl4 and JOGL. As the vertexes and colours are the same for all of them, I have just one array for vertexes and another for colours. For the positions and orientations, I have another big matrix where I have all data for all spheres.

In principle, drawing one with glDrawArrays is not a problem but for severals, I have read that I should use glDrawArraysInstanced instead. My problem is that I am a bit confused about how to apply each transformation for my particles. How should I introduce this array into the shader? Should I send the matrix model after doing the transformations in the cpu or should I send the positions and orientations and transform them inside the shader? How do I connect the data to the shader? How should the shader look like?

# Answer
> 3 votes
Yes, in instanced rendering, you typically supply transformation matrices. And this is how you do that in OpenGL:

In the vertex shader, you supply vertex position and normal as you usually do, but now you also have a vertex attribute for the transformation like this:

```
in mediump vec4 position;
in mediump vec4 surfacenormal;
in mediump mat4 trf;

```

And then you multiply your position and surfacenormal with the transformation matrix like so:

```
mediump vec4 transformedpos = trf * position;
mediump vec4 sn = surfacenormal;
sn.w = 0.0;
mediump vec4 transformedsurfacenormal = trf * sn;

```

Next, use the transformed version in your vertex shader as you usually do.

The matrix on the application side, is treated as 4 consecutive vertex attributes of 4 floats each.

You need to tell OpenGL that these vertex attributes need to advance to the next value, not for each vertex, but once for each instance. You do this with glVertexAttribDivisor() calls like so:

```
glVertexAttribDivisor( ATTRIB_TRF+0, 1 );
glVertexAttribDivisor( ATTRIB_TRF+1, 1 );
glVertexAttribDivisor( ATTRIB_TRF+2, 1 );
glVertexAttribDivisor( ATTRIB_TRF+3, 1 );

```

And tell OpenGL where to find these 4 consecutive attributes in the VBO:

```
glVertexAttribPointer( ATTRIB_TRF+0,  4, GL_FLOAT, 0, 16 * sizeof(float), (void*) ( off +  0*sizeof(float) ) );
glVertexAttribPointer( ATTRIB_TRF+1,  4, GL_FLOAT, 0, 16 * sizeof(float), (void*) ( off +  4*sizeof(float) ) );
glVertexAttribPointer( ATTRIB_TRF+2,  4, GL_FLOAT, 0, 16 * sizeof(float), (void*) ( off +  8*sizeof(float) ) );
glVertexAttribPointer( ATTRIB_TRF+3,  4, GL_FLOAT, 0, 16 * sizeof(float), (void*) ( off + 12*sizeof(float) ) );

```

Note that you will want to put the per-instance data in the VBO, after all the normal model (per-vertex) data, which in my code sample has size 'off'.

Typically, you will want to change the values for these transformation each frame. This means you need to update a part of your VBO and put in the new versions of the matrices. This is done with glBufferSubData()

```
const size_t sz = 16 * sizeof( float ) * objCnt;
glBufferSubData( GL_ARRAY_BUFFER, off, sz, object_matrices );

```

And finally draw all instances with a call to glDrawInstancedArrays()

```
glDrawArraysInstanced( GL_TRIANGLES, 0, numVerts, objCnt );

```

Here, numverts is the number of vertices in the model itself, not the total nr of verts drawn for all instances.

To sum it all up: the instance transformation matrix is treated as a per vertex attribute in your GLSL vertex shader. Yet, the data is fed not as a value per vertex, but only a new value per (typically 1) instance using glVertexAttribDivisor() which you need to call four times, once for each row in the matrix.

# Answer
> 1 votes
For instanced rendering there's GLSL variable called `gl_InstanceID`, which stores the id of the current instance. You can do 2 things:

1.) You create an array of matrices and you load each transformation matrix in it, then use the instance id to get the correct one. This way you don't have to create matrices on the fly (you only have to do it once, not as for each vertex), but you'll need to have a max number of spheres, because OpenGL doesn't support dynamic arrays.

2.) You load the positions and rotations as vec3-s in a dynamic buffer, then you reconstruct the matrices on the fly. If the spheres don't have too many vertices, then this may be a better solution.

# Answer
> 1 votes
As i understood you can draw them by this way.

you should have a `vec3` list which you hold the positions of spheres.(another list for rotations)

using for loop

```
for(int i = 0;i < count_of_positions;i++)
{
    modelMatrix.translate(positions[i]);
    (same for rotations)
    shader.setUniformMat4("modelmat", modelMatrix);(example shader code)
    glDrawArrays(params);
}

```

---
Tags: opengl, java, jogl
---


# Question
Title: How to show a canvas text when i click an UI button on Android
I am trying to show a text when i click on a ui button but i don't know how to implement this. On PC platform I have a collider per object and when the player stay and click the E button, a canvas text appear on screen, but i don't know how to do this on Android. I want something like Resident Evil old style action button, opening doors and getting object description. How could i do this?

**The Script**

```
public class readingNote : MonoBehaviour {

    public AudioSource audio;
    public AudioClip collectSound;
    public  bool playerNextToKey = false;
    bool hasCollided = false;
    public GameObject pic;
    public GameObject text;
    public GameObject notePad;
    private Collider other;

//  void Start () {
//      pic.SetActive(false);
//      text.SetActive (false);
//
//  }

    public Button yourButton;

    void Start()
    {
        pic.SetActive(false);
        text.SetActive (false);
        Button btn = yourButton.GetComponent<Button>();
        btn.onClick.AddListener(TaskOnClick);
    }

    void TaskOnClick()
    {
      //can't text.SetActive(true); because when i get out the scene, text is showing up (I use the same button to open doors and get text description).
    }

    void OnTriggerStay ( Collider other) {

        if(other.gameObject.tag == "Player") {
            //if(Input.GetKeyDown(KeyCode.E)) {
                text.SetActive (true);
                pic.SetActive(true);

                AudioSource.PlayClipAtPoint(collectSound, transform.position);
            //}

        }
    }

    void  OnTriggerExit ( Collider other  )
    {
        if (other.gameObject.tag == "Player")
        {
            //enter = false;
            //print("close");
            playerNextToKey = false;
            hasCollided = false;
            pic.SetActive(false);
            text.SetActive (false);

        }
    }

}

```

# Answer
> 1 votes
as you said in your comments you need a system that shows specific info in specific trigger. you can do it in many different ways. right now using something like a dictionary is in my mind. first of define triggers and a variable in class of your character. I write it as psudo code so it may need some changes.

```
public GameObject   canvasText; //assign ui text game object in editor

string mystring;

    void start()
{
Dictionary<string, string> mydic =  new Dictionary<string, string>();
mydic.add("x1","open the door");
mydic.add("x2","pic up the pistol")
}

void onTriggerEnter(collider other)
{
mystring=mydic[other.name];
}

void onTriggerExit(collider other)
{
mystring="";
canvasText.getcomponent<Text>().text="";
}

    public void UIbutton()// assign this function to function of your button in editor
    {
canvasText.getcomponent<Text>().text=mystring;
    vanvasText.setActive(true);
    }

```

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


# Question
Title: Is it possible to control the difficulty of a multiplayer game?
I'm developing a multiplayer game, played between 2 players. But in these types of games, there can only be 1 winner and 1 loser for per match. So for each player who wins, another player had to lose. This means that roughly 50% of all players in the game are having a bad time (losing more than they win).

In a single-player game, it's easy to solve the problem of "50% of players lose more than they win." You just make the game easier to beat (reduce difficulty). Unfortunately, you can't do this with a multiplayer game, since players' opponents are other players. I don't know if there's a way to control the difficulty of a multiplayer game, but is this even possible?

# Answer
So players in a competitive game either have fun or lose. Why not both? Losing doesn't have to feel bad, or rather, you can have fun without winning.

A lot of team-based games do this by de-emphasising the win/lose outcome itself, and provide lots of alternate goals (and even meta-goals). Your team may lose but maybe you topped the scores. Or you made the most assists, pulled off that one crazy play, or simply had fun socially interacting with other players. There are many ways to appeal to different players, a good game knows this and appeals to their target audience.

In Bartle's taxonomy of player types, the kind that care most about winning would be **killers**. But note that there are other player types who are motivated by other factors. For example:

* **Achievers** may care more about statistics, or achievements, and not about one particular match outcome
* **Socialisers** may care more about things like role playing, or chatting about memorable game moments
* **Explorers** may care more about their own meta-goals, like learning new strategies, so they may enjoy losing if it's part of their learning experience

But if you assume we're just talking about killers, and restrict the problem to 1v1 competitive games where there's an inevitable winner and loser, there are a few things you can do to minimise the pain of losing:

* **Matchmaking**. Make sure players don't play too many games against tough opponents and become upset from big losing streaks. Your good players will appreciate it too by not having to play many boring easy games.
* **Rubber-banding**. While this is controversial and is not appropriate for all games, it does improve the experience for less-skilled players by keeping them in the game, and not letting them fall too far behind. Likewise, look at ways you can prevent good players from getting too far ahead and becoming dominant. There are many ways to achieve this: arena shooters like Quake have level designs that place the best powerups far apart and in exposed areas, making it impossible for players to camp a single position and dominate with good powerups.
* **Randomness**. Add chance-based elements to your game, so that less-skilled players can occasionally win despite being out-classed. Even a little bit of randomness goes a long way, as it exploits psychology to keep less-skilled players in the game, waiting for the next time they "get lucky".
> 9 votes

# Answer
Many competitive multiplayer games rank their players and then match players of similar ranking.

That means bad and inexperienced players will only play against other bad and inexperienced players while the pro's will only play against other pro's. When a player wins or loses a lot of games in a row, their rank changes accordingly and they are again matched more evenly. The goal is that everyone wins about 50% of all matches they play.

A common ranking system is ELO which was originally developed for chess but can be used with any game with two players and a clear win/draw/loss outcome. There are also variants of it which can be applied to games with more players or which allow to also factor in how decisive a win was.

You can also use a league system like in professional sports. Put your players into tiered leagues and in regular intervals move the top x% of all players of a league into the next stronger tier and the bottom x% into the next lower tier.

As a side-effect, such a ranking system adds another gamification system to the game because players can now measure their long-term success by looking at how their rank improves over time.
> 3 votes

# Answer
You could handicap the winner. Make him a little slower, make it a little harder to aim, make it so that the camera shakes for him a bit when he runs, make it so that his rate of fire is a little slower, and so on. Of course the people who get handicapped will probably get mad over it but if they are winning by a huge amount it might actually make the game more interesting for them.
> 1 votes

# Answer
You could try implementing interesting cheats or other interesting things for the looser.

In competetive games there is a factual winner and a factual looser.

You could let the looser have some fun by giving him cheats, when he admits he is outclassed or has lost.

When someone then uses those cheats they should give both players kind of a fun experience, but the looser still gets a loss in his game history and for ranking purposes.

This would only work in 1v1 though, otherwise this is impossible to implement.

Or you could make achievements or secondary game objectives.

Eg. if you have an ingame currency, the loosers gets a bonus for the amount of time he held on against a superior opponent.

Or try to portray the loss in a good light in some way. Gather different stats and point out the ones that were above average for the playerbase or the player himself.

Give the player a replay of the game so he can watch his opponent and learn, and encourage him to do so, eg. by giving him ingame currency for watching his own replays.
> 0 votes

---
Tags: multiplayer, balance, pvp
---


# Question
Title: Moving CCNode with constant speed in cocos2d
I want to **move the object** (CCNODE) with **constant speed** in **any direction** , what i have did till now is applied a force to object at start to get it moving and set elasticity as 1 and friction as 0 to every object which it will collide .

After some time speed goes on increasing , is there any way so i can check if speed increased so that i can control it or to apply velocity instead of force . Thanks !

# Answer
> 1 votes
You can check the velocity in your update function and set it to some max value if the calculated value will be greater than that max. This way you still use force and allow it to stop when it collides with another object, but it will never be able to go faster than the maximum velocity you set.

# Answer
> 1 votes
Just slow it down or speed it up with a force proportional to the error.

If your intentions were to hit a certain position for your object, you would actually need something more advanced like a Proportional Integral Differential Controller.

But if you merely aim for a certain velocity, not a certain position, then its quite easy by setting a force each frame.

---
Tags: physics, game-mechanics, iphone, cocos2d-iphone
---


# Question
Title: Attempting to implement particle movement from N-S-E-W movements
For a personal project, I am attempting to create an environment for reinforcement learning algorithms. Specifically, I want the user (i.e., an artificial intelligent agent, but for intuition you can also think of a human game player) to control a 2-D "point" in some grid. The actions that the user can apply are NORTH, SOUTH, EAST, and WEST.

Pressing NORTH, for instance, should obviously move the particle north. But how do I ensure that if the user keeps applying the NORTH action, that the particle moves faster? And then if the user applies SOUTH, the particle shouldn't reverse immediately but should slow down a bit and then move down, depending on how long the user presses SOUTH. And then if the user presses EAST while the particle is moving south, then the particle should move south-east, and so on.

For the movement part, I am going to follow this tutorial which uses basic trigonometry to determine the resulting movement given the velocity in the x and y directions (see the section "Movement vectors").

However, I'm unsure on how to implement the acceleration, and the tutorial assumes we already have some velocity, but I need to define a reasonable mapping from NORTH, SOUTH, etc., actions to velocity.

I'm not a physicist, so I'm probably missing something obvious. If so, any possible supplemental references would be appreciated. And just to be clear, I'm not looking for a guide on particle *collisions* and the like; my interest is trying to simulate realistic movement from NORTH, SOUTH, EAST, and WEST user-provided actions.

Thanks!

# Answer
> 1 votes
You need to associate both velocity and position to your particle. Each frame, you update the position using its velocity. But you also update the velocity, based on the keys. At the lack of key presses, the particle will maintain its current velocity. (\*)

```
void update( float dt )
{
  // accelerate and decelerate particle.
  float scl=1; // acceleration in units/sec/sec.
  if ( n ) vel.y += scl * dt;
  if ( s ) vel.y -= scl * dt;
  if ( e ) vel.x += scl * dt;
  if ( w ) vel.x -= scl * dt;

  // move particle with vel units/sec.
  pos.x = pos.x + vel.x * dt;
  pos.y = pos.y + vel.y * dt;
}

```

In physics terms:

* velocity is the rate with which the position changes per second. (m/s)
* acceleration is the rate with which the velocity changes per second. (m/s²)

(\*) If you want the particle to gradually slow down during lack of key presses, you need to model friction.

---
Tags: 2d, physics, movement
---


title: How to bypass build-in variables?

text:
# Question
Title: How to bypass build-in variables?
I've been busy working with Gamemaker Studio 2 and I've noticed that it has quite some build-in variables. Like 'x', 'y', 'speed', 'health'. These variables have already a set function, and it overlaps the variable I've set by myself.

I was earlier looking at a tutorial that adds an underscore to all his variables so these will appear on top once written out completely, While it worked, I didn't liked the look of all these uinderscores. hence why I was asking myself if it could be done easier.

So, does anyone knows an other method to make custom variables without the chance to have the build-in variables overlapping them?

# Answer
After some time playing around, I've found my own way.

I can just use my own variables without the underscore at the end, and if it happens that I need to use a variable with the same name as a build-in variable. Then I'll simply add 'my' at the front, like `mySpeed` or `myhealth`.

These can appear even earlier in the intellisense as well as 'my' is pretty unique conpared to the build-in variables.
> -1 votes

---
Tags: game-maker, game-maker-studio-2
---


title: Screen space camera rotation issue

text:
# Question
Title: Screen space camera rotation issue
I have a canvas on a camera set to it's screen space (not as a child of the camera)

I have my camera rotate on the y and x axises but whenever I move it on the x axis (up and down) the canvas doesn't follow it's rotation and is seen from a weird perspective from where the camera rotated.

On the y axis it works fine and follows the camera.

Anyone else had this issue?

# Answer
I just solved this in my project. My Canvas was a child of a camera in a FP Controller, which scale was not (1,1,1), but (1,0.8,1). The tilting of the GUI was then scaled, thus seemed to be tilting in a different angle.
> 0 votes

# Answer
I do not fully understand your issue, however, it may be because you are not scaling your Canvas.

You may want to try adding a Canvas Scaler component, and play around with the settings. Possibly set it to Scale with Screen Size, and then set the Match value to 0.5f.

If this is not helping, possibly try to provide an animated gif of your issue.
> -1 votes

---
Tags: unity, camera
---


# Question
Title: Replacing keycode by UI Buttons doesn't work
I have tried everything but it still doesn't work. I am not talking about implementing functions wich has stuff inside when you click the UI Button. I want literally replace this `Input.GetKeyDown(KeyCode.E)`. That is inside an if statement and replace with the UI Button object. How can i do this? I have tried with GetButton, GetButtonDown, trying to give a name and with Input.touchCount\>0

I am developing a game like Resident Evil old style and when you enter a triggerStay and push the button, a text is showing up.

**The Script**

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

public class readingNote : MonoBehaviour {

    public AudioSource audio;
    public AudioClip collectSound;
    public  bool playerNextToKey = false;
    bool hasCollided = false;
    public GameObject pic;
    public GameObject text;
    public GameObject notePad;

    public Button yourButton;

    void Start()
    {
        pic.SetActive(false);
        text.SetActive (false);
        Button btn = yourButton.GetComponent<Button>();
        btn.onClick.AddListener(TaskOnClick);
    }

    void TaskOnClick()
    {
/*THIS IS SHOWING ALL TEXT IN THE SCENE AND NOT ONE BY ONE WHEN PRESSING*/
//      text.SetActive (true);
//      pic.SetActive(true);
    }

    void OnTriggerStay ( Collider other) {

        if(other.gameObject.tag == "Player") {
            if(Input.GetKeyDown(KeyCode.E)) {
            //if(Input.touchCount>0) {
                text.SetActive (true);
                pic.SetActive(true);

                AudioSource.PlayClipAtPoint(collectSound, transform.position);

            }

        }
    }

    void  OnTriggerExit ( Collider other  )
    {
        if (other.gameObject.tag == "Player")
        {
            //enter = false;
            //print("close");

            playerNextToKey = false;
            hasCollided = false;
            pic.SetActive(false);
            text.SetActive (false);

        }
    }

}

```

# Answer
Simply add a boolean to indicate whether your player is "allowed" to press the button in order to activate your note :

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

public class readingNote : MonoBehaviour
{
    public AudioSource audio;
    public AudioClip collectSound;
    public  bool playerNextToKey = false;
    bool hasCollided = false;
    public GameObject pic;
    public GameObject text;
    public GameObject notePad;

    public Button yourButton;

    void Start()
    {
        pic.SetActive( false );
        text.SetActive( false );
        yourButton.onClick.AddListener( TaskOnClick );
    }

    void TaskOnClick()
    {
        if( !hasCollided )
            return ;

        text.SetActive( true );
        pic.SetActive( true );

        AudioSource.PlayClipAtPoint( collectSound, transform.position );
    }

    void OnTriggerStay( Collider other )
    {
        if ( other.CompareTag("Player") )
        {
            hasCollided = true ;
        }
    }

    void OnTriggerExit( Collider other )
    {
        if ( other.CompareTag("Player") )
        {
            playerNextToKey = false;
            hasCollided = false;
            pic.SetActive( false );
            text.SetActive( false );
        }
    }
}

```
> 2 votes

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


# Question
Title: How can I make my tank move smoothly and not jump from 0 km/h to 10 km/h?
I'm building a multiplayer game of tanks in node js. at the moment I have the movement smooth and mastered but my problem is that at them moment it's basically just unrealistic.

The tanks starts at 0 km/h but upon pressing `w`/`Arrow up` key it goes straight to 10 km/h, as you can imagine with any vehicle that's just unrealistic to do.

I want to know how to make that speed up happen without it being too bulky or confusing. I'm a beginner programmer so I'm not too informed in the world of programming. Can somebody help me with this?

I figured it would have to do with an acceleration command but I have no idea how to do that either.

# Answer
> 2 votes
Let's step away from programming for a second and just look at physics in one dimension. Say you have an object with an `x` coordinate. If you add 1 to this value every second, then your object will move at 1 units per second.

Now instead of 1, let's add `v` (for velocity). If `v` is 1, then you have the same behaviour as before. If you add 2 to `v` every second however (call 2 `a` for acceleration), then the object will keep moving faster and faster over time; aka accelerating, so 2 units per second per second (i.e. units/second²) is your acceleration. In calculus terms: the second derivative of position, or the first derivative of velocity (which is itself the first derivative of position).

So back to programming. You have an update loop that let's say runs 60 times per second. Instead of seconds, lets call our temporal units "ticks" (1/60 seconds). And instead of meters/units, let's call our spatial units "pixels".

Right now, you're adding a constant to your position `poxX` and `posY` based on some user input. Instead, if you add a variable to these, call them `velX` and `velY`, and modify *that* based on user input, you'll find that the speed of of your tanks ramps up or down based on how long you hold the keys, and when you let go, they move on forever. Now you don't exactly want that, so you need to simulate friction through "damping", e.g. `velX *= 0.9` every tick.

Then you can go one step further and add `accX` and `accY`, and set those to constant values when a key is pressed. From there it's just a matter of tweaking parameters to find the right balance.

---
Tags: movement
---


# Question
Title: OpenGL object movement is not smooth and vibrating
In my android NDK OpenGL C++ project, I have a render method which executes every frame on draw event so this is the algorithm:

```
void Engine::render() {
    deltaTime = GetCurrentTime() - lastFrame;
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    update();
    renderDepthMaps();
    renderMeshes();
    if (skybox != nullptr)
        shaders.drawSkyBox(skybox, camera, width, height);
    lastFrame = GetCurrentTime();
}

```

first I calculate the delta time between the last frame and the current frame, then I update all transformation and view matrices from input then render the scene so the game loop depends on the android draw frames, I have an object which moves over a terrain and a third person camera moves with it and rotates around it, so after the object moves for some distance it begins to flicker forward and backward, the update function for the object is:

```
double& delta = engine.getDeltaTime();
GLfloat velocity = delta * movementSpeed;
glm::vec3 t(glm::vec3(0, 0, 1) * velocity * 3.0f);
matrix = glm::translate(matrix, t);
glm::vec3 f(matrix[2][0], matrix[2][1], matrix[2][2]);
f = -glm::normalize(f) * velocity * 3.0f;
camera->translate(f);

```

If it is an interpolation issue I don't know how to make interpolation with using translate matrix to its forward vector.

# Answer
> -1 votes
the problem was in the shader precision once I set it to high it solve the problem

# Answer
> 0 votes
Try this:

```
F = glm:vec3(f[0], f[1], f[2] + velocity);

```

I am suggesting not to do normalization in code as down the graphics pipeline your transformed vertices will be normalized.

---
Tags: opengl, c++, android, interpolation, glm
---


# Question
Title: Unity: Shader Outlined/Uniform uses undefined Queue: 'Geometry + 1'
my outline shader was working fine but suddenly it started throwing this error. the game still works fine in the editor though but when i try to build it gets stuck on the step:

Packing assets - sharedassets0.assets

this is my shader:

```
Shader "Outlined/Uniform"
{
    Properties
    {
        _Color("Main Color", Color) = (0.5,0.5,0.5,1)
        _MainTex ("Texture", 2D) = "white" {}
        _OutlineColor ("Outline color", Color) = (0,0,0,1)
        _OutlineWidth ("Outlines width", Range (0.0, 2.0)) = 1.1
    }

    CGINCLUDE
    #include "UnityCG.cginc"

    struct appdata
    {
        float4 vertex : POSITION;
    };

    struct v2f
    {
        float4 pos : POSITION;
    };

    uniform float _OutlineWidth;
    uniform float4 _OutlineColor;
    uniform sampler2D _MainTex;
    uniform float4 _Color;

    ENDCG

    SubShader
    {
        Tags{ "Queue" = "Geometry + 1" "IgnoreProjector" = "True" }

        Pass //Outline
        {
            ZWrite Off
            Cull Front
            CGPROGRAM

            #pragma vertex vert
            #pragma fragment frag

            v2f vert(appdata v)
            {
                appdata original = v;
                v.vertex.xyz += _OutlineWidth * normalize(v.vertex.xyz);

                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                return o;

            }

            half4 frag(v2f i) : COLOR
            {
                return _OutlineColor;
            }

            ENDCG
        }

        Tags{ "Queue" = "Geometry"}

        CGPROGRAM
        #pragma surface surf Lambert

        struct Input {
            float2 uv_MainTex;
        };

        void surf (Input IN, inout SurfaceOutput o) {
            fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;
            o.Alpha = c.a;
        }
        ENDCG
    }
    Fallback "Diffuse"
}

```

i tried looking on the internet but couldn't get any help on this error.

# Answer
> 2 votes
Remove the spaces in `"Queue" = "Geometry + 1"`, it should look like `"Queue" = "Geometry+1"`

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


# Question
Title: How to change Unity's display settings/resolution?
Unity displays in poor quality on my computer (the software itself), I was wondering how to change resolution/display settings?

# Answer
> 4 votes
It appears that the resolution of your computer is higher than what Unity normally handles. To resolve this:

1. Find the `Unity.exe`, This is normally located at `C:\Program Files\Unity\Editor\Unity.exe`
2. Right click on the .exe and select `properties`.
3. Navigate to the compatibility tab, and check the box that says: `Override high DPI scaling behaviour`.
4. Select `scaling performed by application` from the dropdown.
5. Click `apply` and `ok`.

The next time Unity runs it will not be blurry.

# Answer
> 1 votes
Have you tried looking in the player options?

Edit \> Preferences \> Player Options

Usually there, are graphical options for every platform you are developing, maybe playing with those options you get many results

You can try increasing the quality of the textures too, but then, they will be very large

# Answer
> 0 votes
As you commented :

Everyone also have this problem , and the problem is come from the unity itself , for example :

* Resizing image / sprite scale make the image blur ( to prevent blur you must make your image in high definition so unity will make it not blur as long as possible )
* Resizing text , i sure this is your problem that the text is getting blurry , to fix text blur do this simple step :
* Click which text you want to stop - blur
* Change the font to 10000
* Change the **text scale ( Not Text Font ! )** as small as the text will show like what you want

This will need alot of try and work , also if this not answer you looking for , tell me i can delete this answer ;) .

---
Tags: unity, resolution
---


# Question
Title: How to change a Variable on an Instance of a Player with Network Manager?
So I am trying to change a variable on a player object by clicking a button using Unet. However, I am having trouble getting the instance of the player object. Is there a way to get the instance of a player from the Network Manager component? I can change the variable before the player connects but once they are connected I can no longer modify it.

Is there a way to do this?

I have a PlayerController script and all I basically want to do is change an integer on my player object based on a button press. I have tried referencing the gameObject attached to the script with `gameObject` and `this`. That doesn't seem to work and I have also tried `player.GetComponent<PlayerController>().myInt` and that doesn't seem to change it either.

All of these methods work until I connect as a Host or client and then it just doesn't do anything once I am connected.

# Answer
> 0 votes
I finally figured this out in the very depths of the terrible documentation that I could find.

`GameObject player = FindObjectOfType<NetworkManager>().client.connection.playerControllers[0].gameObject;`

---
Tags: unity, multiplayer, unet
---


# Question
Title: How can i use StartCoroutine to set the speed for each scaling step of the walls?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WallsTest : MonoBehaviour
{
    // using a GameObject rather than a transform
    public GameObject prefab;
    public Vector3 wallsStartPosition;
    public float width = 0;
    public float height = 1;
    public float length = 2;
    public Camera wallsCamera;

    void Start()
    {
        wallsCamera.transform.position = new Vector3(wallsStartPosition.x, wallsStartPosition.y + 100, wallsStartPosition.z - 235);

        StartCoroutine(BuildWalls());
    }

    IEnumerator BuildWalls()
    {
        for (int i = -2; i < 2; i++)
        {
            GameObject go = Instantiate(prefab);
            go.transform.parent = transform;
            Vector3 scale = Vector3.one;
            Vector3 adjustedPosition = wallsStartPosition;

            float sign = Mathf.Sign(i);
            if ((i * sign) % 2 == 0)
            {
                adjustedPosition.x += (length * sign) / 2;
                yield return new WaitForSeconds(0.1f);
                scale.x = width;
                scale.y = height;
                scale.z *= length + width;
            }
            else
            {
                adjustedPosition.z += (length * sign) / 2;
                scale.x *= length + width;
                scale.y = height;
                scale.z = width;
            }

            adjustedPosition.y += height / 2;
            go.transform.localScale = scale;
            go.transform.localPosition = adjustedPosition;
        }
    }
}

```

What it does now it's creating two walls at once it's just waiting 0.1 millisecond before creating them.

But instead i want it to show the scaling of the walls how they scaling and moving same for the else part for the adjustedPosition.z and not only the adjustedPosition.x

The problem is it's just waiting until it's placing the walls at once. I want to see the walls being building step by step like it's placing cube after cube.

# Answer
> 1 votes
I can't completely code it for you now but I give you an general example here which should be understandable hopefully to give you an idea how this works: (sorry for variable names will fix it later)

```
public IEnumerator Example()
{
     //Define start and goal transforms
     Vector3 currentPosition = Vehicle.transform.localPosition;
     Quaternion currentRotation = Vehicle.transform.localRotation;
     Vector3 currentScale = Vehicle.transform.localScale;

     Vector3 goalPostionTarget = _goalTransformVehicle.Position;
     Quaternion goalRotationTarget = _goalTransformVehicle.Rotation;
     Vector3 goalScaleTarget = _goalTransformVehicle.Scale;

     float timePassed = 0.0f;

     //With the TargetAnimationDuration define length of animation in sec
     float TargetAnimationDuration=1.5f;
     float fracTime = timePassed / TargetAnimationDuaration;

     while (fracTime < 1)
     {
         //Use Lerp to interpolate transforms over time
         Vehicle.transform.localPosition = Vector3.Lerp(currentPosition, goalPostionTarget, fracTime);
         Vehicle.transform.localRotation = Quaternion.Lerp(currentRotation, goalRotationTarget, fracTime);
         Vehicle.transform.localScale = Vector3.Lerp(currentScale, goalScaleTarget, fracTime);

         //Update fracTime
          timePassed += Time.deltaTime;
         fracTime = timePassed / TargetAnimationDuration;

         //Return so frame is rendered before going on
         yield return null;
     }

     //Finally set goal Transforms just to be sure
     Vehicle.transform.localPosition = goalPostionTarget;
     Vehicle.transform.localRotation = goalRotationTarget;
     Vehicle.transform.localScale = goalScaleTarget;
}

```

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


# Question
Title: How can i add spaces between gameobject when Instantiate?
```
void Update()
    {
        if (Input.anyKey)
        {
            foreach (Transform child in go.transform)
            {
                if (Input.inputString == child.name)
                {
                    Instantiate(child);
                }
            }
        }
    }

```

I want to Instantiate the gameobjects with a space between each one that i will set with public variable. And that the gameobjects position will start from the 0,0,0 of the terrain.

For example like that:

# Answer
The problem you're trying to solve just takes a little math and the definition of a few configuration variables.

```
Vector3 intialPosition = new Vector3(0,0,0); //The initial position you want to start at
Vector3 spacingOffset = new Vector3(0,1,0); //The desired space between GameObjects
int index = 2; //The n-th (from 0) GameObject in the line to place

//Gets the offset of size in the same axis as your spacing offset
Vector3 sizeOffset = this.gameObject.GetComponent<MeshRenderer>().bounds.size * spacingOffset.normalized;
//Computes the vector from initial position to n-th GameObject
//(spacingOffset * index) = contribution from spaces
//(sizeOffset * index) = contribution from the size of the GameObjects
//(spacingOffset * index) + (sizeOffset * index) simplifies to the below...
Vector3 vectorFromInitial = (spacingOffset + sizeOffset) * index;

//Final position is computed for n-th cube as follows
this.gameObject.transform.position = intialPosition + vectorFromInitial;

```

The only mysterious property might be `MeshRenderer.bounds.size` which is the size of your GameObjects mesh in world space. Everything else was just visualizing the problem and picking out the variables to put together to get the desired value.

Note that this breaks for a `spacingOffset` that is not axis aligned where it would be more appropritate to use a `BoundingSphere`. Also, if the objects are not all the same size or have different origins, this also breaks and requires more complex logic to get the size of each one individually.
> 1 votes

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


# Question
Title: Transform vertices in a line differently?
With a `GL_LINE`, is there a way to have the vertex (or geometry) shader treat the first and second point differently?

i.e. In a line from `p0` -\> `p1` I'd like to apply a different transform to `p0` than to `p1`.

I know how to do this with a computer shader, but I was wondering if there is a way to do it with a vertex/geometry shader.

# Answer
> 1 votes
If, in your case, you want to treat all even numbered vertices different from all odd numbered vertices, then you could use gl\_VertexID built in GLSL variable.

You could pass in two modelviewprojection matrices, one for type A and one for type B, and apply the one based on the least significant bit of gl\_VertexID.

```
if ( gl_VertexID & 1 ) ...

```

If there is no fixed pattern for which vertex number gets which treatment, then you just need to add an additional vertex attribute like DMGregory proposed.

If you don't want to do that, and if you are passing 4-float coordinates with x,y,z,w you could even encode the special treatment in 'w', and reset it to '1' after detecting the special case. (Or even hack in a large offset in x to signal this. But that's the ugliest option.)

---
Tags: opengl, geometry-shader, vertex-shader
---


title: Group path following

text:
# Question
Title: Group path following
A path is defined as a list of positions for units to follow sequentially to navigate terrain. For example,

```
var Path = new List<Vector2> (){
    new Vector2 (0,0),
    new Vector2 (10,5),
    new Vector2 (20,5)
};

```

Conceptually, how would a group of 10 clumped-up units navigate to each of the waypoints? When each unit checks its distance to the waypoint to decide whether or not to move on to the next waypoint, units may start running into each other, trying to occupy the same waypoint.

Are there any clearcut solutions for group path following or ideas for how to solve it?

# Answer
> 1 votes
For 10 units I would probably use some hack where I would adjust the tolerance for hitting waypoints. The denser the crowd, the more lax with hitting waypoints. Not the cleanest, and not necessarily a robust solution, but it may suffice, so it's worth trying.

For large crowds, look into Continuum Crowds.

This method solves the path to the goal not for a specific source to a specific goal. Instead it computes the path (in the form of a gradient field) for every location on the map, to a goal.

This is of course computationally expensive, but if crowd sizes get really large, and many in the crowd share a common goal, then that extra cost is amortized, and you pretty much get larger crowds essentially for free.

I've used it myself, and the results are very impressive. The agents will avoid bottlenecks, take alternate routes, and will even automatically form lanes if two groups (with different goals) travel in opposite directions.

If in your case, you want the group to always stay together, then a flow field approach like Continuum Crowds may not be the best, as it would not guarantee this.

---
Tags: ai, path-finding, rts, steering-behaviors
---


# Question
Title: Projectile Aim Prediction with Acceleration
I'm trying to solve the classic shoot moving object problem but with acceleration attached to that changes it from a quadratic to quartic formula but my math skills are not this good sadly as i prefer to speak in code and not formulas.

i found this https://wiki.beyondunreal.com/Legacy:Projectile\_Aiming. i ported it and it's almost what i'm looking for but missing control over the acceleration as its only made for gravity or no gravity and even this i got working only with tricks and modifying it without knowing what i'm doing is getting me only that far.

I made myself a Prototype Interface for the minimum of what i'm trying to get out of it

```
public class PredictionResult {
    public bool IsInRange; // can we even hit the target?
    public Vector3[] ShotVelocity; // should be up to 4 possible values
    public float[] ShotImpactTime; // how long each shot takes to arrive at the predicted target
    public Vector3[] ShotImpactLocation; // somewhat redundant yet still useful if available
}
// only really the delta between start and target matter but its up to the function
// same for startVel and targetVel where startVel is the shooters speed that gets added to the bullet
// the bullet and target can have different accelerations (standing on ground => no gravity or bullet is not affect by gravity)
public PredictionResult ShootAtTarget(Vector3 start, Vector3 target, Vector3 startVel, Vector3 targetVel, Vector3 bulletAccel, Vector3 targetAccel, float bulletSpeed);

```

any help solving this would be great

# Answer
To make things a little simpler, let's work within the inertial frame of our launcher. That means our projectile will be firing from the point (0, 0, 0).

(You can subtract any arbitrary firing position from the target position to get this state of affairs for the purpose of the calculations, then add it back when you need to work with the resulting path)

Let's define:

**unknowns**

* `v_p` the launch velocity of our projectile relative to the launcher (vector)
* `t` the time after launch when our projectile impacts the target (scalar)

**knowns**

* `s` the speed of our projectile (scalar)
* `p_T` the offset from the launcher to the target at the time of firing (vector)
* `v_T` the velocity of the target relative to the launcher at the time of firing (vector)
* `a_T` the constant acceleration of the target (vector)
* `a_p` the constant acceleration of the projectile (vector)

Using our parametric equation for motion over time under constant acceleration...

```
p(t) = p(0) + v * t + (a/2.0) * t^2

```

We know that at the time of impact we want:

```
v_p * t + (a_p/2.0) * t^2 = p_T + v_T * t + (a_T/2.0) * t^2

```

Rearranging to isolate `v_p`, we get:

```
v_p = (1/t)(t^2(a_T - a_p)/2.0 + t * v_T + p_T)

```

Let's define `a = a_T - a_p` since they'll appear paired from here on in.

Applying our speed constraint: (Here · refers to a dot product between vectors)

```
s = ||v_p||

s^2 = v_p·v_p
s^2 = (1/t^2)(t^4(a·a/4.0) + t^3(a·v_t) + t^2(a·p_T + v_T·v_T) + t(2.0 * v_T·p_T) + p_T·p_T)

```

Rearranging:

```
  t^4 * (a·a/4.0)
+ t^3 * (a·v_T)
+ t^2 * (a·p_T + v_T·v_T - s^2)
+ t   * (2.0 * v_T·p_T)
+       p_T·p_T
= 0

```

That's a quartic equation in `t`, which is not the most fun to solve. When the target is stationary, the `t^3` and `t` terms vanish and we can use quadratic formula to solve for `t^2`, but for the general case of a moving target there's not much we can do but bite the bullet.

You can either plug this into a math library to solve the polynomial, write your own polynomial solver, or approximate a solution using an iterative method like Newton's.

However you choose to go about it, you'll come out with up to 4 time values at which you can successfully intercept the target. Some could be negative, corresponding to projectiles being lobbed *from the target* sometime in the *past* to arrive at the firing position at time zero travelling at the desired speed - discard those and consider only the positive time values. (You might get none, if the target is simply out of firing range or moving too fast to intercept)

To turn any of these remaining valid time values into a launch velocity, do the following:

1. Plug your `t` value into the formula for the target's position

`p(t) = p_T + v_T * t + (a_T/2.0) * t^2`

This gives you the position of the target at the time of impact. Since this is the net offset in space that your projectile will have to bridge, we'll call this vector `travel`
2. Calculate the initial velocity (aim direction & speed) of an arc travelling to this point in space & time:

`v_p = travel / t - (a_p/2.0) * t`

By construction, launching the projectile with this velocity `v_p` will intersect the target's movement while respecting the initial speed constraint we started with, to within the numerical accuracy of the operations we took to get here. (Some rounding can be introduced at each step)

Here's an animation of this formula at work:

This little test rig generates random target positions/velocities/accelerations and projectile gravity values, then calculates up to four intercept trajectories.

The white ball is the target, moving along its trajectory before t=0 (black curve) to its position at the time of firing (grey dot) and continuing along its future trajectory t \> 0 (grey curve). Its path is marked by red dots at the solution points.

The intercepting projectiles and their trajectories appear in cyan & green at t = 0 and arc to intercept the target at their corresponding impact times.

For completeness, I also show the negative solutions if there are any, in yellow or magenta, firing from the target when it crosses a negative solution time and arriving at the firing point in the center at t = 0.
> 12 votes

# Answer
You mention "a rifle firing at an accelerating car."

Note that the rifle's bullet has its maximum speed at the nozzle, and will only slow down from there, in real-life.

For simplicity, I will assume that the bullet will not noticeably slow down before hitting the car: most games don't even model air-resistance for bullets.

So the acceleration to compensate for, is the car's, and not the bullet's. Correct?

So the travel time for the bullet to where the car currently is, is easily determined.

What the car does during that travel time (dt), will impact the aim of the rifle, but hardly that travel time itself.

So in my games, I neglect the difference with the actual travel time it takes to the car at time of impact.

Then your aiming problem simply comes down to predicting the car's position at t + dt.

This prediction requires the car's current position, current velocity and current acceleration.

I would add some additional simplifications to this problem, which probably have little impact in accuracy: You calculate the car's speed at t+dt, and then assume on average, the speed of the car between firing and impact lies half-way between the car's current speed and the predicted speed. With that, you can estimate the car's position at t+dt.

In pseudo code I would do:

```
traveltime = distance_to_car / bullet_nozzle_velocity
current_speed = car.speed
predicted_speed = car.speed + traveltime * car.acceleration
average_speed = ( current_speed + predicted_speed ) / 2
predicted_pos = car.pos + average_speed * traveltime

```
> 0 votes

---
Tags: c#, mathematics, projectile-physics, trajectory, aiming
---


# Question
Title: Transparent parts of texture are opaque black instead
I render a sprite twice, one on top of the other. The sprites have transparent parts, so I should be able to see the bottom sprite under the top sprite. The transparent parts are black (the clear colour) and opaque instead though and the topmost sprite blocks the bottom sprite.

My fragment shader is trivial:

```
uniform sampler2D texture;
varying vec2 f_texcoord;
void main()
{
    gl_FragColor = texture2D(texture, f_texcoord);
}

```

I have `glEnable(GL_BLEND)` and `glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)` in my initialization code. My texture comes from a PNG file that I load with libpng. I'm sure to use `GL_RGBA` when initializing the texture with `glTexImage2D` (otherwise the sprites look like noise).

**Edit:** Here's a screenshot.

# Answer
> 7 votes
What do you get if you try and swap the order you draw them in?

Transparent pixels still create depth buffer entries. If you're drawing the back one after the first it's not processing the pixels behind the front image, making it look like there's no alpha.

For reference, take a look at the Painter's alogrithm.

# Answer
> 1 votes
I don't think your textures have the desired alpha inside them, so calling `gl_FragColor = texture2D(texture, f_texcoord)` won't generate any transparent fragments. You should pass the alpha through as a varying from the vertex program to the fragment program if you want transparency.

**EDIT:** Teodron suggestion writing the following code to verify that alpha information is getting passed to the shaders (this is in the fragment shader and color is a varying which is assigned in the vertex program). `vec4 color = texture2D(texture, f_texcoord); if (color.w < 1) gl_FragColor = vec4(1,0,0,1); else gl_FragColor = vec4(0,1,0,1);`

# Answer
> 0 votes
If you know that those pixels have zero alpha and you want to discard them, a trivial solution is:

```
if (color.a <= 0.0) {
    discard;
}

```

There are better options probably, but this does work. There is no claim that this is good for performance on my behalf however.

---
Tags: opengl, textures, transparency
---


# Question
Title: Why are Monogame models tied to effects?
When I load a model in Monogame using `ContentManager`, the model contains effects on each mesh (`mesh.Effects`). This is confusing to me since models seem to be directly tied to their rendering, rather than existing as standalone 3D models. Further, this makes applying custom effects more difficult in code, since I have loop through each `ModelMeshPart` and assign effects. The comparison to 2D would be a `Texture2D` containing its own `SpriteBatch` settings, which wouldn't make sense. Why are models tied to effects, and how can I separate them?

# Answer
I believe this is is mainly for greater flexibility with model's materials (over just textures) and is derived from the FBX standard which allows for effects in this manner.

Also, remember that effects tell the GPU how to render a specific piece of geometry, SpriteBatch is a tool for batching GPU calls.

That said, this is probably not a feature you want in your games (You'll probably want unified effects and effect batching), so you should probably write your own Draw calls
> 1 votes

---
Tags: 3d, shaders, monogame, models
---


# Question
Title: Unity: Import a mesh that only has vertex and edge data but no faces
I am working on a game that requires meshes that only have edges and vertices but no faces. In blender, you can make a mesh with only edges and vertices, but if you export it to FBX or OBJ, once it is imported into Unity, the resulting prefab has no mesh data linked to it. The prefab has no MeshFilter. It's as if I imported an mesh with absolutely no mesh data.

For example, if I create a plane in Blender and then delete the face but leave the edges and vertices, and then export as OBJ, I can open the OBJ in a file editor. This is a square with no faces:

```
# Blender v2.78 (sub 0) OBJ File: ''
# www.blender.org
mtllib egdes.mtl
o Plane
v -1.000000 0.000000 1.000000
v 1.000000 0.000000 1.000000
v -1.000000 0.000000 -1.000000
v 1.000000 0.000000 -1.000000
l 3 1
l 1 2
l 2 4
l 4 3

```

So it appears that OBJ actually does export with the correct mesh data, however, it seems that Unity does not know how to import an OBJ if there are no faces.

Does anyone know if anyone has come up with a solution to this problem yet? If not, I guess I'll just have to write my own parser. If that's the case, does anyone know if there is a way to extend or override Unity's built-in OBJ parser?

# Answer
> 2 votes
With Tim R.'s help, I implemented a custom importer to address this problem. You can get the code here:

https://github.com/taylorgoolsby/lineobj-importer

# Answer
> 4 votes
First of all can I say I've never encountered by total chance someone encountering such an incredibly specific issue that I also encountered, so good job on that, universe.

So as you've already discovered, Unity's model importers discard all edges and points.

I haven't completely solved this problem myself for a similar project, but I have a partial workaround and an alternate solution you could try.

The stuff I was working on only applied to edges, but all of this can be extended to point meshes as well.

# My workaround

My workaround I used in my experimental project recently: In Blender, before exporting my edges mesh to FBX, I add a Screw modifier and I enter 0 in all the text fields (screw, angle, steps, render step). Some of the values round up to 2. This creates two quads for each edge in the mesh, but they're all degenerate quads with two identical edges and two 0-length edges. I give the mesh object a name with "lines" in it, to identify it and tell it apart from normal meshes in the asset processing.

In Unity, I have a class LinesMesh that extends AssetPostProcessor. It disables welding vertices on the import settings to prevent the degenerate polygons from being removed by the model importer. After the mesh is processed, I recursively iterate over the transforms in the processed model to find any meshes with "lines" in their name. I change the topology to lines, and create new line indices based on the triangle indices.

I haven't done the work of collapsing all the duplicated verts down, so with this method you'll get 12 lines when all you needed/wanted was 1. This code is obviously really unfinished on that count. But, it preserves all per-vertex data like if you somehow managed to assign vertex colors and UVs to your edges in your 3D program.

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

public class LinesMesh : AssetPostprocessor
{
    void OnPreprocessModel()
    {
        ModelImporter modelImporter = (ModelImporter)assetImporter;
        modelImporter.weldVertices = false;
        //modelImporter.addCollider = false;
    }

    void OnPostprocessModel(GameObject g)
    {
        Apply(g.transform);
    }

    void Apply(Transform t)
    {
        if (t.name.ToLower().Contains("lines") && t.GetComponent<MeshFilter>())
        {
            Mesh mesh = t.GetComponent<MeshFilter>().sharedMesh;
            if (mesh)
            {
                // Toooons of duplicated and degenerate lines in this method. investigate optimizations.
                for (int submesh = 0; submesh < mesh.subMeshCount; submesh++)
                {
                    if (mesh.GetTopology(submesh) == MeshTopology.Triangles)
                    {
                        int[] triIndices = mesh.GetIndices(submesh);
                        int[] lineIndices = new int[triIndices.Length * 2];
                        for (int tri = 0; tri < triIndices.Length; tri += 3)
                        {
                            lineIndices[tri * 2] = triIndices[tri];
                            lineIndices[tri * 2 + 1] = triIndices[tri + 1];
                            lineIndices[tri * 2 + 2] = triIndices[tri + 1];
                            lineIndices[tri * 2 + 3] = triIndices[tri + 2];
                            lineIndices[tri * 2 + 4] = triIndices[tri + 2];
                            lineIndices[tri * 2 + 5] = triIndices[tri];
                        }

                        mesh.SetIndices(lineIndices, MeshTopology.Lines, submesh);
                    }
                    else
                    {
                        Debug.LogErrorFormat("Unhandled mesh topology ({0}) in mesh {1}", mesh.GetTopology(submesh), mesh.name);
                    }
                }
            }
            else
            {
                Debug.LogWarningFormat("Failed to get mesh for object {0}", t.name);
            }
        }

        // Recurse
        foreach (Transform child in t)
            Apply(child);
    }
}

```

The above code should work on any mesh, not just line-like polygonal meshes, and turn them into a wireframe mesh, with about 2x the optimal number of lines.

# But maybe don't use that stuff

You could make it work with more tweaks on top of the above kludge to get rid of the duplicated edges, but the extra steps in Blender of adding the modifiers, naming objects and such adds a lot of work to each mesh you need to import. If you don't care about performance at all, you could even use the above code as-is, and just ignore that you're sending 2-3 times as much vertex data to the GPU and 6-12 times as many edges than you need.

What I would suggest instead is renaming the exported model's file extension to something that Unity won't process as a model, something like `mymodel.linesobj`. Then you have to produce a mesh by parsing the file yourself, since Unity doesn't give you the power to hook into the importer during the import process.

You can reference the above code for how to create a meshpart with lines topology, it should be way easier than what I did if you're parsing the obj file yourself.

# The legacy way of writing custom importers:

In an asset postprocessor, you can use `OnPostProcessAllAssets` to detect when a .linesobj file finished importing, and write your own OBJ parser to produce a new model with meshes with Lines topology similar to above. Then you can call `AssetDatabase.CreateAsset` with the model to create a .asset file containing the model generated by your custom obj processor.

# The currently experimental way to write custom importers in new versions of Unity

This is marked as experimental currently, but if this API gets completed it should be a much less janky way of custom asset processing: https://docs.unity3d.com/Manual/ScriptedImporters.html

If you do end up writing a custom importer or fixing up the mesh data, I would appreciate if you posted it here as its own answer, as I would like to revisit my project and fix the excessive geometry and tedious blender export process.

---
Tags: unity, blender, obj
---


# Question
Title: How to make sure that the set of randomly spawning obstacles is passable?
## Prompt

Suppose we have a little mini-game where you have to avoid incoming obstacles by moving the blob up and down at a constant speed. The blob's x coordinate is fixed and the obstacles will spawn from the right edge of the screen.

The obstacles may vary in size, speed, starting height, spawn interval, angle, etc. (they can overlap). But let us work with just varying height and speed for now. My question is:
If I were to generate the next obstacle with randomised starting height and speed, how can I make sure that the player can still avoid everything?

## Example

In the image above, suppose the blob's speed is enough to move him up towards the gap near the top before the obstacles reach his x coordinate, but he's not fast enough to reach the bottom gap in time. So given the current set of obstacles, the blob should move himself towards that gap (possibly with a bit of leeway before the obstacles will actually reach him).

Now consider the next obstacle spawning at the same height as the gap.
This is fine since the blob can still move up or down immediately after getting through the first set of obstacles. But suppose we are unlucky and the random difficulty setting makes it so that the new obstacle is twice as fast and will reach the blob's x coordinate at the same time as the first set of obstacles. Then the whole set of obstacles is regarded as impassable with respect to the blob's current position.
In particular, how can we determine that the first case is OK while the second is not?

## Attempt

Intuitively, I am imagining a "live zone" that updates itself as the obstacles move. The live zone defines a (set of) range along the blob's vertical axis in which he can be in at any given point in time in order to make sure that he can avoid the obstacles. By definition, blob **must always remain within the zone, otherwise, we will hit an obstacle no matter what**. In a sense, the live zone "zooms in" on spaces without an obstacle.

In the above example, we have 2 zones near the top and bottom gaps.

* The zone narrows as the obstacles approach the blob. The narrowing rate depends the relevant obstacles' speeds.
* The fact that blob cannot reach the bottom gap in time can be demonstrated with him having to leave the zone he's in.

Let's call part of the live zone that blob is in an "active zone". The goal is then to make sure that the active zone is always non-empty and that it is always possible for blob to stay within that zone. If a new obstacle removes the active zone, we can stop it and let it pick a different settings for the new obstacle. But how would I go about implementing this or is this approach feasible in the first place?

* Some parametrisation of the obstacle's position based on time or their x coordinate?
* If we squash the x axis into just a line corresponding to blob's x coordinate, then the live zone is just the complement of the union of all the obstacles.
* What if there really is no next valid obstacle? No, this cannot be the case since we can just repeat the last spawned obstacle, provided we started with a non-empty active zone.

# Answer
> 4 votes
If the blob has a constant vertical speed, and you know the horizontal speed of the incomming objects, you can use those variables to calculate the minimum and maximum angles the blob can travel to at most in that time frame.

If you then calculate the distance between every two waves of obstacles, you can use that to find an angle that the player can actually travel to in time.

Hopefully this helps

---
Tags: game-design, game-mechanics, procedural-generation, random, spawning
---


title: Libgdx 2d floor Animation

text:
# Question
Title: Libgdx 2d floor Animation
I'm building Runner Game. Ground Class.

```
public class Ground extends Actor {

private Texture texture;
private ArrayList<Vector2> groundLocations;
private float speed;
private float cameraLeft, cameraRight;
private int textureWidth;

public Ground() {
    this.cameraRight = Const.GAME_WIDTH + Const.GAME_MARGIN;
    this.cameraLeft = 0 - Const.GAME_MARGIN;
    texture = new Texture(Gdx.files.internal("ui/ground.png"));
    groundLocations = new ArrayList<Vector2>();
    init();
}

public void setSpeed(float speed) {
    this.speed = speed;
}

private void init() {

    textureWidth = texture.getWidth();
    float currentPosition = cameraLeft;
    while (currentPosition < cameraRight) {

        Vector2 newLocation = new Vector2(currentPosition, 0);
        groundLocations.add(newLocation);
        currentPosition += textureWidth;
    }

}

public int getFloorHeight() {
    return texture.getHeight();
}

@Override
public void act(float delta) {
    super.act(delta);
    int size = groundLocations.size();

    for (int i = 0; i < size; i++) {
        Vector2 location = groundLocations.get(i);
        location.x -= delta * speed;
        if (location.x < cameraLeft) {

            location.x = findMax().x + textureWidth;
        }
    }

}

private Vector2 findMax() {
    return Collections.max(groundLocations, new Vector2Comparator());
}

@Override
public void draw(Batch batch, float parentAlpha) {
    super.draw(batch, parentAlpha);
    for (Vector2 location : groundLocations) {
        batch.draw(texture, location.x, location.y);
    }
}

public void dispose() {
    if (texture != null)
        texture.dispose();
}

```

}

* Ground Texture is 128x128
* GAME\_WIDTH = 1024f
* GAME\_MARGIN = 250f
* speed = changes.

While the ground is moving according to Speed and FPS. (Speed * delta) Problem is : There are always Gaps between ground Textures. after certain Movement function findMax finds the texture with the biggest X any help would be Appreciated.

Solution:

```
  for (int i = 0; i < size; i++) {
        Vector2 location = groundLocations.get(i);
        if (location.x < cameraLeft) {
            location.x = findMax().x + textureWidth;
        }
        location.x -= delta * speed;
    }

```

# Answer
If I understand correctly you are getting gaps between the textures.

This is usually caused by floating point rounding errors and can usually be solved by using a texture packer to pack your images with padding.

Another possible fix is to change your texture filtering to NEAREST which basically uses the pixel nearest the point supplied.

Another possible fix is to limit your camera to INT positions which will remove floating point rounding all together.
> 0 votes

---
Tags: libgdx
---


title: Unexpected ScriptableObject Behaviour

text:
# Question
Title: Unexpected ScriptableObject Behaviour
I am currently working on a game which should be your basic RPG style and in this game I am using an Ability system based on ScriptableObjects. Each Ability has its own ParticleSystem (prefab) and AudioSource.

Basically all Ability.asset files are added to a list of Abilities. Using PageUp/Down buttons the player equips the next/previous Ability of the List.

When "Fire1" is pressed the ability is then cast which works just fine before equipping the next Ability. Then, no matter how many times I press "Fire1" no Ability is cast unless I click out of game-view and inside of it again. However in the Inspector everything seems OK.

Here's my code:

```
void Update ()
{
    abilityCount = AbilitySystem.Instance.allAbilities.Count - 1;
    abilityCooldown -= Time.deltaTime;
    if(Input.GetButtonDown("Fire1") && abilityCooldown <= 0f)
    {
        Shoot();
        abilityCooldown = 1f / castingSpeed;
    }

    if (Input.GetKeyDown(KeyCode.PageDown))
    {
        abilityIndex--;
        if (abilityIndex < 0)
        {
            abilityIndex = abilityCount;
        }
        currentAbility = AbilitySystem.Instance.allAbilities[abilityIndex];
        UpdateAbilityStats();
    }

    if (Input.GetKeyDown(KeyCode.PageUp))
    {
        abilityIndex++;
        if (abilityIndex > abilityCount)
        {
            abilityIndex = 0;
        }
        currentAbility = AbilitySystem.Instance.allAbilities[abilityIndex];
        UpdateAbilityStats();
    }

}

void UpdateAbilityStats()
{
    abilityDamage = currentAbility.abilityDamage;
    abilityRange = currentAbility.abilityRange;
    abilityCooldown = currentAbility.abilityCooldown;
    particles = currentAbility.Particles;
    particlesOnTarget = currentAbility.onTargetParticles;
}

```

# Answer
castingSpeed for some ability is 0f and abilityCooldown becomes float.PositiveInfinity, then no matter what you subtract to that, it will never become \<= 0 so the if condition is never satisfied.
> 1 votes

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


# Question
Title: How do RPG games like Titan Quest, Diablo, WoW or similiar ones handle XP distribution?
For my own game I'd like to know if any of you have an idea about how some popular RPG games handle XP distribution? What I'd be particularly interested in is how the amount of XP a certain enemy gives the player after it's defeat is determined.

For my game I'm struggling to find a proper algorithm/formular to determine that specific amount, since it's a rather small game with not that many enemies types it might be okay to set a value for each enemy type by hand. At first I was experimenting with a formular which takes certain stats of an enemy and then calculates the amount of XP the enemy is 'worth' but as I already said I could not achieve a satisfying result by this.

Nonetheless it would be interesting to know how large games handle this determination. I'd assume that it's not done by hand because you have too many different enemies but I also might be wrong. If anyone could give me any insights or good reads on this I'd be very thankful.

Another thing I'd be interested in is how the XP gaining for the player with a level difference is handled. For instance: If the player is 10 levels ahead of an enemy he should gain 100% less XP from that enemy. If he is 5 levels ahead he only should get 50%. Of course that's a bit depended on my game and the entire design but would that be a common approach to deal with farming low level enemies and still gaining full XP from that? Or are there other approaches such games usually use?

Thanks for any hints, comments and opinions!

# Answer
In Borderlands 2 and Borderlands: The Pre-Sequel, each enemy has their own level (up to 50) and the number of XP available is fixed and calculated on a percentage of the level of the player.

This means that a player who somehow manages to kill an enemy much higher than themselves gains a massive amount of XP but those who go back to earlier enemies get zero for farming lower levels.

In my head, I'd always worked this out based on what level the player should be when completing the mission, it should give a reasonable XP reward.

This is where your algorithm comes in. Fix the level and total XP available and calculate it against the level of the player.
> 2 votes

---
Tags: game-design
---


# Question
Title: When should I use a fixed or variable time step?
Should a game loop be based on fixed or variable time steps? Is one always superior, or does the right choice vary by game?

# Variable time step

Physics updates are passed a "time elapsed since last update" argument and are hence framerate-dependent. This may mean doing calculations as `position += distancePerSecond * timeElapsed`.

*Pros*: smooth, easier to to code
*Cons*: non-deterministic, unpredictable at very small or large steps

deWiTTERS example:

```
while( game_is_running ) {
    prev_frame_tick = curr_frame_tick;
    curr_frame_tick = GetTickCount();
    update( curr_frame_tick - prev_frame_tick );
    render();
}

```

# Fixed time step

Updates might not even accept a "time elapsed", as they assume each update is for a fixed time period. Calculations may be done as `position += distancePerUpdate`. The example includes an interpolation during render.

*Pros*: predictable, deterministic (easier to network sync?), clearer calculation code
*Cons*: not synced to monitor v-sync (causes jittery graphics unless you interpolate), limited max frame rate (unless you interpolate), hard to work within frameworks that assume variable time steps (like Pyglet or Flixel)

deWiTTERS example:

```
while( game_is_running ) {
    while( GetTickCount() > next_game_tick ) {
        update();
        next_game_tick += SKIP_TICKS;
    }
    interpolation = float( GetTickCount() + SKIP_TICKS - next_game_tick )
                    / float( SKIP_TICKS );
    render( interpolation );
}

```

# Some resources

# Answer
There are two issues related to the question.

* Should physics step rate be tied to frame rate?
* Should physics be stepped with constant deltas?

In Glen fielder's Fix your time step he says to "Free the Physics". That means your physics update rate should **not** be tied to your frame rate.

> For example, if the display framerate is 50fps and the simulation is designed to run at 100fps then we need to take two physics steps every display update to keep the physics in sync.

In Erin Catto's recommendations for Box2D he advocates this as well.

> So don't tie the time step to your frame rate (unless you really, really have to).

*Should Physics step rate be tied to your frame rate?* No.

---

Erin's thoughts on fixed step vs variable stepping:

> Box2D uses a computational algorithm called an integrator. Integrators simulate the physics equations at discrete points of time. ... We also don't like the time step to change much. A variable time step produces variable results, which makes it difficult to debug.

Glen's thoughts on fixed vs variable stepping:

> ### Fix your timestep or explode
>
> ... If you have a series of really stiff spring constraints for shock absorbers in a car simulation then tiny changes in dt can actually make the simulation explode. ...

*Should physics be stepped with constant deltas?* Yes.

---

The way to step the physics with constant deltas and not tie your physics update rate to the frame rate still is to use a time accumulator. In my game I take it a step further. I apply a smoothing function to incoming time. That way large FPS spikes don't cause the physics to jump too far, instead they're simulated more quickly for a frame or two.

You mention that with a fixed rate, the physics wouldn't sync up with the display. This is true if the target physics rate is near the target frame rate. It's worse the frame rate is larger than the physics rate. In general it is better to target a physics update rate of twice your target FPS, if you can afford it.

If you can't afford a large physics update rate, consider interpolating the graphics' positions between frames to make the drawn graphics appear to move more smoothly than the physics actually moves.
> 143 votes

# Answer
I think there are really 3 options, but you're listing them as only 2:

**Option 1**

Do nothing. Attempt to update and render at a certain interval, e.g. 60 times per second. If it falls behind, let it and don't worry. The games will slow down into jerky slow motion if the CPU can't keep up with your game. This option won't work at all for real-time multi-user games, but is fine for single player games and has been used successfully in many games.

**Option 2**

Use the delta time between each update to vary the movement of objects. Great in theory, especially if nothing in your game accelerates or decelerates, but just moves at a constant speed. In practice, many developers implement this badly, and it can lead to inconsistent collision detection and physics. It seems some developers think this method is easier than it is. If you want to use this option you need to step your game up considerably and bring out some big-gun maths and algorithms, for example using a Verlet physics integrator (rather than the standard Euler that most people use) and using rays for collision detection rather than simple Pythagoras distance checks. I asked a question about this on Stack Overflow a while back and got some great answers:

https://stackoverflow.com/questions/153507/calculate-the-position-of-an-accelerating-body-after-a-certain-time

**Option 3**

Use Gaffer's "fix your time step" approach. Update the game in fixed steps as in option 1, but do so multiple times per frame rendered - based on how much time has elapsed - so that the game logic keeps up with real time, while remaining in discrete steps. This way, easy to implement game logic like Euler integrators and simple collision detection still work. You also have the option of interpolating graphical animations based on delta time, but this is only for visual effects, and nothing that affects your core game logic. You can potentially get in trouble if your updates are very intensive - if the updates fall behind, you will need more and more of them to keep up, potential making your game even less responsive.

Personally, I like Option 1 when I can get away with it and Option 3 when I need to sync to real time. I respect that Option 2 can be a good option when you know what you're doing, but I know my limitations well enough to stay well away from it.
> 63 votes

# Answer
I really like the way the XNA Framework implements fixed time step. If a given draw call takes a bit too long, it will call update repeatedly until it "catches up". Shawn Hargreaves describes it here:
http://blogs.msdn.com/b/shawnhar/archive/2007/11/23/game-timing-in-xna-game-studio-2-0.aspx

> In 2.0, the Draw behavior has changed:
>
> * Call Update as many times as needed to catch up to the current time
> * Call Draw once
> * Wait until it is time for the next Update

The biggest pro in my opinion to this is one that you mentioned, that it makes all of your game code calculations so much simpler because you don't have to include that time variable all over the place.

*note: xna supports variable timestep as well, it's just a setting.*
> 25 votes

# Answer
There's another option - decouple Game update and physics update. Trying to tailor the physics engine to the game timestep leads to problem if you fix your timestep (the problem of spinning out of control because integration needs more timesteps which take more time which needs more timesteps), or make it variable and get wonky physics.

The solution that I see a lot is to have the physics run on a fixed timestep, in a different thread (on a different core). The game interpolates or extrapolates given the two most recent valid frames it can grab. Interpolation adds some lag, extrapolation adds some uncertainty, but your physics will be stable and not spin your timestep out of control.

This is not trivial to implement, but might prove itself future proof.
> 12 votes

# Answer
Personally, I use a variation of variable time-step (which is sort of a hybrid of fixed and variable I think). I stress tested this timing system in several ways, and I find myself using it for many projects. Do I recommend it for everything? Probably not.

My game loops calculate the amount of frames to update by (let's call this F), and then perform F discrete logic updates. Every logic update assumes a constant unit of time (which is often 1/100th of a second in my games). Each update is performed in sequence until all F discrete logic updates are performed.

Why discrete updates in logic steps? Well, if you try and use continuous steps, and suddenly you have physics glitches because the calculated speeds and distances to travel are multiplied by a huge value of F.

A poor implementation of this would just do F = current time - last frame time updates. But if calculations get too far behind (sometimes due to circumstances beyond your control like another process stealing CPU time), you will quickly see awful skipping. Quickly, that stable FPS you tried to maintain becomes SPF.

In my game, I allow "smooth" (sort of) slowdown to restrict the amount of logic catchup that should be possible between two draws. I do this by clamping: F = min(F, MAX\_FRAME\_DELTA) which usually has MAX\_FRAME\_DELTA = 2/100 * s or 3/100 * s. So instead of skipping frames when too far behind game logic, discard any massive frame loss (which slows things down), recover a few frames, draw, and try again.

By doing this, I also make sure that the player controls keep in closer sync with what is actually shown on the screen.

Final product pseudocode is something like this (delta is F mentioned earlier):

```
// Assume timers have 1/100 s resolution
const MAX_FRAME_DELTA = 2
// Calculate frame gap.
var delta = current time - last frame time
// Clamp.
delta = min(delta, MAX_FRAME_RATE)
// Update in discrete steps
for(i = 0; i < delta; i++)
{
    update single step()
}
// Caught up again, draw.
render()

```

This sort of updating is not suitable for everything, but for arcade style games, I would much rather see the game slow down because there is a lot of stuff going on than miss frames and lose player control. I also prefer this to other variable-time step approaches which end up having irreproducible glitches caused by frame loss.
> 8 votes

# Answer
This solution doesn't apply to everything, but there is another level of variable timestep -- variable timestep for each object in the world.

This seems complicated, and it can be, but think of it as modeling your game as a discrete event simulation. Each player movement can be represented as an event which starts when the motion starts, and ends when the motion ends. If there is any interaction that requires the event be split (a collision for instance) the event is canceled and another event pushed onto the event queue (which is probably a priority queue sorted by event end time).

Rendering is totally detached from the event queue. The display engine interpolates points between event start/end times as necessary, and can be as accurate or as sloppy in this estimate as need be.

To see a complex implementation of this model, see the space simulator EXOFLIGHT. It uses a different execution model from most flight simulators -- an event-based model, rather than the traditional fixed time-slice model. The basic main loop of this type of simulation looks like this, in pseudo-code:

```
while (game_is_running)
{
   world.draw_to_screen();
   world.get_player_input();
   world.consume_events_until(current_time + time_step);
   current_time += time_step;
}

```

The main reason for using one in a space simulator is the necessity of providing arbitrary time-acceleration without loss of accuracy. Some missions in EXOFLIGHT may take game-years to complete, and even a 32x acceleration option would be insufficient. You'd need over 1,000,000x acceleration for a usable sim, which is difficult to do in a time-slice model. With the event-based model, we get arbitrary time rates, from 1 s = 7 ms to 1 s = 1 yr.

Changing the time rate does not change the behavior of the sim, which is a critical feature. If there is not enough CPU power available to run the simulator at the desired rate, events will stack up and we might limit UI refreshing until the event queue is cleared. Similarly, we can fast-forward the sim as much as we want and be sure we're neither wasting CPU nor sacrificing accuracy.

So summing up: We can model one vehicle in a long, leisurely orbit (using Runge-Kutta integration) and another vehicle simultaneously bouncing along the ground -- both vehicles will be simulated at the appropriate accuracy since we do not have a global timestep.

Cons: Complexity, and lack of any off-the-shelf physics engines which support this model :)
> 6 votes

# Answer
Fixed time step is useful when taking into account floating point accuracy and to make updates consistent.

It's a simple piece of code so it would be useful to try it out and see if it works for your game.

```
now = currentTime
frameTime = now - lastTimeStamp // time since last render()
while (frameTime > updateTime)
    update(timestep)
    frameTime -= updateTime     // update enough times to catch up
                                // possibly leaving a small remainder
                                // of time for the next frame

lastTimeStamp = now - frameTime // set last timestamp to now but
                                // subtract the remaining frame time
                                // to make sure the game will still
                                // catch up on those remaining few millseconds
render()

```

The main issue with using a fixed time step is that players with a fast computer won't be able to make use of the speed. Rendering at 100fps when the game is updated only at 30fps is the same as just rendering at 30fps.

That being said, it may be possible to use more than one fixed time step. 60fps could be used to update trivial objects (such as UI or animated sprites) and 30fps to update non-trivial systems (such as physics and) and even slower timers to do behind the scenes management such as deleting unused objects, resources etc.
> 5 votes

# Answer
On top of what you've already stated it may come down to the feel you want your game to have. Unless you can guarantee that you will always have a constant frame rate then you're likely to have slowdown somewhere and fixed and variable time steps will look very different. Fixed will have the effect of your game going in slow motion for a while, which can sometimes be the intended effect (look at an old school style shooter like Ikaruga where massive explosions cause slowdown after beating a boss). Variable timesteps will keep things moving at the correct speed in terms of time but you may see sudden changes in position etc. which can make it hard for the player to perform actions accurately.

I can't really see that a Fixed time step will make things easier over a network, they would all be slightly out of sync to begin with and slowdown on one machine but not another would push things more out of sync.

I've always leant towards the variable approach personally but those articles have some interesting things to think about. I've still found fixed steps quite common though, especially on consoles where people think of the framerate being a constant 60fps compared to the very high rates achievable on PC.
> 3 votes

# Answer
Use Gaffer's "fix your time step" approach. Update the game in fixed steps as in option 1, but do so multiple times per frame rendered - based on how much time has elapsed - so that the game logic keeps up with real time, while remaining in discrete steps. This way, easy to implement game logic like Euler integrators and simple collision detection still work. You also have the option of interpolating graphical animations based on delta time, but this is only for visual effects, and nothing that affects your core game logic. You can potentially get in trouble if your updates are very intensive - if the updates fall behind, you will need more and more of them to keep up, potential making your game even less responsive.

Personally, I like Option 1 when I can get away with it and Option 3 when I need to sync to real time. I respect that Option 2 can be a good option when you know what you're doing, but I know my limitations well enough to stay well away from it
> 0 votes

# Answer
I have found that fixed timesteps synchronized to 60fps gives mirror smooth animation. This is especially important for VR applications. Anything else is physically nauseating.

Variable timesteps are unsuited for VR. Have a look at some Unity VR examples which use variable timesteps. It is unpleasant.

The rule is if your 3D game is smooth in VR mode, it will be excellent in non-VR mode.

Compare these two (Cardboard VR apps)

(Variable timesteps)

(Fixed timesteps)

Your game must be multithreaded in order to achieve consistent timestep/framerate. Physics, UI and rendering must be separated into dedicated threads. It is hideous PITA to sync them, but the results are that mirror smooth rendering that you want (esp. for VR).

Mobile games are esp. challenging because the embedded CPUs and GPUs have limited performance. Use GLSL (slang) sparingly to offload as much work from the CPU as possible. Be aware than passing parameters to the GPU consumes bus resources.

Always keep your framerate displayed during development. The real game is to keep it fixed at 60fps. This is the native sync rate for most screens and also for most eyeballs.

The framework you are using should be able to notify you of a sync request, or use a timer. Do not insert a sleep/wait delay to acheive this - even slight variations are noticeable.
> 0 votes

# Answer
Variable time steps are for procedures which should be run as often as possible: Render cycles, event handling, network stuff etc.

Fixed time steps are for when you need something to be predictable and stable. This includes, but is not limited to physics & collision detection.

In practical terms, physics and collision detection should be decoupled from everything else, on it's own time step. The reason for performing procedures like these on a small fixed time step, is to keep them accurate. Impulse magnitudes are highly dependent on time, and if the interval gets too big, the simulation becomes unstable, and crazy stuff happens like a bouncing ball phases through the ground, or bounces out of the game world, Neither of which is desirable.

Everything else can run on a variable time step (though professionally speaking, it's often a good Idea to allow locking rendering to a fixed time step). In order for a game engine to be responsive, things like network messages and user input should be handled as soon as possible, which means that the interval between polling should ideally be as short as possible. This generally means variable.

Everything else can be handled asynchronously, making timing a moot point.
> 0 votes

---
Tags: physics, game-loop, frame-rate, fixed-timestep
---


# Question
Title: When is the best time to consider performance?
> I am coming from software development background. During the software development cycle, we usually focus on functionalities and the working product. At the end of development, we start optimizing the code and improving performance.

Now the question is, do we need to think about performance in every single line of code in game development?

Doing so I feel we miss the design patterns and clean code. I was wondering if there is any best practice approach in game development industry?

# Answer
**Engineering for Performance**

* Follow vendor recommendations.
* Use the correct data structures.
* Implement the correct usage patterns.
* Don't do anything stupid.

**Optimization**

* When already written code is running slow, measure it, find out why, implement what is required to make it fast.

**Premature Optimization**

* Make assumptions about what is fast or slow without measurements, build these assumptions into how code is designed and written.

---

**These three things are not the same**.

In particular *Engineering for Performance* is something you should be doing from *the very start* and it is most definitely *not the same as Premature Optimization* because it is drawing on actual measurements; in this case drawing on experience and recommendations as to how hardware works and what usage patterns are going to be fast or slow.

Failing to engineer for performance can lead to results as bad as needing an entire redesign and rewrite by the time you notice anything is wrong.

For example: all of the GPU vendors advise that doing readbacks from the GPU every frame is slow. Designing your code to not do readbacks is *not premature optimization*.
> 88 votes

# Answer
If you want to do optimization at the right times, have slow machines and use them. For a small shop, a good option is to use a slow laptop on the commute and a fast desktop in the office. As an additional benefit, if you're a one man shop this also forces you to properly back up the entire build environment.

By using a slow machine you'll know when you need to improve performance.

> do we need to think about performance in every single line of code in game development?

Absolutely not. Performance of a line of code is *usually* irrelevant in any kind of development. You need to think in terms of algorithms and algorithmic complexity, rather than in terms of lines. In many cases, decent programming means you can get about a 2 times speedup by optimizing lines of code, but choosing the right or wrong algorithm will result in factors between tens and millions.

The talk about premature optimization isn't actually about optimization being a bad thing. It's about people failing to optimize the right thing. Your time is one of the variables that needs to be optimized, which is achieved by not wasting time to "optimize" a function that is called once every 30 milliseconds and takes 100 microseconds to execute.

In other words: Making something "faster" is pointless. Your goal is "fast enough". Making something "faster" that is already "fast enough" is a waste of time, and making something "faster" that still isn't "fast enough" just means it's still too slow. "faster" is irrelevant, only "fast enough" is relevant.
> 22 votes

# Answer
No, you don't have to check after *every* line because not every line is performance-relevant. It mostly depends on how often a line is executed. A code section which takes 1 ms to be executed is completely irrelevant when it is executed once at game startup, worth watching when executed every frame and must definitely be optimized if executed for every game object each frame.

It also depends on what kind of game you are developing. When you are developing a very graphic-intense 3d shooter, you need to be much more performance-aware than when you are programming a retro-style RPG game.

In the end, the best advise is test, test, test. Build some realistic test-scenes for your game which put slightly more stuff on the screen than would be expected in the real game. Test it on hardware which is at the lower end of your targeted specs. Make sure the performance is as expected. When it gets worse, use a profiler to find the bottlenecks.
> 9 votes

# Answer
You need to put in enough effort to at least go "is this potentially going to be a bottleneck, and if so, how involved a change will it be to fix it?".

Generally speaking, this involves a balance between time/resources spent figuring out if something is the right direction and time/resources spent undoing bad decisions.

Think of it somewhat like renovating an apartment. Some decisions can have lasting repercussions ("Whoops, the fridge no longer fits in its cubby." "Whoops, where I want to put my bathroom has no water"), but you'll not think about how every stroke of your paint brush may affect e.g. the structural stability of the building.

Or, to put it another way, don't back yourself into a corner. Or at least know when you are backing yourself into a corner and make sure that is the corner you want to back into. For instance:

* Am I tying game update rate to graphical framerate?
* Am I forcing synchronous saving?
* Am I forcing (non)-determinism?
> 3 votes

# Answer
For a game, your primary goal is to meet the target framerate on the target minimum spec machine (and possibly a maximum load time, etc).

In order to do that, no, you do not have to worry after every line.

You have to worry early whenever you select a particular strategy, algorithm, or container. If you make it literally impossible to meet the target by making inadequate design decisions, then any optimization that you may do later is to no avail.

Next, you have to worry whenever *something* is parallel or parallelizable. Games are massively parallel, if for no other reason, then because graphics are.
Therefore, parallel doesn't just mean "threads" but also for example the graphics API, disk access, or network. Whenever you miss the opportunity of having something that *could* easily and natively be parallelized run in parallel, for example due to synchronizing badly (or due to not using an asynchronous API at all), you lose more than you can ever optimize by other means.
You also have to worry whenever *something* is well-known to be a bottleneck or a source of stalls, or a hindrance to scaling. Such as, for example, switching render states, draw calls, reading back from the GPU, or opening files.

Last, when you are done, and testing shows that you *do not* meet the target frame rate, you need to optimize. Find the one biggest bottleneck that takes 90% of the time, and optimize that. If this is not enough, find the seconds biggest.
If you do meet the target, congratulations. Move on and forget it.
> 1 votes

# Answer
Get real. The answer is simply totally NO. No discussion.

The main problem is the way you ask:

> do we need to think about performance in every single line of code in game development?

You mean, also in things like the config screens? Like a one time parser for a small 1kb max config file? Seriously?

It does not matter how time critical most of your code is. There is not a single software where every single line is time critical. Nowhere.
> 0 votes

---
Tags: performance, software-engineering, design-patterns, development-speed, refactoring
---