title: Counting shader animation "iterations"

text:
# Question
Title: Counting shader animation "iterations"
I'm writing a shader that animates "pinching" an image and releasing it. It's similar to this shader on shadertoy.

One issue I have is that my shader should only "animate" once - meaning the image should appear to "pinch", then "unpinch", but then **stop**. Like this example, it'll keep going since the animation ia time-driven.

Since the shader is called for each pixel I don't see any easy way to track how many "animation iterations" there have been for the entire image.

I can handle animation via a Unity `Update` method, where I can easily control when to stop, but I'd rather do this entirely in-shader if at all possible.

```
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 uv = fragCoord.xy / iResolution.xy;

    vec2 center = vec2( .5 );
    vec2 dir = normalize( center - uv );
    float d = length( center - uv );
    float factor = .5 * sin( iTime );
    float f = exp( factor * ( d - .5 ) ) - 1.;
    if( d > .5 ) f = 0.;

    fragColor = texture( iChannel0, uv + f * dir );
}

```

# Answer
All you need to do is clamp your time value, so that it holds a constant value after it's gone through the desired number of iterations.

```
// Constants to declare elsewhere.
#define TWOPI 6.28318530718
#define maxCycles 1.0f

// These lines go inside your mainImage shader.
float phase = (iTime - startTime)/TWOPI;
phase = min(phase, maxCycles);
float factor = .5 * sin(TWOPI * phase);

```

This effectively stops time after the desired number of cycles of the sine function.

Note that you'll need to provide a startTime so it knows when the pinch began. You can use a float uniform for this and set it once at the beginning of the effect.
> 4 votes

# Answer
@DMGregory Answer is correct but you mentioned that didn't reailze his answer,I just explain more here:

for counting shader animation iterations you should use periodic function. if you want understand you can see below functions on GraphToy.

```
sin(clamp(x,0,(2*PI)))
sin(clamp(x,0,(2*PI)*2))
sin(clamp(x,0,(2*PI)*3))

```

this is simple example:

```
    #define PI 3.14159265359

    void mainImage(out vec4 fragColor, in vec2 fragCoord) {

        float Iterate = 2.0;
        float Periodic = sin(clamp(iTime,0.,(2.0*PI)*Iterate));
        fragColor =  vec4(1.0) * Periodic;
    }

```

so you can iterate your shader animation easily:

```
#define PI 3.14159265359

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 uv = fragCoord.xy / iResolution.xy;
    float Iterate = 2.0;
    float Periodic = sin(clamp(iTime,0.0,(2.0*PI)*Iterate));
    vec2 center = vec2( .5 );
    vec2 dir = normalize( center - uv );
    float d = length( center - uv );
    float factor = .5 * Periodic;
    float f = exp( factor * ( d - .5 ) ) - 1.;
    if( d > .5 ) f = 0.;

    fragColor = texture( iChannel0, uv + f * dir );

}

```

this is unity version of your shader that converted by shadertoy to unity tool.

```
Shader"ShaderMan/Periodic"{
Properties{
_MainTex("_MainTex", 2D) = "white"{}
_Iterate("Iterate",Float) = 2

}
SubShader{
Pass{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma fragmentoption ARB_precision_hint_fastest
#include "UnityCG.cginc"
struct appdata{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
sampler2D _MainTex;

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

v2f vert(appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
#define PI 3.14159265359
float _Iterate;

fixed4 frag(v2f i) : SV_Target{

{
    float Periodic = sin(clamp(_Time.y,0.0,(2.0*PI)*_Iterate));
    fixed2 uv = i.uv;
    fixed2 center = fixed2( .5 , .5 );
    fixed2 dir = normalize( center - uv );
    fixed d = length( center - uv );
    fixed factor = .5 * Periodic;
    fixed f = exp( factor * ( d - .5 ) ) - 1.;
    if( d > .5 ) f = 0.;

    return tex2D( _MainTex, uv + f * dir );
}
}ENDCG
}
}
}

```
> 2 votes

---
Tags: unity, shaders
---


title: how can I make delay in shader?

text:
# Question
Title: how can I make delay in shader?
my effect is loop but I need have delay between each flash effect.i don't want use c# code because i believe there is easy way to implement delay in shader.

```
waitfor 2 second
flash effect
waitfor 2 second
flash effect
....

```

this is my shader:

```
Shader "Smkgames/SwordFlash" {
    Properties {
        _MainTex("MainTex",2D) = "white"{}
        _Color ("Color", Color) = (1,1,1,1)
        _LineColor ("LineColor", Color) = (1,1,0,1)
        _Speed ("Speed",Float) = 1
        _Thickness ("Thickness", Float) = 4.286548
        _LineSeparation ("LineSeparation", Range(0.1, 10)) = 1
        _LineRotation ("LineRotation", Range(-180, 180)) = 0
        _Numbers ("Numbers", Float ) = 1
        [MaterialToggle] _Enable ("Enable", Float ) = 1
        _Mask ("Mask", 2D) = "white" {}
    }
    SubShader {
               Tags {
            "IgnoreProjector"="True"
            "Queue"="Transparent"
            "RenderType"="Transparent"
        }
ZWrite Off Blend SrcAlpha OneMinusSrcAlpha

Pass
{
Name "Sprite"

CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma fragmentoption ARB_precision_hint_fastest
#include "UnityCG.cginc"

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

struct VertexOutput
{
float4 vertex : SV_POSITION;
half2 uv  : TEXCOORD0;
};

sampler2D _MainTex;
float4 _MainTex_ST;
fixed4 _Color;
float _Speed;
float _Numbers;

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

float4 frag (VertexOutput i) : COLOR
{

float2 uv = i.uv.xy;
    float4 tex = tex2D(_MainTex, uv);

return tex*_Color;
}
ENDCG
}

        Tags {
            "IgnoreProjector"="True"
            "Queue"="Transparent"
            "RenderType"="Transparent"
        }
        Pass {
            Name "FlashEffect"
            Blend One One
            ZWrite Off

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #define UNITY_PASS_FORWARDBASE
            #include "UnityCG.cginc"
            #pragma multi_compile_fwdbase
            #pragma only_renderers d3d9 d3d11 glcore gles n3ds wiiu
            #pragma target 3.0
            uniform float4 _TimeEditor;
            uniform float _LineAlpha;
            uniform float _Speed;
            uniform float _Thickness;
            uniform float _LineSeparation;
            uniform float _LineRotation;
            uniform float4 _LineColor;
            uniform float _Numbers;
            uniform fixed _Enable;
            uniform sampler2D _Mask; uniform float4 _Mask_ST;
            sampler2D _MainTex;
            struct VertexInput {
                float4 vertex : POSITION;
                float2 texcoord0 : TEXCOORD0;
            };
            struct VertexOutput {
                float4 pos : SV_POSITION;
                float2 uv0 : TEXCOORD0;
            };
            VertexOutput vert (VertexInput v) {
                VertexOutput o = (VertexOutput)0;
                o.uv0 = v.texcoord0;
                o.pos = UnityObjectToClipPos(v.vertex );
                return o;
            }
            float4 frag(VertexOutput i) : COLOR {
                float4 _Mask_var = tex2D(_Mask,TRANSFORM_TEX(i.uv0, _Mask));
                float node_9529_ang = (_LineRotation*0.01745333+0.0);
                float node_9529_spd = 1.0;
                float node_9529_cos = cos(node_9529_spd*node_9529_ang);
                float node_9529_sin = sin(node_9529_spd*node_9529_ang);
                float2 node_9529_piv = float2(0.5,0.5);
                float2 node_9529 = (mul(float2((i.uv0.r/_LineSeparation),(i.uv0.g/_LineSeparation))-node_9529_piv,float2x2( node_9529_cos, -node_9529_sin, node_9529_sin, node_9529_cos))+node_9529_piv);
                float4 node_5664 = _Time + _TimeEditor;
                float node_6322 = frac((_Numbers*(1.0 - (node_9529+(node_5664.g*_Speed))).g));
                float node_4443 = (pow(smoothstep( 0.5, 0.0, ((1.0 - node_6322)*node_6322) ),(35.0-_Thickness))*_LineColor.a);
                float3 emissive = lerp( ((node_4443*_LineColor.rgb)), 0.0, 1-_Enable )*_Mask_var.a;
                float3 finalColor = emissive;
                return fixed4(finalColor,1)*tex2D(_MainTex,i.uv0).a*_Mask_var.x;
            }
            ENDCG
        }
    }
Fallback "Sprites/Default"
}

```

# Answer
To create a pause what you need to do is to scale and clamp your time.

As your animation time is already exactly 1 second long and you want a 2 second pause (1+2 = 3) you will need to:

* divide your time by 3 (multiply by 1.0/3.0)
* keep the fractional part as you're doing already,
* multiply by 3 (back to normal time scale)
* then clamp the animation value between 0 and 1 (your original animation length).

The line:

`float node_6322 = frac((_Numbers*(1.0 - (node_9529+(node_5664.g*_Speed))).g));`

Need to be changed to:

`float node_6322 = clamp(frac( (_Numbers*(1.0 - (node_9529+(node_5664.g*_Speed))).g) * (1.0/3.0)) * 3.0, 0.0, 1.0)`;

This will extend the animation to 3 seconds total (1 second animation + 2 seconds pause) but the clamp part stops the animation at the loop point (1.0).

You'll have to insure the pause point is at the start/end (loop point) of your animation, which usually it is.
> 1 votes

---
Tags: unity, shaders, sprites, fragment-shader, shaderlab
---


# Question
Title: What means the error "already purchased" when buying a Consumable item with Unity IAP?
I'm facing an issue related to Unity IAP with consumable items. If I try to purchase one it shows: "Item already purchased" with this

> log- onIabPurchaseFinished: false Unable to buy item (response: 7:Item Already Owned)

Does anyone know what this means?

# Answer
> 1 votes
I've never used Unity IAP, but as the log states, a consumable item *"has already been purchased"*. The log tells you `onIabPurchaseFinished: false`. This means that the in app puchase didn't finish(because apparently you *already* purchased it). It also tell you `Unable to buy item (response: 7:Item Already Owned)`, so the cause is: you already own the item.

To fix the problem, you need to call `FinishTransaction` to *consume* the consumable. That way Google knows the user did get his reward, and can complete the transaction successfully.

---
Tags: unity, google-play-services, in-app-purchase
---


# Question
Title: Why when generating a maze the grid is not really 10x10 size?
For example in the Inspector i set the Width and Height values to 10. So the grid should be 10x10 But when i'm running the game it's changing the values of the Width and Height in the inspector to 11 both to 11. And then when i look at the scene view and counting the width and height i see they are both 9. Like 9x9 grid, not 10x10 and not 11x11.

Then later if i click the button i created to generate a new maze each time then if i set the width and height both to 5 the grid size will be 4x4 and if i set both to 6x6 the grid size will be 5x5

For some reason the value i enter for width and height he reduce it by one. And i want to make it in the size of the values. For example 10x10 so the grid will be 10x10.

This is a screenshot while the game is running. you can see on the right in the inspector i changed the values to 5 and 5 and clicked the button. But in the scene view you can count the size of the grid: it's 4x4

It's showing only the maze but you can imagine and count how the grid should be and see it's not 5x5 but 4x4

This is another screenshot of 5x5 this time the grid seems like size of 3x3 Maybe i don't understand how it's working and how it should work ?

This is a link for the tutorial i'm trying to make:

Maze tutorial

This is the scripts i'm using so far:

Maze class for all settings and generating:

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

public class Maze
{
    //Grid size
    public int width;
    public int height;

    //Store grid
    private bool[,] grid;
    //Generate random directions to move
    private System.Random rg;

    //Start position
    int startX;
    int startY;

    //Public getter
    public bool[,] Grid
    {
        get { return grid; }
    }

    //Constructor of the grid for setting values
    public Maze(int width, int height, System.Random rg)
    {
        this.width = width;
        this.height = height;

        this.rg = rg;
    }

    //Generate the grid
    public void Generate()
    {
        grid = new bool[width, height];

        startX = 1;
        startY = 1;

        grid[startX, startY] = true;

        MazeDigger(startX, startY);
    }

    void MazeDigger(int x, int y)
    {
        int[] directions = new int[] { 1, 2, 3, 4 };

        //We create random array of directions
        HelpingTools.Shuffle(directions, rg);

        //We are looping over all the directions
        for (int i = 0; i < directions.Length; i++)
        {
            if (directions[i] == 1)
            {
                if (y - 2 <= 0)
                    continue;

                if (grid[x, y - 2] == false)
                {
                    grid[x, y - 2] = true;
                    grid[x, y - 1] = true;

                    MazeDigger(x, y - 2);
                }
            }

            if (directions[i] == 2)
            {
                if (x - 2 <= 0)
                    continue;

                if (grid[x - 2, y] == false)
                {
                    grid[x - 2, y] = true;
                    grid[x - 1, y] = true;

                    MazeDigger(x - 2, y);
                }
            }

            if (directions[i] == 3)
            {
                if (x + 2 >= width - 1)
                    continue;

                if (grid[x + 2, y] == false)
                {
                    grid[x + 2, y] = true;
                    grid[x + 1, y] = true;

                    MazeDigger(x + 2, y);
                }
            }

            if (directions[i] == 4)
            {
                if (y + 2 >= height - 1)
                    continue;

                if (grid[x, y + 2] == false)
                {
                    grid[x, y + 2] = true;
                    grid[x, y + 1] = true;

                    MazeDigger(x, y + 2);
                }
            }
        }
    }
}

```

This class create random array of the maze:

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

public class HelpingTools : MonoBehaviour
{
    public static T[] Shuffle<T>(T[] array, System.Random rg)
    {
        for (int i = 0; i < array.Length - 1; i++)
        {
            int randomIndex = rg.Next(i, array.Length);

            T tempItem = array[randomIndex];

            array[randomIndex] = array[i];
            array[i] = tempItem;
        }

        return array;
    }
}

```

This is the maze generator class

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

public class MazeGenerator : MonoBehaviour
{
    public Maze maze;
    public int mazeWidth;
    public int mazeHeight;
    public string mazeSeed;
    public GameObject wallPrefab;

    private GameObject wall;
    private GameObject wallCorner;
    private System.Random mazeRG;
    private GameObject[] bricks;

    // Use this for initialization
    void Start ()
    {
        mazeRG = new System.Random();

        if (mazeWidth % 2 == 0)
            mazeWidth++;

        if (mazeHeight % 2 == 0)
        {
            mazeHeight++;
        }

        maze = new Maze(mazeWidth, mazeHeight, mazeRG);
        GenerateMaze();
    }

    public void GenerateMaze()
    {
        bricks = GameObject.FindGameObjectsWithTag("MazeBrick");
        if (bricks.Length > 0)
            DestroyMaze();

        maze.Generate();
        DrawMaze();
    }

    private void DestroyMaze()
    {
        for(int i = 0; i < bricks.Length; i++)
        {
            DestroyImmediate(bricks[i]);
        }
    }

    void DrawMaze()
    {
        for (int x = 0; x < mazeWidth; x++)
        {
            for (int y = 0; y < mazeHeight; y++)
            {
                Vector3 position = new Vector3(x, 0.5f, y);

                if (maze.Grid[x, y] == true)
                {
                    CreateMaze(position, transform, 0, mazeRG.Next(0, 3) * 90);
                }
            }
        }
    }

    void CreateMaze(Vector3 position, Transform parent, int sortingOrder, float rotation)
    {
        GameObject mazePrefab = Instantiate(wallPrefab, position, Quaternion.identity);
        mazePrefab.transform.SetParent(parent);
        mazePrefab.transform.Rotate(0, 0, rotation);
        mazePrefab.tag = "MazeBrick";
    }

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

    }
}

```

This is the button script@

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

[CustomEditor(typeof(MazeGenerator))]
public class GenerateButton : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        MazeGenerator myScript = (MazeGenerator)target;
        if (GUILayout.Button("Generate Maze"))
        {
            myScript.GenerateMaze();
        }
    }
}

```

My problem is that the grid size not fit to the result when running the game. The Maze is fine but the grid not seems to be 10x10 or 5x5 or 6x6

If for example i wanted to draw the completed grid not only the random maze then how can i do it and what would be the size ?

Again maybe i didn't understand how it is working and should be working.

# Answer
At a glance, it looks like each cell is either open or a wall (as opposed to maze algorithms that treat walls as lines rather than volumes). Some algorithms that do so further assume that outer ring of cells must be a wall (though some later dig an entrance & exit). It looks as if this algorithm does something similar. for instance, in the code for `Start()` you have:

```
if (mazeWidth % 2 == 0)
     mazeWidth++;

if (mazeHeight % 2 == 0)
{
     mazeHeight++;
}

```

This code checks to see if either dimension is even & if so, will increment said dimension to the next largest integer. (Side note: you should be consistent with your use of `{ }` braces & `if` statements. either brace all single line `if`s or none - don't do some, but not others. Personally, I recommend them on all `if` statements, single line or otherwise.)

So that's why your size doesn't always match your parameters. But your maze digging logic might also depend on getting an odd size, so fixing this might not be as simple as just changing the code in `Start.` For instance, there are several conditionals in `MazeDigger` that are checking the indices relative to the dimensions.
> 2 votes

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


# Question
Title: Render 2D texture on the cube texture at given location
I would like to simulate a moving sun on the sky. What I have managed to do so far is calculating the exact location of the sun, that is the 3D direction vector from the camera's position in the world to the sun. The sky is the cube with 6 faces textured with some cube map texture. The skybox positon is constantly being set to the position of the camera, so that the camera is always in the cube's center.

Now, I have a simple 2D texture of the sun that I would like to render onto the cube map texture using the aforementioned direction vector. Could you please describe how I can achieve this? My reasoning is that I need to bind the framebuffer of the cube map and then render the sun mesh with the correct sun texture. But how do I specify the position of the sun here so that it matches the direction vector I have calculated earlier? Another question is if there might be problem when it happens that part of the sun is supposed to be rendered on one face of the cube texture and the other part on some other face of the cube texture?

Thank you in advance.

# Answer
> 3 votes
Why render the sun into the skybox? Just render the skybox and then draw the sun without using a depth test. This way you don't have to modify any textures and then redraw them. It's much easier to draw the sun where it belongs that way, too.

As Nicol Bolas mentions in the comment, you can put the sun *behind* the skybox if it's transparent. You might do something like set the clear color to a sky blue and clear it, draw the sun in the appropriate position, then draw the skybox containing clouds after that. If you're simulating an entire day, you'll need to change the clear color over time, and rotate the skybox so the clouds look like they're moving.

---
Tags: opengl, frame-buffer, skybox, rendertexture, sky
---


# Question
Title: Implementing spot lights in Vulkan and some pixels are black
**TL;DR;** I have come to the conclusion that the problem is linked to the spot light being too close to the camera. Which only made me more confused.

**Long version;** I have sat with this my whole day and now, my head just hurts and I need to ask for help. Basically, I have a spot light attached to my camera - pointing in the same direction as the camera, acting as a flashlight. I can toggle this on and off. When toggling this on and off, the whole scene gets covered in random black pixels and I have no idea why. For reference, here's my entire fragment shader;

```
/*
*   Calculates the distribution.
*/
float CalculateDistribution(vec3 halfwayDirection)
{
float roughnessSquared = roughness * roughness;
float roughnessSquaredSquared = roughnessSquared * roughnessSquared;
float normalHalfwayAngle = max(dot(normalDirection, halfwayDirection), 0.0f);
float normalHalfwayAngleSquared = normalHalfwayAngle * normalHalfwayAngle;

float denominator = normalHalfwayAngleSquared * (roughnessSquaredSquared - 1.0f) + 1.0f;

return roughnessSquaredSquared / (PI * denominator * denominator);
}

/*
*   Calculates the geometry.
*/
float CalculateGeometry(float lightAngle)
{
float geometryRoughness = roughness + 1.0f;
geometryRoughness = (geometryRoughness * geometryRoughness) / 8.0f;

float lightObstruction = lightAngle / (lightAngle * (1.0f - geometryRoughness) + geometryRoughness);
float viewObstruction = viewAngle / (viewAngle * (1.0f - geometryRoughness) + geometryRoughness);

return lightObstruction * viewObstruction;
}

/*
*   Calculates the fresnel, with roughness in mind.
*/
vec3 CalculateFresnelRoughness(float lightViewAngle)
{
return surfaceColor + (max(vec3(1.0f - roughness), surfaceColor) - surfaceColor) * pow(1.0f - lightViewAngle, 5.0f);
}

/*
*   Calculates the fresnel.
*/
vec3 CalculateFresnel(float lightViewAngle)
{
return surfaceColor + (1.0f - surfaceColor) * pow(1.0f - lightViewAngle, 5.0f);
}

/*
*   Calculates the ambient component of this fragment.
*/
vec3 CalculateAmbient()
{
return albedoColor * AmbientMultiplier;
}

/*
*   Calculates a light.
*/
vec3 CalculateLight(vec3 lightDirection, vec3 radiance, float intensity)
{
vec3 halfwayDirection = normalize(viewDirection + lightDirection);
float lightViewAngle = max(dot(halfwayDirection, viewDirection), 0.0f);
float lightAngle = max(dot(normalDirection, lightDirection), 0.0f);

float distribution = CalculateDistribution(halfwayDirection);
float geometry = CalculateGeometry(lightAngle);
vec3 fresnel = CalculateFresnel(lightViewAngle);

vec3 diffuseComponent = vec3(1.0f) - fresnel;
diffuseComponent *= 1.0f - metallic;

vec3 nominator = distribution * geometry * fresnel;
float denominator = 4 * viewAngle * lightAngle + 0.001f;
vec3 specularComponent = nominator / denominator;

//Return the combined components.
return (diffuseComponent * albedoColor / PI + specularComponent) * radiance * lightAngle * intensity;
}

/*
*   Calculates a single point light.
*/
vec3 CalculatePointLight(int index)
{
//Calculate the point light.
vec3 lightDirection = normalize(pointLightWorldPositions[index] - fragmentWorldPosition);

float distanceToLightSource = length(fragmentWorldPosition - pointLightWorldPositions[index]);
float attenuation = clamp(1.0f - distanceToLightSource / pointLightAttenuationDistances[index], 0.0f, 1.0f);
attenuation *= attenuation;

vec3 radiance = pointLightColors[index] * attenuation;

return CalculateLight(lightDirection, radiance, pointLightIntensities[index]);
}

/*
*   Calculates a single spot light.
*/
vec3 CalculateSpotLight(int index)
{
//Calculate the spot light.
vec3 lightDirection = normalize(spotLightWorldPositions[index] - fragmentWorldPosition);
float angle = dot(lightDirection, -spotLightDirections[index]);

float distanceToLightSource = length(fragmentWorldPosition - spotLightWorldPositions[index]);
float attenuation = clamp(1.0f - distanceToLightSource / spotLightAttenuationDistances[index], 0.0f, 1.0f);
attenuation *= attenuation;

vec3 radiance = spotLightColors[index] * attenuation;

vec3 calculatedLight = CalculateLight(lightDirection, radiance, spotLightIntensities[index]);

//Calculate the inner/outer cone fade out.
float epsilon = spotLightInnerCutoffAngles[index] - spotLightOuterCutoffAngles[index];
float intensity = angle > spotLightInnerCutoffAngles[index] ? 1.0f : clamp((angle - spotLightOuterCutoffAngles[index]) / epsilon, 0.0f, 1.0f);

calculatedLight *= intensity;

return calculatedLight;
}

void main()
{
//Sample values from the textures.
albedoColor = pow(texture(albedoTexture, fragmentTextureCoordinate).rgb, vec3(2.2f));

//Calculate the normal direction.
normalDirection = texture(normalMapTexture, fragmentTextureCoordinate).xyz * 2.0f - 1.0f;
normalDirection = fragmentTangentSpaceMatrix * normalDirection;
normalDirection = normalize(normalDirection);

roughness = texture(roughnessTexture, fragmentTextureCoordinate).r;
metallic = texture(metallicTexture, fragmentTextureCoordinate).r;
ambientOcclusion = texture(ambientOcclusionTexture, fragmentTextureCoordinate).r;

//Calculate globals.
viewDirection = normalize(cameraWorldPosition - fragmentWorldPosition);
viewAngle = max(dot(normalDirection, viewDirection), 0.0f);
surfaceColor = mix(vec3(0.04f), albedoColor, metallic);

//Start off with just the ambient lighting.
vec3 finalFragment = CalculateAmbient();

//Calculate all point lights.
for (int i = 0; i < numberOfPointLights; ++i)
{
    finalFragment += CalculatePointLight(i);
}

//Calculate all spot lights.
for (int i = 0; i < numberOfSpotLights; ++i)
{
    finalFragment += CalculateSpotLight(i);
}

//Apply gamma correction.
finalFragment = pow(finalFragment, vec3(1.0f / 2.2f));

//Set the final fragment color.
fragmentColor = vec4(finalFragment, 1.0f);
}

```

PHEW. That's a lot of code. It's a PBR shader in the making, kind of. The function "CalculateSpotLight" is of the most interest. For some reason, changing out;

```
vec3 lightDirection = normalize(spotLightWorldPositions[index] - fragmentWorldPosition);

```

to;

```
vec3 lightDirection = vec3(0.0f, 1.0f, 0.0f);

```

or some other arbitrary value, removes the black pixels, which led me to believe that the normalize function receives a vec3(0.0f, 0.0f, 0.0f), but that's not the case, I've added numerous checks to detect division by zero, and checking afterward with isnan() and isinf(), and none of those tests trigger anything.

Weirdly enough, moving the spot light DOWN just a bit removes the black pixels. So basically, the problem is that the spot light is to close to the camera? However that would relate to anything. So I'm confused. Some posts suggested these kind of issues are actually just driver issues, and I've actually seen some users solve these kind of issues by just updating the drivers, so I tried updating my graphics driver aaand - Still there.

I'm confused. I don't know what could be wrong. Please help.

**EDIT;**

Okay, so now I've sat for around an hour testing everywhere for divisions by zero, and I've found where the fault... It was in the "CalculateFresnel()" function. The first argument to pow somehow was negative, so just adding;

```
return surfaceColor + (1.0f - surfaceColor) * pow(max(1.0f - lightViewAngle, 0.0f), 5.0f);

```

instead fixed the black pixels. Which perhaps kind of makes sense in the end? In the "CalculateLight()" function, I calculated the halfwayDirection by normalizing the viewDirection (as in, the direction from the camera to the fragment) added together with the lightDirection (as in, the direction from the spot light to the fragment) which basically did nothing because **those vectors are the same** in this specific, since the spot light position is at the camera. Then, I tried doing a dot product of the halfwayDirection and the viewDirection, which in this case are the same vectors. And the result calculating the dot product of two identical vectors result in the magnitude of either of those vectors squared. But then again, it doesn't make sense how that number could be negative? It's a unit vector, so the magnitude should be 1, and 1 multiplied by 1 is still one.. So this is where I can't wrap my head around what's going on again. If anyone has any input, feel free to share. (:

# Answer
**So,** it appears that I have found the issue. Kind of. I know what I want to blame it on at least - **floating point rounding errors**. As I wrote in my edit, the problem seems to stem from *lightViewAngle* being larger than 1.0f, which will cause the fresnel calculation,

```
return surfaceColor + (1.0f - surfaceColor) * pow(1.0f - lightViewAngle, 5.0f);

```

to be faulty, because it passes in a negative value as the first argument to *pow()*, which is undefined behavior. In this case the behavior is defined in that my graphics card throws up it's hands and gives me a black pixel. Mathematically it's impossible to get a dot product over 1.0f, but after reading up on it a bit, apparently floating point rounding errors can cause it to be a bit larger. So instead of doing a *max()* I now do a *clamp()* between 0.0f and 1.0f, which fixed my problem.

Why this only happens on certain pixels, I don't know. As I wrote in my post, it stems from the fact that it tries to get a dot product from two (in theory) equal unit vectors, and this causes the dot product to be larger than 1.0f, for... Some reason. Might be a driver bug. At least I've found the issue now at least. Thank you all for the help. (:
> 2 votes

# Answer
Random black pixels usually means a division by zero somewhere in your shader producing a NaN.

Look at each one of your divisions and insure that none have a zero as the denominator, maybe using a `y / max(x, 0.001)` or something similar or rewriting your formula to avoid using divisions.

The angle between your spotlight and the camera most likely end up being exactly zero in those cases, moving the spotlight away changes the angle and avoids the divisions by zero.
> 0 votes

---
Tags: opengl, glsl, shading, vulkan
---


# Question
Title: Unreal Engine 4.18 - Knife (Weapon) collides with character capsule collision
I have a character and he has a knife in his hand. When Run / Walk action happens hands move and so does knife, its collision collides with character's capsule collision and causes issue in movement.

More info: Component Hierarchy looks like

# Answer
Following is the answer for blueprints

**Ignore Knife with reference to Capsule Component**

1. In your **character blueprint** \> **event graph** draw a new connection from **Event BeginPlay** node, select **Ignore Actor when Moving** from list
2. It has two pins **Target** and **Actor**, Set **Target** to **Capsule Component** reference
3. For **Actor** you kneed to connect the Knife, but Knife is not exactly a true actor, it is a child actor component (A component that spawns an actor when registered, and destroys when unregistered, so do the following)

4. Don't forget to check **should ignore** third key

that's it, now your **Knife** will be ignored by your **Capsule Component**

thanks to @DMGregory for the lead
> 1 votes

---
Tags: collision-detection, movement, unreal-4, socket
---


# Question
Title: How can i loop over all the childs of childs?
In top of script i added:

```
public Transform parentToSearch;

```

Then:

```
private void OnGUI()
    {
        if (hasDescription == true && clickForDescription == true)
        {
            foreach (Transform child in parentToSearch)
            {
                if (child.GetComponent<ItemInformation>() != null)
                {
                    ItemInformation iteminformation = child.GetComponent<ItemInformation>();
                    if (child.name == objectHit)
                    {
                        var centeredStyle = GUI.skin.GetStyle("Label");
                        centeredStyle.alignment = TextAnchor.UpperCenter;
                        GUI.Label(new Rect(Screen.width / 2 - 50, Screen.height / 2 - 25, 100, 50), iteminformation.description, centeredStyle);
                    }
                }
            }
        }
    }

```

But when i make the loop:

```
foreach (Transform child in parentToSearch)

```

It will find the first level childs of the first parent but this childs have also childs and so on. And i want to loop all the childs and childs of childs under the Transform.

For example in the Hierarchy i have:

* Test
    + Test1
    + Test2
    + Test3
        - Test31
        - Test32
    + Test4
    + Test5
        - Test51

So now it will loop only over Test 1,2,3,4,5 but I want also to loop over Test31,Test32,Test51

# Answer
You can use a recursive call

```
void Process(Transform parent, int level = 0)
{
    // TODO: process the parent object.

    foreach (Transform child in parent) {
        // The Process method calls itself. This is the recursive call.
        Process(child, level + 1);
    }
}

```

You never have to process the child, as each child will become the parent in the recursive call.

I also added a level information allowing you to indent children when printing, adding a label etc. (optional).

---

If you don't want to process the top-level parent, you can instead process the children.

```
void Process(Transform parent, int level = 0)
{
    foreach (Transform child in parent) {
        // TODO: process the child object.

        // Process next deeper level
        Process(child, level + 1);
    }
}

```

---

Applied to your problem:

```
private void OnGUI()
{
    if (hasDescription && clickForDescription)
    {
        ProcessOnGUI(parentToSearch);
    }
}

void ProcessOnGUI(Transform parent, int level = 0)
{
    foreach (Transform child in parent) {
        var iteminformation = child.GetComponent<ItemInformation>();
        if (iteminformation != null && child.name == objectHit) {
            var centeredStyle = GUI.skin.GetStyle("Label");
            centeredStyle.alignment = TextAnchor.UpperCenter;
            GUI.Label(new Rect(
                  Screen.width / 2 - 50 + 20 * level, // <== INDENTATION
                  Screen.height / 2 - 25, 100, 50),
                iteminformation.description, centeredStyle);
        }

        // Process next deeper level
        ProcessOnGUI(child, level + 1);
    }
}

```
> 1 votes

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


title: Trail Effect for fast moving object

text:
# Question
Title: Trail Effect for fast moving object
I am currently working on some FX trail effect. Here's the situation, you have a fast moving object that puts trail on another object.

Here's how it works for the moment. I have some kind of stamp texture (the object) that is printed onto another texture of the receiver object. When the object is moving not to fast, you can see the trail effect. But the problem appears when the object is moving to fast, then you don't see the trail but only the stamp texture printed at some points.

The issue is quite logical and linked to the time when the update function is called (I am using Unity). The function is not called enough so it's missing some positions and thus the trail effect

# Answer
> 1 votes
You could find the distance traveled per frame and then draw the stamp texture in all the positions along the line segment calculated. For example:

```
vec2 prevPoint; // contains the previous position of the moving object
vec2 currentPoint; // contains the current position of the moving object
vec2 direction = currentPoint - prevPoint;
double distance = direction.legnth();
direction.normalize();
const double spacing = <distance between stamps you want>;
for (double distTraveled = 0.0; distTraveled < distance; distTraveled += spacing)
{
    vec2 stampPos = prevPoint + direction * distTraveled;
    placeStamp(stampPos);
}

```

---
Tags: unity, rendering, graphics, graphic-effects, special-effects
---


title: How to make body flying

text:
# Question
Title: How to make body flying
I am trying to make a body flying

is there any way to change gravity or hold the circle levitating?

Here is the code i'm using:

```
public class Fly extends Enemy {

     .....
   protected void defineEnemy() {
    BodyDef bdef = new BodyDef();
    bdef.position.set(getX(),getY());
    bdef.type = BodyDef.BodyType.DynamicBody;
    b2body=world.createBody(bdef);

    FixtureDef fdef = new FixtureDef();
    CircleShape shape = new CircleShape();
    shape.setRadius(6/Advanture.PPM);
    b2body.createFixture(fdef).setUserData(this);

}

 @Override
public void update(float dt) {
   stateTime +=dt;
   b2body.setLinearVelocity(new Vector2(-1,0));
   setPosition(b2body.getPosition().x - getWidth()/2, 1);

  }

......
 }

```

# Answer
I just found the way of changing gravity.

So, this is done by using `b2body.setGravityScale(float number);`

If you want to make the body less affected by gravity, it should be `b2body.setGravityScale(1/100);`

So it depends on number, you can let the character be affected by gravity however much you want.
> 1 votes

---
Tags: libgdx, box2d
---


# Question
Title: How can I move game objects using keyboard in the Unity scene editor?
I know I can click on the "move" button

and use my mouse to drag the object around. How can I do the same using my keyboard?

# Answer
> 3 votes
You can use Q/W/E/R/T to trigger those buttons, W being "move", E "rotate" and R "scale". This is faster than clicking the buttons in my opinion.

However, there is unfortunately no key for "grabbing and moving" an object, like for example blender has.

# Answer
> 2 votes
There is no keyboard shortcuts for moving a selected object around (afaik). What I like to do is change the location on each axis by selecting the gameobject in question and moving it using the inspector; If you mouse over the axis you are working with (for instance: X), you can 'drag' it right or left to increase and decrease that value. This might be a good alternative.

# Answer
> 1 votes
I just made a Unity editor script to accomplish exactly what you are looking for. Check it out at this GitHub Gist

# Answer
> 0 votes
I don't have my copy of unity to hand right now to try it out, but I couldn't find any way to move gameobjects using the keyboard. However, I did find this page full of keyboard shortcuts. Also, if the issue was not having enough precision with the mouse, you can always use snapping to make sure that the vertices and objects align properly.

---
Tags: unity
---


# Question
Title: Alternative to Google Play when publishing Android game app (.apk)?
In order to register as a game developer and publisher of the Android app for Google Play Developer account, you must pay around $100. But what if there's a tight budget, especially for indie game developers from the start? I want to know where can I find alternatives to publish and promote Android game apps with no registration cost. It is something like a stepping stone.

# Answer
> 1 votes
You can host the *.apk* anywhere online and just let the users download and install it manually. The down sides of this approach are many, for example discoverability (most people find *all* their applications *only* in Google Play) and lower level of trust (people are less likely to trust something outside of Google Play).

Having said that, this approach is used successfully by some apps, notably some betting companies do it this way due to Google Play's stance on gambling apps.

---
Tags: android, publishing, business, accessibility
---


# Question
Title: Let player upload text file in-game Unity
How would I create a button for the user to click and be able to upload a text file from his desktop let's say?

I'd like to know about both, computer and mobiles.

# Answer
> 1 votes
There are multiple ways to get some bytes of text from the client to a server. But one way to do this which should be quite platform-agnostic is with a HTTP POST Request. The Unity class you need for this is the class `WWWForm` to store the POST data in addition to the class `WWW` to make the HTTP request.

The example in the official documentation shows you how to take and upload a screenshot, but you can of course use the same technique to upload a string of text. Here is a modification of the example which should do that (untested, but I am feeling lucky):

```
IEnumerator UploadString() {
    // TODO: replace with the URL of your receiver webservice on your webserver
    string url = "https://example.com/textFileUpload"

    // TODO: Obtain name and content of the file you want to upload
    string filename = "hello.txt";
    string content = "Hello World!";

    // Create a Web Form
    WWWForm form = new WWWForm();
    form.AddField("fileContent", content);
    form.AddField("fileName", filename);

    // Upload to a cgi script
    WWW w = new WWW(url, form);
    yield return w;
    if (!string.IsNullOrEmpty(w.error)) {
        print(w.error);
    }
    else {
        print("Finished Uploading File");
    }
}

```

Your server will receive a POST request with the filename in the field `fileName` and the content in the field `fileContent`.

What you still need to do is write a server-sided webservice which accepts the HTTP POST request and does something with the received string of text. But this is outside of the scope of this question because it isn't something you would do with Unity. With what technology do you do it instead? There are countless possibilities. ASP.NET, JSP, Perl, Node.JS, PHP, Python + Django, Ruby on Rails... and many more. Pick one and check on Stackoverflow if you need help.

(oh, and keep security in mind. Letting anyone upload anything under any name to a webserver without any plausibility checks is a very bad idea.)

---
Tags: unity, c#, networking, file
---


# Question
Title: Unity, OnMouseOver blocked by another gameobject with a collider in front of it
I have two gameobjects, both with 2D colliders.

One of them can be behind the other, and because of this its OnMouseOver can be blocked from firing as the GameObject in front blocks it from triggering.

What is a way around this? I really like the ease of using OnMouseOver, and would rather not use raycastAll.

Asked this question on SO, maybe it should be asked here.

# Answer
Two ways of doing that.

A classic, manual `Raycast` (recommended):

```
 void Update ()
 {
     RaycastHit[] hits = Physics.RaycastAll(Camera.main.ScreenPointToRay(Input.mousePosition));
     foreach(RaycastHit hit in hits)
     {
         if(hit.collider.gameObject.name == "Cube A")
         {
             //do something here
             break;
         }
     }
 }

```

The second one involves setting your object's layer to `Ignore Raycast`, which should work perfectly with `OnMouseOver`:
> 1 votes

# Answer
Not really.

Only option I can think of rn is using a 2nd camera that only renders clickable objects, so the objects that would block the ray are somewhere else in the world but rendered on another cam with higher/lower depth.

But it would probably be easier to make a ray with a LayerMask at that point.
> 0 votes

---
Tags: unity
---


# Question
Title: Why does execution continue when a delay is hit
I am working on a tile based game. I have a board generator and on the hard level I have to create 900 game tiles and add them to the screen. This takes about 3 to 4 seconds to complete. I started moving the UI code to C++ but ran into tons of issues and read that UI in C++ isn't recommended as its bug prone and difficult to work with. So I moved it back to blueprints and to avoid hogging all the CPU for 3 to 4 seconds I implemented a system to layout the board one row at a time with a short delay between to free up the CPU. This works beautifully and the board is laid out one row at a time and with the delay the FPS still hangs around 50 while doing it so sweet.

But I am running into a problem with the delay nodes. I layout a row, delay for a short period and layout the next row and so on. The proplem is as soon as I hit the first delay node, execution picks up AFTER the event containing the delays finishes.
1. While debugging, this breakpoint is the first one hit as expected.
2. Execution then enters the Layout10x10EasyBoard event as it should where a delay is triggered between rows.
3. Before the delay is finished execution picks up here and continues down the line before the delay even finishes.
4. Then this breakpoint is hit and we continue showing the rest of the game tiles.

It's my understanding that execution will stop at a delay so what I think should happen is the Layout10x10EasyBoard should finish execution before picking up at number 3. But that is not happening. The code at the end of the line requires all the tiles to be created before continuing and since the delay seems to have no effect on execution, that code is not working correctly. Does anyone know why the delay is not stopping execution?

# Answer
> 0 votes
I also posted the question to UE answer hub and apparently this is how delays are supposed to work. I added an event delegate to call at the end of the tile creation process and now the code that needs to wait, wont run till all tiles are created.

---
Tags: unreal-4, blueprints
---


# Question
Title: How to create a list of buttons from a list?
I have a scrollable list and an array of objects (about 300 to 400). The objects have two properties, a string name and a string prefab path.

I need to add a button for each object, how would I go about creating these buttons using scripting?

# Answer
Creating a button in Unity is quite simple, via scripting. Once you understand how create *a single* button, it should not be complicated to create a *list* of buttons. Let's take a look at the Unity manual.

### Step One: Make a Prefab

> In order to be able to easily instantiate UI elements dynamically, the first step is to create a prefab for the type of UI element that you want to be able to instantiate. Set up the UI element the way you want it to look in the Scene, and then drag the element into the Project View to make it into a prefab.
> **\- Unity Manual: Creating UI elements from scripting**

Simple enough, really. Make a prototype for your button. Set it up to look exactly how you want it to, and ensure it has all the components you intend to use. Save it as a prefab, so we can reference it via code. Ultimately, you have to do this because there are no public constructors for UI elements. The manual further explains the logic behind this:

> You might wonder why we don’t have a API methods to create the various types of controls, including visuals and everything. The reason is that there are an infinite number of way e.g. a button could be setup. Does it use an image, text, or both? Maybe even multiple images? What is the text font, color, font size, and alignment? What sprite or sprites should the image use?
> **\- Unity Manual: Creating UI elements from scripting**

## Step Two: Instantiate an instance of your prefab

> Prefabs of UI elements are instantiated as normal using the `Instantiate` method. When setting the parent of the instantiated UI element, it’s recommended to do it using the `Transform.SetParent` method with the `worldPositionStays` parameter set to `false`.
> **\- Unity Manual: Creating UI elements from scripting**

Following the simple route, we are using some basic Unity methods to instantiate and set up the button. First and foremost, we are using `UI.Button`, so ensure you include `using UnityEngine.UI` or otherwise refer to the button object as `UI.Button`. Note that we reference the actual button object as a `GameObject`, as you will need to include *other* components to provide realistic functionality. You will also need to have a reference to *at least* the game object that holds your canvas component (if not, a child of that object), as you will need to parent the button to the canvas when you instantiate it.

In the below example, I have provided both the prefab and the canvas reference as `public` variables, so I can simply drag and drop them in through the Unity editor.

```
using UnityEngine;
using UnityEngine.UI;

public class MinorTestMono : MonoBehaviour
{
    public GameObject buttonPrefab;
    public GameObject canvasParent;

    void InstantiatePrefab()
    {
        GameObject sample = Instantiate(buttonPrefab);
        sample.transform.SetParent(canvasParent.transform, false);
    }
}

```

## Further customisation

You would likely want to add some customisation to each button. How you do so is up to you, especially given that you have not told us *how* the button should look, at all. You should consider reading the aforementioned manual, as it elaborates on how to do so, and makes further suggestions.

Assuming you wish to include a string display on the button, you will need to include a `UI.Text` component on your original button prefab. From there, it is just a matter of directly changing the text component. You can do this inline, with something like `sample.GetComponent<Text>().text = "this is a button";`.

## Regarding lists

Now you know how to create a button, doing so as an array should be childs-play. If it is not, you should focus on familiarising yourself with how arrays work, before dealing with the creation of a 400+ array of game objects.

**I *will* give some pointers:**

* I have never personally worked with such a large number of UI elements, and will forewarn that I do not think it will run very well, in the implementation you describe. If you only wish to display a certain number of buttons at once, consider creating a more complicated system, where buttons that disappear off screen are "recycled" for use as the new buttons that appear on screen. This way, your keeping record of the exact amount of buttons you need to be *visible*, and memory usage will be a lot lighter. *Do not just ask a new question on 'how do I do that' without actually researching it for yourself, as you will likely need to put a lot more effort into this approach.*
* Ensure your `GameObject` array runs *parallel* to your other array; that is, `button[1]` should be using `object[1]` for its path and name, `button[2] should be using`object\`, and so on.
* Keep your game objects *simple*. If you do not use a particular component, do not keep it. Remember, you are potentially creating 400 iterations of this game object.
> 3 votes

# Answer
I have another (I think much better) answer. When I created a quest system for a simple RPG, I also needed a List or array in buttons. I found out, that a 'List' and 'foreach' is a much easier way to do this so here is my code:

```
public List<Quest> activeQuests = new List<Quest> ();

public GameObject ButtonParent;

public GameObject ButtonCanvas;

void Update () {
    if (Input.GetKeyDown(KeyCode.Q)) {
        if (ButtonCanvas.activeInHierarchy) {

            ButtonCanvas.SetActive(false);

        } else {
            ButtonCanvas.SetActive (true);

            foreach (Quest currentQuest in activeQuests) {
                GameObject currentButton = Instantiate (ButtonPrefab, ButtonCanvas.transform, false);
                //use currentQuest for your GameObject like Array[i] in for
            }
        }
    }
}

```
> 0 votes

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


# Question
Title: Cannot find GameController script - causing errors with logging and references
I am learning the Unity engine and have been practicing with various tutorials, but there is a curious error I am experiencing with the space shooter tutorial. Collisions with the player ship do not destroy asteroids or the player, while collisions with bolts fired by the player will destroy the asteroids but not increase the score at all.

The error being logged is "Cannot find GameController script" which makes me think there is a problem with my code below, specifically the void Start() function that checks if GameController != null.

Is there something about Unity 5 that differs from Unity 4 that I would need to change? Or have I made a mistake in this code attempting to reference the GameController script?

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

public class DestroyByContact : MonoBehaviour {

    public GameObject explosion;
    public GameObject playerExplosion;
    public int scoreValue;
    private GameController gameController;

    void Start()
    {
        GameObject gameControllerObject = GameObject.FindWithTag("GameController");
        if (gameController != null)
        {
            gameController = gameControllerObject.GetComponent<GameController>();
        }
        if (gameController == null)
        {
            Debug.Log("Cannot find 'GameController' script");
        }
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Boundary")
        {
            return;
        }
        Instantiate(explosion, transform.position, transform.rotation);
        if (other.tag == "Player")
        {
            Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
            gameController.GameOver();
        }

        Debug.Log(other.name);
        Destroy(other.gameObject);
        Destroy(gameObject);
        gameController.AddScore(scoreValue);
    }
}

```

# Answer
> 2 votes
You're most-likely doing a wrong check in the **Start** function and it should read

```
if (gameControllerObject != null)
{
 ...
}

```

because you're trying to find the controller object by tag and have to verify that the return value of `GameObject.FindWithTag(...)` is not `null`. Otherwise you might risk running into a `NullReferenceException`.

# Answer
> 0 votes
Make sure you have the game object tagged as GameController. See image.

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


# Question
Title: How do I find out if this particular puzzle can still be solved?
A while ago, I made a simple game that involved swapping birds to combine them and release them to create points. The idea is that eventually, the birds would get stuck and your game is over, but I found it tremendously hard to think of a way to detect a game-over, so I published it without such an algorithm and just hoped people would see it for themselves. However, I'm still very interested in a solution and hoped someone could help me.

The game works as follows:

* `6` different kinds of birds are distributed over an `n x n` (usually `4 x 4`) grid.
* For every two birds of the same type, if they would form a perfect rectangle together, they merge into one bigger bird of the same type. This means you can have birds that are, for example, `4 x 1` or `3 x 2`.
* Birds that are big enough can be removed from the grid, generating points. What's 'big enough' depends on the type of bird, some only need to cover `1` square on the grid, others `2` or `3`.
* Empty squares on the grid will get filled up with new, random birds falling from above. That is, of course, as long as other birds don't block the way. All birds always fall down when they can, and moving a bird upwards is therefore impossible (though, swapping upwards is allowed).
* Two birds can swap places if they are of the same width when swapping vertically, or of the same height when swapping horizontally, but only when they are aligned perfectly. A bird can always move to an empty spot, given that its new position would be large enough to contain it and that the new spot wouldn't deny gravity.
* Eventually, groups of 2 tall/wide birds will prevent anymore progress. Some birds can still be swapped, and maybe some would even become big enough to be removed when combined with certain others, but they will never get near each other, resulting in a game over.

I'm not too sure whether this is clear enough. I don't really want to post a link to the game here because I'm really only interested in the algorithm, not new downloads. Also I'm not too sure if I'm allowed to, as it could be seen as an advertisement. But please request more clarity where needed!

# Answer
> 3 votes
I think starting from a **brute force** solution is fine here, as the search space is relatively small.

At the start of every turn, recursively look at all the moves that can be made, storing the layouts that you've looked at already to avoid repeating yourself. If you can find a series of moves that lead to merging birds, *in a reasonable time*, stop; the puzzle isn't stuck yet.

For example, given this example grid:

```
+-+---+
|A| B |
+-+---+
|B|A|B|
+-+-+-+

```

We could swap the birds on the top row:

```
                 v v
+-+---+       +---+-+
|A| B |       | B |A|
+-+---+  -->  +-+-+-+
|B|A|B|       |B|A|B|
+-+-+-+       +-+-+-+

```

Next, we *don't* swap the top row again because that would repeat the first grid. Instead, we could swap the last column:

```
                 v v
+-+---+       +---+-+       +---+-+
|A| B |       | B |A|       | B |B|<
+-+---+  -->  +-+-+-+  -->  +-+-+-+
|B|A|B|       |B|A|B|       |B|A|A|<
+-+-+-+       +-+-+-+       +-+-+-+

```

...which results in pairs of birds that can be merged:

```
                 v v                         v
+-+---+       +---+-+       +---+-+       +-----+
|A| B |       | B |A|       | B |B|<      |  B  |
+-+---+  -->  +-+-+-+  -->  +-+-+-+  -->  +-+---+
|B|A|B|       |B|A|B|       |B|A|A|<      |B| A |
+-+-+-+       +-+-+-+       +-+-+-+       +-+---+
                                              ^

```

And we're done.

If we've exhausted the search space without finding pairs that can be merged, the game is stuck. It's also possible that we can't find a result in a reasonable amount of time, but this is very unlikely given the limited bird types (6) and grid size (4x4 and larger). You could add a heuristic to improve your search strategy, favouring moves that bring similar bird types closer together, if the search is too slow.

This is not a perfect solution, as it's possible that despite there being merges available, the game will eventually get stuck anyway. I don't think you'll need such a good solver though; most puzzle games make do with a simple no-moves-available-now simple solver like this one.

---
Tags: algorithm, puzzle
---


# Question
Title: WWW request does not connect using webgl platform
I use request like code below:

```
string url = "http://localhost:51820/Home/login/" + end+"/";
        WWW www2 = new WWW(url);
        StartCoroutine(waitForLogin(www2));

```

It works fine in the editor but the html build shows a connection problem. message of www error is only "unknown error"

# Answer
When you look into your browsers error console, you will likely notice an error message like this:

> Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:51820/Home/login/

For security reasons, web browsers do not allow javascript applications to send http requests to localhost when they aren't also loaded via localhost. Note that loading a html document via the `file:///` pseudo-protocol is **not** considered the same as loading from `http://localhost`.

What you can do as a workaround is put the game into the document directory of your local webserver and also load it via an URL like `http://localhost:51820/yourgame/index.html`.
> 3 votes

---
Tags: unity, html5
---


title: Dungeons in a 3d space game

text:
# Question
Title: Dungeons in a 3d space game
I'm in the process of creating a prototype for a 3d space game (3rd person). My question is this:

**How can a 3d space game have Zelda-like (or similar) dungeons in open space?**

***Problems:***

1. Space has no walls (obviously) - how to restrict movement?
2. No movement restrictions - no doors.
3. No doors, no interesting mechanics of opening them.
4. No backtracing (for example after acquiring new power at the end that enables access to a place at the beginning of the dungeon).

***More info:*** The Legend of Zelda: Oracle of Ages and Seasons' dungeon design \- to see how some Zelda games do it.

The dungeon should be in 1 star system.

The EVE Online example is a good one, in the sense that it has been done before and it works, but for me it always somehow felt like cheating because in EVE you can travel anywhere... but not to a pocket of space right behind the dungeon gate. Even if you had a bookmark there.

And since my game will most likely feature even more free-form travel then EVE (think Elite: Dangerous) then what I'm saying is I'm looking for something that could improve that can be found in EVE.

# Answer
> 99 votes
Level designers I've spoken with often lament how difficult it is to create interesting challenges & spaces in open areas, so you've definitely set a hard problem for yourself.

That said, the core structure of something like a Zelda dungeon is often about finding a number of MacGuffins (items required to progress) or switches (locations where you modify some dungeon state) in a particular sequence. And so even without walls, you can still **introduce structure via the dependency graph of these actions**.

Let's run through an arbitrary example (which may not directly align to your gameplay or fiction):

* The player wants to get to a warp gate to go to the next space sector (something to act as an end goal, you can replace this with whatever...)

+ Because there's no walls, they can just fly up to it, so we have it begin in a powered-off state to put some challenge in their way.
* To activate it they'll need to turn on three power-beaming stations around the map.
* One station is missing an energy crystal, so they need to go to a nearby asteroid field to collect one.
* Another station has a turret that keeps you from getting close. The player needs to go back to the asteroid field and tow an asteroid they can use as a shield.
* The final station is damaged, but the spare parts to fix it are in locked chests at the other two stations. The player collects a maintenance key at this station that lets them access the chests.
* spare parts collected, they can return to the third station, repair it, then head to the warp gate to escape (and maybe fight the space monster boss lured to it by all the activity)

This lets us construct a reasonably interesting dependency graph without a hard wall that blocks the player anywhere, and gives them cause to re-visit a few previously explored areas in a new context.

Here the variety of interactions has to take up some of the slack left by variety of spatial layouts & approach, since we have fewer tools in open space to control the latter. (Though that doesn't preclude you from introducing constrained spaces at key sites along the graph, like big space stations or wrecks the player needs to navigate into through a controlled number of doors - I avoided such cases above just to show you can get interesting dependency relationships without always going to interior spaces)

The other side of this challenge is **landmarking.** It's extremely easy to get lost and disoriented in space. If the player is to feel like they're purposefully solving challenges, rather than just chasing a waypoint, you'll need to give them tools to understand where they are and let them plan.

In the example above, we led the player to the asteroid field landmark to find the energy crystal, which ensured they knew it was there when they later needed an asteroid (or vice versa). Coming back to a recognizably familiar landmark like that, with a new purpose in mind, can really help a scenario feel like a space the player is exploring and mastering, rather than a sequence of arbitrary roadblocks.

Consider using things like gassy nebulae, debris fields, space stations, planets, etc. to give players these kinds of landmarks they can recognize.

# Answer
> 6 votes
One thing you could do is place derelict space ships and space stations into the game. When large enough they can be explored with a small one-person space ship. Puzzles requiring backtracking can be implemented by alien machines which need to be activated in order to open paths.

Another option are large asteroids with elaborate cave systems in them to explore. These might also contain derelict alien artifacts or abandoned mining equipment the player needs to interact with in order to progress. You might want to take a look at the Descent series for inspiration.

When your player controls a space ship which is far larger than a one-person fighter, you could build dungeons from asteroid fields or hazardous nebula which can only be navigated through narrow paths. Yes, this is extremely implausible from a hard-science perspective, but it's a sci-fi trope which is so common it's usually accepted by the audience. Backtracking can be enabled by having the player acquire weapons which can destroy certain kinds of asteroids or protection equipment which allows them to pass through certain kinds of nebula clouds.

# Answer
> 3 votes
If you are creating a fly-around-free in outer space as if you where in an airplane game you are almost certainly bending science so far that the game is fantasy.

So make up spacey things that act as barriers. So long as they are spacey, you should be fine.

Asteroid fields so dense that you'll be destroyed going through them, with a path through it that is free of debris. Maybe that path is described through nav beacons, maybe it is kept clear by mining robots, whatever.

Or nebula. Or swarms of planets. Or space geese. Or force fields. Or lazer beams in a gravitationan nexus. Or space grues.

All science fantasy, but so are the engines of the spaceship used in every space-like game I've ever played short of KSP.

If you want technobabble (why don't see seem them now?), take whatever handwavium you use to make your engines and tie them to the new space fantasy elements.

The engines used to travel around space as if you where in an airplane (your thrusters) cause temporal anomolies / gravitational eddies / random babble. That changes the nature of space from the current "well, really, nothing here" to whatever random excuse you need to make "dense" terrain for your gameplay.

So, suppose a gravitational "knot" that has caused a asteroid belt cluster with nebula.

The 3d maze you can navigate through is the first wave. You have to go to various spots in the maze, defeat various foes. (The maze is a home for pirates, or whatever foe you want players to fight. And maybe space monsters, because that is spacey. The space monsters can have ~~magic~~ gravitational powers.)

There can be parts with dense asteroid fields or whatever. Picking up navigational solutions to these swarms can let you fly through them. Or upgrading your ship with a streamlined "frictionless" surface can let you penetrate some "nebulas". Or narrow choke points defended by automated defences or "force fields" that you have to deactivate.

You could so this on a large scale. Suppose that the disaster that resulted from the activation of the experimental reactionless drive destroyed entire planets and shoved the debris into a shell, locked there by the gravitational knot. (Enough technobabble?). This was later used as weapons, destroying planet after planet. Only some planets have survived, and since then a defence has been developed. The existing shells are still out there, and civilization has taken hold in them. Navigating between them is free-space, but in them it is a set of 3d maze like paths.

# Answer
> 3 votes
After the OP's reply to my earlier answer, I now understand the question better. :) So, in "open space", you need a reason not to go in a certain direction. If you want to recreate walls, all you need is a HUD representation of hazards and a reason for the player not to cross into the hazardous areas (or at least to have some risk of harm in those areas), and you've got your walls. They don't really exist, but cross them and you die instantly.

Asteroid fields in reality aren't very dense. However if you're orbiting a planet/moon/asteroid, a small bit of fraction-of-C shrapnel intersecting your orbit could really spoil your day (see *Gravity*). Your HUD could represent this as a tube circling the planet with a "ball" in the tube showing where the shrapnel is. Now you've got a "hazard wall" which they're best avoiding, as well as a HUD representation of instant death coming towards them.

Lasers don't have a range as such - what they have is a certain amount of decoherence over distance. The further you are from them, the less each hit will hurt, and there'll be some range where it doesn't really have any effect. So each laser emplacement has a solid sphere of "you die here", shading out to nothing as you get out of its ability to hurt. Again, you've got a hazard wall, this time deepening in hazard as you get closer.

For all anti-ship weapons, you can't be hit if they don't know you're there; and as the king of a space castle you wouldn't want your death rays frying your own ships by accident. So every emplacement will have a detection threshold for where it can identify incoming ships and consider engaging them. If you're trying to sneak into somewhere, your HUD will need to show all the detection "walls" which you need to avoid. For bonus tactical points, your ship might get quieter if you turn off shields/weapons, so you can sneak in more easily if you're completely defenseless when someone spots you.

Or conversely, if you're defending an asteroid against incoming enemies, then you might want to *not* go outside the HUD representation of your emplacement's lasers. Your emplacement might not be able to shoot down the enemy ships itself, but it could still take out anti-ship missiles. So within laser range of the asteroid you have some protection against missiles; outside laser range you're a lot more at risk.

All of this is going to limit where you can go. I have to be clear though, this will limit where you can go ***in a 3D way***. Anyone who played games in the 90s will remember the difference between *Doom* and *Descent*, when suddenly you had to remember maps in 3D with no obvious up or down. Don't fall into *Wrath of Khan*'s "two-dimensional thinking" trap.

# Answer
> 2 votes
As I don't know anything about your game, I don't know if this answer fits your problem; but I will give it a try. You can make a level a complete star system (or even a galaxy depending on the size of your gameplay). From one star system to another you cannot travel to the next, because there are lightyears between them. So you can make the player fly "out of the level" and simply never arriving anywhere, because it would simply take years to arrive somewhere.

The doors which enable you to get to another level aka star system is then a black hole/warp point/whatever fits which enables instant travel. If it is technology based you can insert a mechanic to act like keys to activate.

If this is too big for the scope of what you have planned you could go down to a level being the orbit of one planet. The player could not be able to leave this orbit because the gravity is too strong. A door could then be either a new technology, special fuel or the same portals from above. With the latter two options backtracking should be easy to integrate.

Hope one of these ideas helps you.

# Answer
> 2 votes
# Restrict movement with resources

Rather than trying to actually block the path of the ship, just make sure they need to have access to resources frequently to keep going.

* They need to refuel uranium/food/water frequently, or perhaps even gather different fuel components in a specific order
* There is an infrastructure which provides laser beams, whose energy they need most of the time to power the engines
* They need to consider their angle to the sun to keep the solar sails/panels working properly.

If you don't want to change your whole game for this, just introduce some 'problems' in certain areas. For example space radiation that disables regular engines, or a crappy wormhole that squeezes you a bit on arrival.

# Additonal random ideas

* They need the gravity of objects to change course (or perhaps even tag along with a comet to move at all)
* They are getting chased by baddies and need to lose them by manouvering near obstacles
* In an open area, they still need to manouvre carefully to avoid radiation overdose

# Answer
> 2 votes
The space sim Freelancer had **trade lanes** \- these offered fast travel between points of interest within a star system.

> Note the light-blue lines are trade lanes

It's an interesting mechanic; while players are usually unrestricted and can fly anywhere, taking the trade lanes is much more attractive, as you get around in a fraction of the time - from memory, it takes 10-20 minutes to cross the breadth of a typical map without the lanes. So in practice, the trade lanes create a map layout, which you can use to lead your players to landmarks, points of interest, and even risky situations.

# Answer
> 1 votes
Take Deadspace as an example. The game had open space environments, however the areas were restricted in the form of clustered "debris fields". If you venture too far out there wouldn't be any oxygen tanks, thus the player would die. It looked large, but it was restricted to linear ideal paths.

# Answer
> 0 votes
Depending on the % of realism you want, just solve the problem and actually do walls. An old space RTS i know (Conquest: Frontier Wars) is doing just that (battle occurs on 2D plane). They invented streams of whatever science stuff who justs act as impenetrable walls (no light of sight and no passing through).

# Answer
> -2 votes
Warhammer 40K invented the "space hulk", and a game of that name which is basically a rip-off of *Aliens*. Doors are kind of optional there - what matters is lots of creepy corridors in a derelict (but ***not*** uninhabited!) drifting spaceship. This is very much a "dungeon crawl", but in a sci-fi setting with a sci-fi justification for why it looks like that. Can you do the same?

---
Tags: 3d, game-design, level-design
---


# Question
Title: How can i put a skybox on a new layer with a new camera and then move the skybox?
I want to create a moving start effect. For example the space station is moving around the star or moving to the star. But instead moving the space station i think it will be better to make effect of the skybox moving.

I have in the Hierarchy a RigiBbodyFPSController and a child MainCamera. Now i added a new Camera to the Hierarchy.

Now how do i make the rest ? Moving the new camera and the skybox to new layer and move the skybox ? Or it's more logic to say to move the new camera that the skybox is with in it in the new layer.

Not sure if my idea is logic or if there are a better ways to do it. The general idea is to make movement effect like the space station is moving around the star or to the star. Star i mean the skybox.

The skybox is on the right. I can't see the skybox in the scene view i see it only when running the game in the game view.

This is a screenshot when the game is running then i can see the skybox in scene view and game view:

# Answer
> 1 votes
If you want to rotate or move your skybox which can be possible by calling renderSettings

```
    RenderSettings.skybox.SetFloat ("_Rotation", Time.time *speed );

```

or if you want to change your skybox each time interval use insideout shader which you can get it

https://github.com/maazirfan/InsideOut-Shader-Unity

and link it with sphere using material, add your skybox texture in it. and change that sphere by each interval,scale it as much that your rest of models will fit in and look like skybox.that might help you in your project

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


# Question
Title: Is there a term for an incorrect interpretation of game memory?
In Prince of Persia, using cheats in certain rooms can access "secret" rooms with strange graphics, like in this video. This effect is caused by the game referencing parts of memory which are invalid or containing garbage. For games running on MS-DOS with little bounds checking and no virtualisation, such memory access doesn't result in a crash, but in the game trying to interpret it as a valid and relevant memory instead.

If the data doesn't cause any other crash (e.g. divide by zero), the game might interpret the memory as an entirely new location in the game (room, level), possibly even with new graphics (with "random" pixels) or enemies.

I would like to know how this effect of misintepreting incorrect parts of memory as valid game locations is called.

The affected games that I know about:

* Prince of Persia, using cheats or modified rooms to enter undefined rooms with weird tiles or enemies.
* Commander Keen 4, saving with the viewport near the level edge displays garbage graphics after subsequent load.
* Dangerous Dave, entering a non-existing warp zone displays parts of other levels or weird tiles.

I am also curious about other games where this can be found.

# Answer
One source for such bugs can be a buffer over-read. A bug in your program reads beyond the boundaries of an allocated array, so it reads whatever is stored beyond it.

Another possible source is use after free. The program tells the runtime environment to deallocate the memory a pointer points to, but still keeps a pointer to it around. The runtime then allocates something else to that supposedly no longer used memory. When the program later reads data from the pointer, it reads whatever is now stored there but interprets it in the context of the pointer.

The bug in *Commander Keen* might be uninitialized variables. When you create a new variable and don't assign any value to it, most programmers intuitively assume that that data will be empty (full of 0's). With many modern high-level programming languages, that's in fact the case. But with many older or more low-level languages, the data will be filled with whatever was there in memory before. So when you forget to write to allocated data before reading from it, you might find strange things in there. The programmer of Commander Keen likely allocated an array as large as the screen to store the tiles currently on-screen, but then stopped writing to it when the border of the map was reached. So the off-level portion of the screen stayed uninitialized.

---

You might wonder why you see such glitches so rarely in modern games. The reason is that while these glitches are quite interesting in the context of a game, they can have disastrous consequences in any software where security and/or correctness matters. So the software development community (beyond game development) has put considerable effort into making them a thing of the past.

* The memory managers of operating systems try to detect and prevent such unusual memory access patterns, usually by crashing the program ("segmentation fault").
* With multitasking operating systems there are multiple processes allocating and deallocating memory. The memory management of the operating system is a lot more sophisticated and hence less predictable than in a single-task operating system like DOS. That means if such bugs occur and do something interesting, you might not be able to reproduce it.
* High level programming languages like C# with bound checking, garbage collection and implicit variable initialization built in are raising in popularity among game developers. With such languages, the above bugs are no longer that easy to create accidentally.
* And even the low-level programming languages like C/C++ have evolved in the past 30 years. This applies to both the language features themselves and to the best practices used by developers.
> 3 votes

# Answer
Glitching:

> Glitching is an activity in which a person finds and exploits flaws or glitches in video games to achieve something that was not intended by the game designers. Gamers who engage in this practice are known as glitchers. Glitches can help or disable the player.

Note: not everyone is going to necessarily associate this particular definition with this term. In general, I'd argue that most all non-game development software engineers would use glitch as a synonym for error or bug. For instance, the wikipedia definition for computer glitch reads:

> A computer glitch is the failure of a system, usually containing a computing device, to complete its functions or to perform them properly.
>
> In public declarations, glitch is used to suggest a minor fault which will soon be rectified and is therefore used as a euphemism for a bug, which is a factual statement that a programming fault is to blame for a system failure.
>
> It frequently refers to an error which is not detected at the time it occurs but shows up later in data errors or incorrect human decisions.

Even among game development practitioners, usage will probably be mixed. Due to the ambiguation, it would probably be wise to establish your usage / context rather than assume a shared vocabulary. But if you're just interested searching on it for yourself, start with glitch level & glitch run.
> 1 votes

---
Tags: terminology
---


# Question
Title: Alternatives to Prototype pattern for Buildings
Hope some of you have ideas for this. first I will describe the Task ahead and then go on with the my thoughts about solving it and what kind of problems I see.

1) I have a number of buildings. Their data is stored in a json file and contains stuff like name, price, maxHP, etc... all those static infos - This file can be changed or extended by additional types of buildings and my system should take them all, as long as there are no invalid data (negative health for example)

2) I need some kind of list of all buildings, that I can use to iterate over (for example to display all buildings in a build-menu)

3) I need to be able to place them somewhere and therefore create concrete instances of them in my gameworld

basically buildings can do different stuff in my game. they can create units, generate income, attack and other stuff.

my thoughts about solving it:

1) On loading my building.json, first the allowedActions of this building are looked at and the various components are added (e.g weapon component for shooting stuff) and then the actual data (like hp, damage, etc) is set and validated.

2) Currently to get a list of all my buildings and being able to place them somewhere, I do the following. on loading buildings, I actually create an instance of each of them in order to get a List of prototypes - this prototype list is then used everywhere, where I need to be able to iterate over them, e.g. buildmenu.

3) When I then want to build it, I kind of just clone this building and update the data specific to the new clone (e.g. its actual position) and add it to my game world

So basically I'm using some kind of prototype pattern, if I understood it correct. However I don't really feel comfortable to have a list of instances of my buildings that in reality don't exist in my gameworld and for which I always have to care, that they don't ever influence the actual game (like accidently they are iterated through in a list, when I want to do something to all currently constructed buildings in my game but this will also influence the prototypes, which i clone my buildings from but are not actually constructed)

Do you have other Ideas to solve this, or is using prototypes here the right thing to do?

Thanks for any advice Kind Regards

# Answer
> 1 votes
If you're uncomfortable with having building instances that aren't physically present on your map (though as pointed out above, this works fine and there's nothing "wrong" with doing it this way), you're only a few small changes away from using the Type Object Pattern instead.

Here the data you're storing in your JSON/iterating in your menus no longer represent "Buildings," but "Building Types." This contains only the information common to all buildings of that type:

* max HP
* cost
* visual asset
* actions it can perform

but no instance-specific data.

Then you have a separate type for your Building instances themselves, which *reference* their buildingType and add data that's specific to structures built somewhere in your world:

* building type
* position
* controlling faction
* current HP
* action components

Now you don't have to worry about accidentally writing code that's supposed to iterate one of these but feeding it the wrong list. The data has a completely different makeup, so strict type checking will catch this error immediately, and even with dynamic typing the problem should become obvious very quickly.

You'd move the step of attaching components to the instance to the moment when the building is placed in the world (since unbuilt building archetypes in your menus have no need of these components.

You could even extend this to additional types for other systems that need different views of building type data, like a BuildingButton type with disabled/cooldown state tracking to use in your menus, or a BuildingOption type that annotates the building type with info an AI player uses to select what to build when & where. Each of these still refer back to the same set of BuildingType instances for the core of the building's description, so that no one type has to handle all of these different use cases.

---
Tags: design-patterns
---


# Question
Title: What exactly is the "blend factor" t in Color.Lerp?
I had a bit of a look around and couldn't see anywhere this was addressed, my apologies if it has been.

In Color.Lerp, I understand that the 3rd parameter t is not in fact the time that it takes to change between the colors but is rather the "blend factor". If the first color is at 0 and the second is at 1, then a blend factor of e.g. 0.2 would indicate it is closer to the first than the second.

My confusion is this - how exactly is it determined how long it takes the lerp to occur? I assume it's something to do with the frames per second? e.g. if the blend factor is 0.001 and frames per second are 50, with lerp in the update function then it should take 0.001 * 50 = 0.05 of a second for the change to occur?

# Answer
> 3 votes
The other answers correctly explain how the parameter works when you're using it something like this:

```
progress = Mathf.Clamp01(progress + Time.deltaTime/fadeDuration);
currentColor = Color.Lerp(startColor, endColor, progress);

```

But there's another common way to use Lerp that you might have seen (and your reference to a blend factor of 0.001 affecting the speed suggests to me that this might be the one you're using):

```
currentColor = Color.Lerp(currentColor, targetColor, sharpness);

```

This style is one we might call an Exponential Moving Average or Exponential Ease-Out. The change in colour starts quickly (if our sharpness were 0.5, we cover half the distance in the very first update), then gets slower and slower as we get closer to the target (our next updates move 1/4, 1/8, 1/16th of the original difference)

In pure math terms, this type of blend never actually finishes - it approaches the target asymptotically, but no finite number of iterations is enough to make `currentColor` equal to `targetColor`

On real computers, we have only finite precision, so the blend will eventually stop because the remaining difference rounds to zero (or is too small for the player to perceive).

For colours, we can estimate this time by figuring out how many iterations it would take to reduce an initial difference of 1.0f (the difference between full black and full white in colours normalized to the 0-1 range) to 0.5/255 (the smallest deviation from a colour that will round to a new 8-bit colour value for displaying on a conventional monitor)

$$\begin{align} (1 - sharpness)^{iterations} &= \frac 1 {2 \times 255}\\ iterations &= log\_{(1 - sharpness)}\left(\frac 1 {510} \right) \\ iterations &= \frac {log\left(\frac 1 {510}\right)} {log(1 - sharpness)} \\ duration = iterations \times \text{frames per second} &= \frac {log\left(\frac 1 {510}\right)} {log(1 - sharpness)} \times fps \end{align}$$

So for your example of 0.001 for the `sharpness` parameter, it could take around 6200 iterations before the colour would stop changing, or around 124 seconds at 50 fps.

Granted, most of the change happens very quickly. Half the change happens in the first 14 seconds, and 95% of the change is done in the first minute. But exponential ease has a loooong tail. ;)

# Answer
> 2 votes
That's up to you and your needs.

Lerping can be based on time but it could also be used in order situations with other factors, for instance: how close is the player from the objective? You could want to lerp from red to green. In this case, the `t` parameter would be computed like such (pseudo-code):

```
departurePosition
endPosition
currentPosition

totalDistanceToGo = (endPosition - departurePosition).lenght
distanceLeftToGo = (endPosition - currentPosition).lenght

ratioDone = clamp(0, 1, distanceLeftToGo/totalDistanceToGo)

colourUsed = Color.Lerp(Color.red, Color.green, ratioDone);

```

If you need to lerp on time, you'd have to set in advance over what period you'd like to lerp, then use this value and the frame time to determine `t` (pseudo-code):

```
totalDurationInSec = 3
timeAccForLerp = 0
lerpedColour

function Update() {
   timeAccForLerp += Time.deltaTime
   timeAccForLerp = clamp( 0, totalDurationInSec, timeAccForLerp )
   lerpedColour = Color.Lerp(Color.red, Color.green, timeAccForLerp/totalDurationInSec);
}

```

---
Tags: unity, c#, color, lerp
---


# Question
Title: Implement resolution scaling HTML5 canvas
I'm building an hmtl5 real time game using socket.IO and node.js. If you've heard of the classic game "pong", I'm going for that. When you consider the gameplay for this game, it becomes apparent that resolution scaling is something I'll have to implement. I'm running one instance of the game on the server (no graphics rendering, only physics), and of course once for every client. Each client's canvas is the size of the browser window so could be any resolution.

What I'm wondering is how I should keep track of positions, velocities, etc. in the core game code. Should I use percentages and then multiply them by the respective screen sizes? Like `x = 0.5` to store a position halfway across the screen? What's the best/standard way of doing this? Thanks so much.

# Answer
> 1 votes
You have an authoritative server. That server has no screen, so it doesn't make sense to use pixel-measurements in your game mechanics code. So you should make up a coordinate system which works for you. There are countless ways to handle this. The upper left corner of the play area could be `0.0`:`0.0` while the lower right is `1.0`:`1.0`. Or the origin could be in the center with the play area stretching from `-1.0`:`-1.0` to `1.0`:`1.0`. It really doesn't matter that much where you put the origin as long as it seems plausible for you.

When the clients visualize the game, they need to convert the game-coordinates to screen-coordinates. You can that quite elegantly by setting `context.scale` and `context.translate` so the visual coordinate system is the same as your logical.

---
Tags: javascript, html5, resolution, node.js
---


# Question
Title: Why do engines need to be optimized for new processors of the same architecture?
When a new processor generation is released, most websites report that game engines and programs need to be optimized for the new hardware. I do not quite understand why. A processor usually has an architecture that defines what kind of instruction set it uses. The one we all use nowadays is amd\_x86\_64 . Why would any program or compiler need to be updated if all processors use this same architecture? Surely there are features WITHIN the pipeline of the new processor that optimizes the execution of machine code, but why would the machine code itself need to be changed if the architecture did not?

# Answer
**Because different *generations* of the same architecture can have different instruction sets**.

For example, Streaming SIMD Extensions are probably the best-known x86 instruction set, but yet, and despite there just being one x86 architecture, there exists SSE, SSE2, SSE3, and SSE4.

Each of these generations can include new instructions that provide faster ways of performing certain operations. An example that would be relevant to games might be dot product instructions.

So if a game engine is compiled for a previous generation of an architecture, it will not have support for these newer instructions. Similarly, it may be necessary to optimize the engine for newer instructions; SSE4, for example, has support for dot product instructions that work on array-of-structs data. An optimization that could take advantage of these newer instructions would be to change your data layout to array-of-structs.
> 53 votes

# Answer
Maximus's answer is correct, I just want to give another piece of the story:

The hardware itself changes in a way you need to change how you code, regardless of newly introduced instructions.

* Increased or decreased amounts of cache means you need to worry less or more about cache optimization/cache invalidation being issues. More cache means with small data you can focus less on making sure data is contiguous with out running into performance concerns. Less cache means this could be an issue, and very little cache means with some large data structures it won't matter any way.
* New levels of cache means you need to think more about how you organize even larger sets of data (L1, vs L2, vs L3 vs L4).
* More cores means you need to think about how you are going to multi thread applications better, and how your application scales in a multi process environment.
* Faster clocks means you need to start thinking about memory latency more than you need to think about CPU computation speed as a bottleneck of your system.
* The number of FPUs on a system may no longer match the number of integer ALUs per core any more (AMD had/has architectures like this).
* The number of clock cycles it takes to compute an operation my have decreased, or increased.
* The number of registers available changed.

All of these have very real performance impact on programs which made assumptions about underlying architecture in previous hardware with the same ISA, either positive or negative.
> 37 votes

# Answer
Even beyond gross changes like support for new instructions, microprocessor manufacturers are constantly modifying their designs to improve performance, and every new design can have different *relative* performance for each instruction or technique. Maybe you wrote some carefully optimized branchless code for the Model X, but the Model Y has an improved branch-predictor that reduces the misprediction penalty for the non-branchless version of the code (which also frees up a register to be used somewhere else). Maybe the Model Y supports greater parallelism of a certain high-latency instruction, so that now an unrolled loop of that instruction gets you better throughput, while on the Model X a shorter sequence was better.

Any problem can be solved in many ways, and every program is an interlocking collection of trade-offs and resource allocations, from the point of optimization. Even small changes in the availability of those resources or the cost of a given piece of code in terms of those resources, can have a cascade effect that gives a substantial performance advantage to one piece of code or another. Even if an upgraded chip has "more of everything", how *much* more of each thing can swing the balance.
> 2 votes

---
Tags: hardware, cpu
---