title: blur and gray shader

text:
# Question
Title: blur and gray shader
I'm new to shaders. I am trying to combine the blur shader and the grayscale shader. Here's what I have came up with so far:

```
Shader "Custom/blur_and_gray" {
 Properties {
        _Color ("Main Color", Color) = (1,1,1,1)
        _BumpAmt  ("Distortion", Range (0,128)) = 10
        _MainTex ("Tint Color (RGB)", 2D) = "white" {}
        _BumpMap ("Normalmap", 2D) = "bump" {}
        _Size ("Size", Range(0, 20)) = 1
        _MainTex ("Texture", 2D) = ""

    }

    Category {

        // We must be transparent, so other objects are drawn before this one.
        Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Opaque" }
     ZWrite Off
    Blend SrcAlpha OneMinusSrcAlpha

        SubShader {

            // Horizontal blur
            GrabPass {
                Tags { "LightMode" = "Always" }
            }
            Pass {
                Tags { "LightMode" = "Always" }

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

                struct appdata_t {
                    float4 vertex : POSITION;
                    float2 texcoord: TEXCOORD0;
                };

                struct v2f {
                    float4 vertex : POSITION;
                    float4 uvgrab : TEXCOORD0;
                };

                v2f vert (appdata_t v) {
                    v2f o;
                    o.vertex = UnityObjectToClipPos(v.vertex);
                    #if UNITY_UV_STARTS_AT_TOP
                    float scale = -1.0;
                    #else
                    float scale = 1.0;
                    #endif
                    o.uvgrab.xy = (float2(o.vertex.x, o.vertex.y*scale) + o.vertex.w) * 0.5;
                    o.uvgrab.zw = o.vertex.zw;
                    return o;
                }

                sampler2D _GrabTexture;
                float4 _GrabTexture_TexelSize;
                float _Size;

                half4 frag( v2f i ) : COLOR {
//                  half4 col = tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(i.uvgrab));
//                  return col;

                    half4 sum = half4(0,0,0,0);

                    #define GRABPIXEL(weight,kernelx) tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(float4(i.uvgrab.x + _GrabTexture_TexelSize.x * kernelx*_Size, i.uvgrab.y, i.uvgrab.z, i.uvgrab.w))) * weight

                    sum += GRABPIXEL(0.05, -4.0);
                    sum += GRABPIXEL(0.09, -3.0);
                    sum += GRABPIXEL(0.12, -2.0);
                    sum += GRABPIXEL(0.15, -1.0);
                    sum += GRABPIXEL(0.18,  0.0);
                    sum += GRABPIXEL(0.15, +1.0);
                    sum += GRABPIXEL(0.12, +2.0);
                    sum += GRABPIXEL(0.09, +3.0);
                    sum += GRABPIXEL(0.05, +4.0);

                    return sum;
                }
                ENDCG
            }

            // Vertical blur
            GrabPass {
                Tags { "LightMode" = "Always" }
            }
            Pass {
                Tags { "LightMode" = "Always" }

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

                struct appdata_t {
                    float4 vertex : POSITION;
                    float2 texcoord: TEXCOORD0;
                };

                struct v2f {
                    float4 vertex : POSITION;
                    float4 uvgrab : TEXCOORD0;
                };

                v2f vert (appdata_t v) {
                    v2f o;
                    o.vertex = UnityObjectToClipPos(v.vertex);
                    #if UNITY_UV_STARTS_AT_TOP
                    float scale = -1.0;
                    #else
                    float scale = 1.0;
                    #endif
                    o.uvgrab.xy = (float2(o.vertex.x, o.vertex.y*scale) + o.vertex.w) * 0.5;
                    o.uvgrab.zw = o.vertex.zw;
                    return o;
                }

                sampler2D _GrabTexture;
                float4 _GrabTexture_TexelSize;
                float _Size;

                half4 frag( v2f i ) : COLOR {
//                  half4 col = tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(i.uvgrab));
//                  return col;

                    half4 sum = half4(0,0,0,0);

                    #define GRABPIXEL(weight,kernely) tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(float4(i.uvgrab.x, i.uvgrab.y + _GrabTexture_TexelSize.y * kernely*_Size, i.uvgrab.z, i.uvgrab.w))) * weight

                    //G(X) = (1/(sqrt(2*PI*deviation*deviation))) * exp(-(x*x / (2*deviation*deviation)))

                    sum += GRABPIXEL(0.05, -4.0);
                    sum += GRABPIXEL(0.09, -3.0);
                    sum += GRABPIXEL(0.12, -2.0);
                    sum += GRABPIXEL(0.15, -1.0);
                    sum += GRABPIXEL(0.18,  0.0);
                    sum += GRABPIXEL(0.15, +1.0);
                    sum += GRABPIXEL(0.12, +2.0);
                    sum += GRABPIXEL(0.09, +3.0);
                    sum += GRABPIXEL(0.05, +4.0);

                    return sum;
                }
                ENDCG
            }

            // Distortion
            GrabPass {
                Tags { "LightMode" = "Always" }
            }
            Pass {
                Tags { "LightMode" = "Always" }

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

                struct appdata_t {
                    float4 vertex : POSITION;
                    float2 texcoord: TEXCOORD0;
                };

                struct v2f {
                    float4 vertex : POSITION;
                    float4 uvgrab : TEXCOORD0;
                    float2 uvbump : TEXCOORD1;
                    float2 uvmain : TEXCOORD2;
                };

                float _BumpAmt;
                float4 _BumpMap_ST;
                float4 _MainTex_ST;

                v2f vert (appdata_t v) {
                    v2f o;
                    o.vertex = UnityObjectToClipPos(v.vertex);
                    #if UNITY_UV_STARTS_AT_TOP
                    float scale = -1.0;
                    #else
                    float scale = 1.0;
                    #endif
                    o.uvgrab.xy = (float2(o.vertex.x, o.vertex.y*scale) + o.vertex.w) * 0.5;
                    o.uvgrab.zw = o.vertex.zw;
                    o.uvbump = TRANSFORM_TEX( v.texcoord, _BumpMap );
                    o.uvmain = TRANSFORM_TEX( v.texcoord, _MainTex );
                    return o;
                }

                fixed4 _Color;
                sampler2D _GrabTexture;
                float4 _GrabTexture_TexelSize;
                sampler2D _BumpMap;
                sampler2D _MainTex;

                half4 frag( v2f i ) : COLOR {
                    // calculate perturbed coordinates
                    half2 bump = UnpackNormal(tex2D( _BumpMap, i.uvbump )).rg; // we could optimize this by just reading the x  y without reconstructing the Z
                    float2 offset = bump * _BumpAmt * _GrabTexture_TexelSize.xy;
                    i.uvgrab.xy = offset * i.uvgrab.z + i.uvgrab.xy;

                    half4 col = tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(i.uvgrab));
                    half4 tint = tex2D( _MainTex, i.uvmain ) * _Color;

                    return col * tint;
                }
                ENDCG
            }

            // gray
            GrabPass {
                Tags {"Queue"="Transparent"}
            }Pass {
                Tags {"Queue"="Transparent"}
                CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag
                struct v2f {
                    float4 position : SV_POSITION;
                    float2 uv_mainTex : TEXCOORD;
                };

                uniform float4 _MainTex_ST;
                v2f vert(float4 position : POSITION, float2 uv : TEXCOORD0) {
                    v2f o;
                    o.position = UnityObjectToClipPos(position);
                    o.uv_mainTex = uv * _MainTex_ST.xy + _MainTex_ST.zw;
                    return o;
                }

                uniform sampler2D _MainTex;
                fixed4 frag(float2 uv_mainTex : TEXCOORD) : COLOR {
                    fixed4 mainTex = tex2D(_MainTex, uv_mainTex);
                    fixed4 fragColor;
                    fragColor.rgb = dot(mainTex.rgb, fixed3(1.222, 1.707, 1.071));
                    fragColor.a = mainTex.a;
                    return fragColor;
                }
                ENDCG
            }
        }
    }
}

```

The problem with this code is that it's giving me only a white texture. here are the shadera I am using **BLUR**

```
Shader "Custom/SimpleGrabPassBlur" {
    Properties {
        _Color ("Main Color", Color) = (1,1,1,1)
        _BumpAmt  ("Distortion", Range (0,128)) = 10
        _MainTex ("Tint Color (RGB)", 2D) = "white" {}
        _BumpMap ("Normalmap", 2D) = "bump" {}
        _Size ("Size", Range(0, 20)) = 1
    }

    Category {

        // We must be transparent, so other objects are drawn before this one.
        Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Opaque" }

        SubShader {

            // Horizontal blur
            GrabPass {
                Tags { "LightMode" = "Always" }
            }
            Pass {
                Tags { "LightMode" = "Always" }

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

                struct appdata_t {
                    float4 vertex : POSITION;
                    float2 texcoord: TEXCOORD0;
                };

                struct v2f {
                    float4 vertex : POSITION;
                    float4 uvgrab : TEXCOORD0;
                };

                v2f vert (appdata_t v) {
                    v2f o;
                    o.vertex = UnityObjectToClipPos(v.vertex);
                    #if UNITY_UV_STARTS_AT_TOP
                    float scale = -1.0;
                    #else
                    float scale = 1.0;
                    #endif
                    o.uvgrab.xy = (float2(o.vertex.x, o.vertex.y*scale) + o.vertex.w) * 0.5;
                    o.uvgrab.zw = o.vertex.zw;
                    return o;
                }

                sampler2D _GrabTexture;
                float4 _GrabTexture_TexelSize;
                float _Size;

                half4 frag( v2f i ) : COLOR {
//                  half4 col = tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(i.uvgrab));
//                  return col;

                    half4 sum = half4(0,0,0,0);

                    #define GRABPIXEL(weight,kernelx) tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(float4(i.uvgrab.x + _GrabTexture_TexelSize.x * kernelx*_Size, i.uvgrab.y, i.uvgrab.z, i.uvgrab.w))) * weight

                    sum += GRABPIXEL(0.05, -4.0);
                    sum += GRABPIXEL(0.09, -3.0);
                    sum += GRABPIXEL(0.12, -2.0);
                    sum += GRABPIXEL(0.15, -1.0);
                    sum += GRABPIXEL(0.18,  0.0);
                    sum += GRABPIXEL(0.15, +1.0);
                    sum += GRABPIXEL(0.12, +2.0);
                    sum += GRABPIXEL(0.09, +3.0);
                    sum += GRABPIXEL(0.05, +4.0);

                    return sum;
                }
                ENDCG
            }

            // Vertical blur
            GrabPass {
                Tags { "LightMode" = "Always" }
            }
            Pass {
                Tags { "LightMode" = "Always" }

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

                struct appdata_t {
                    float4 vertex : POSITION;
                    float2 texcoord: TEXCOORD0;
                };

                struct v2f {
                    float4 vertex : POSITION;
                    float4 uvgrab : TEXCOORD0;
                };

                v2f vert (appdata_t v) {
                    v2f o;
                    o.vertex = UnityObjectToClipPos(v.vertex);
                    #if UNITY_UV_STARTS_AT_TOP
                    float scale = -1.0;
                    #else
                    float scale = 1.0;
                    #endif
                    o.uvgrab.xy = (float2(o.vertex.x, o.vertex.y*scale) + o.vertex.w) * 0.5;
                    o.uvgrab.zw = o.vertex.zw;
                    return o;
                }

                sampler2D _GrabTexture;
                float4 _GrabTexture_TexelSize;
                float _Size;

                half4 frag( v2f i ) : COLOR {
//                  half4 col = tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(i.uvgrab));
//                  return col;

                    half4 sum = half4(0,0,0,0);

                    #define GRABPIXEL(weight,kernely) tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(float4(i.uvgrab.x, i.uvgrab.y + _GrabTexture_TexelSize.y * kernely*_Size, i.uvgrab.z, i.uvgrab.w))) * weight

                    //G(X) = (1/(sqrt(2*PI*deviation*deviation))) * exp(-(x*x / (2*deviation*deviation)))

                    sum += GRABPIXEL(0.05, -4.0);
                    sum += GRABPIXEL(0.09, -3.0);
                    sum += GRABPIXEL(0.12, -2.0);
                    sum += GRABPIXEL(0.15, -1.0);
                    sum += GRABPIXEL(0.18,  0.0);
                    sum += GRABPIXEL(0.15, +1.0);
                    sum += GRABPIXEL(0.12, +2.0);
                    sum += GRABPIXEL(0.09, +3.0);
                    sum += GRABPIXEL(0.05, +4.0);

                    return sum;
                }
                ENDCG
            }

            // Distortion
            GrabPass {
                Tags { "LightMode" = "Always" }
            }
            Pass {
                Tags { "LightMode" = "Always" }

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

                struct appdata_t {
                    float4 vertex : POSITION;
                    float2 texcoord: TEXCOORD0;
                };

                struct v2f {
                    float4 vertex : POSITION;
                    float4 uvgrab : TEXCOORD0;
                    float2 uvbump : TEXCOORD1;
                    float2 uvmain : TEXCOORD2;
                };

                float _BumpAmt;
                float4 _BumpMap_ST;
                float4 _MainTex_ST;

                v2f vert (appdata_t v) {
                    v2f o;
                    o.vertex = UnityObjectToClipPos(v.vertex);
                    #if UNITY_UV_STARTS_AT_TOP
                    float scale = -1.0;
                    #else
                    float scale = 1.0;
                    #endif
                    o.uvgrab.xy = (float2(o.vertex.x, o.vertex.y*scale) + o.vertex.w) * 0.5;
                    o.uvgrab.zw = o.vertex.zw;
                    o.uvbump = TRANSFORM_TEX( v.texcoord, _BumpMap );
                    o.uvmain = TRANSFORM_TEX( v.texcoord, _MainTex );
                    return o;
                }

                fixed4 _Color;
                sampler2D _GrabTexture;
                float4 _GrabTexture_TexelSize;
                sampler2D _BumpMap;
                sampler2D _MainTex;

                half4 frag( v2f i ) : COLOR {
                    // calculate perturbed coordinates
                    half2 bump = UnpackNormal(tex2D( _BumpMap, i.uvbump )).rg; // we could optimize this by just reading the x  y without reconstructing the Z
                    float2 offset = bump * _BumpAmt * _GrabTexture_TexelSize.xy;
                    i.uvgrab.xy = offset * i.uvgrab.z + i.uvgrab.xy;

                    half4 col = tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(i.uvgrab));
                    half4 tint = tex2D( _MainTex, i.uvmain ) * _Color;

                    return col * tint;
                }
                ENDCG
            }
        }
    }
}

```

**GRAY SCALE**

```
Shader "RGB -> Grey Texture/Alpha Blended" {

Properties{
    _MainTex ("Texture", 2D) = ""
}

Subshader {
    Tags {"Queue"="Transparent"}
    ZWrite Off
    Blend SrcAlpha OneMinusSrcAlpha
    Pass {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        struct v2f {
            float4 position : SV_POSITION;
            float2 uv_mainTex : TEXCOORD;
        };

        uniform float4 _MainTex_ST;
        v2f vert(float4 position : POSITION, float2 uv : TEXCOORD0) {
            v2f o;
            o.position = UnityObjectToClipPos(position);
            o.uv_mainTex = uv * _MainTex_ST.xy + _MainTex_ST.zw;
            return o;
        }

        uniform sampler2D _MainTex;
        fixed4 frag(float2 uv_mainTex : TEXCOORD) : COLOR {
            fixed4 mainTex = tex2D(_MainTex, uv_mainTex);
            fixed4 fragColor;
            fragColor.rgb = dot(mainTex.rgb, fixed3(.000, .000, .000));//(.222, .707, .071));
            fragColor.a = mainTex.a;
            return fragColor;
        }
        ENDCG
    }
}

}

```

The problem is that they work fine individually, but they don't when combined togheter

# Answer
> 2 votes
The answer to this one was actually surprisingly easy when I've gone through all the code in that seemingly huge blur shader. The only time it ever handles colors is at the bottom, with the `col` parameter. All I did was add three color channels together and then divide them by three, essentially making it grayscale.

Relevant part of the shader at the end:

```
half4 frag( v2f i ) : COLOR {
     // calculate perturbed coordinates
     half2 bump = UnpackNormal(tex2D( _BumpMap, i.uvbump )).rg; // we could optimize this by just reading the x  y without reconstructing the Z
     float2 offset = bump * _BumpAmt * _GrabTexture_TexelSize.xy;
     i.uvgrab.xy = offset * i.uvgrab.z + i.uvgrab.xy;

     half4 col = tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(i.uvgrab));
     half4 tint = tex2D( _MainTex, i.uvmain ) * _Color;

     /*the part that I added
     * use the first line and comment the second for faster processing
     * use the second line and comment the first for better colors */
     //col.r = (col.r + col.g + col.b) / 3;
     col.r = (col.r * 0.2126f + col.g * 0.7152f + col.b * 0.0722f);
     col.g = col.r;
     col.b = col.r;

     return col * tint;
}
ENDCG

```

The result:

---
Tags: unity, shaders
---


# Question
Title: How do I move a camera to a new X and Y position when the player collides with a certain object?
The lowdown is this: I'm making a 2D overhead game that takes place in separate screens in a room. Each screen is separated by a few blocks of black space (to give the impression of screens being separate rooms) and a rectangular "transition block" in doorways. My idea is, once a player touches this block, they are moved to the next adjacent screen *along* with the camera **instantly**.

I can move a player to the next screen this way, the big hangup that I'm having is moving the camera as well. I want every collision box to have the coordinates needed to set the camera around the next screen once player-box collision happens, similar to the setup I have with the player character.

# Answer
What you'll want to do is, upon collision, change view\_visible. You can set up 8 different views in the room editor, but it sounds like you want to set the new view in the player-box collision object which can be done with room\_set\_view.
> 1 votes

---
Tags: camera, game-maker
---


# Question
Title: Why does FRunnable become an unknown name after including it?
I am trying to create a runnable object to run code in a background thread. It's used to generate a level and it compiles as long as I don't include it somewhere. I've tried including it in a couple different classes and it fails.

.h

```
#pragma once

#include "CoreMinimal.h"

class ULevelGeneratorParams;
class ULevelData;

/**
 * Performs the actions of generating a level in a background thread.
 */
class MINESEEKER_API GenerateLevelRunnable : public FRunnable // as soon as I include this class in another class, FRunnable becomes an unknown type
{
public:

    static GenerateLevelRunnable Start(ULevelGeneratorParams *parameters);

    GenerateLevelRunnable();
    ~GenerateLevelRunnable();

    virtual bool Init();
    virtual uint32 Run();
    virtual void Stop();

private:

    static const int32 MINES_EASY = 10;
    static const int32 MINES_MEDIUM = 50;
    static const int32 MINES_HARD = 100;

    static const int32 WIDTH_HEIGHT_EASY = 10;
    static const int32 WIDTH_HEIGHT_MEDIUM = 20;
    static const int32 WIDTH_HEIGHT_HARD = 30;

    static ULevelGeneratorParams *Parameters;

    // Generates a unique vector and places it into the provided array.
    void GenerateUniqueVector(TArray<FVector2D> *locations, ULevelData *data);
};

```

c++

```
#include "GenerateLevelRunnable.h"
#include "Runnable.h"
#include "LevelGeneratorParams.h"
#include "LevelData.h"

GenerateLevelRunnable GenerateLevelRunnable::Start(ULevelGeneratorParams *parameters)
{
    GenerateLevelRunnable::Parameters = parameters;
    return new GenerateLevelRunnable();
}

GenerateLevelRunnable::GenerateLevelRunnable()
{
}

GenerateLevelRunnable::~GenerateLevelRunnable()
{
    delete GenerateLevelRunnable::Parameters;
    GenerateLevelRunnable::Parameters = NULL;
}

bool GenerateLevelRunnable::Init()
{
   return true;
}

uint32 GenerateLevelRunnable::Run()
{
    ULevelData *data = NewObject<ULevelData>();
    TArray<FVector2D> mineLocations;

    EDifficulty difficulty = GenerateLevelRunnable::Parameters->GetDifficulty();
    switch (difficulty)
    {
    case EDifficulty::EASY:
        data->SetWidth(WIDTH_HEIGHT_EASY);
        data->SetHeight(WIDTH_HEIGHT_EASY);

        for (int8 i = 0; i < MINES_EASY; i++)
        {
            GenerateUniqueVector(&mineLocations, data);
        }

        break;

    case EDifficulty::MEDIUM:
        data->SetWidth(WIDTH_HEIGHT_MEDIUM);
        data->SetHeight(WIDTH_HEIGHT_MEDIUM);

        for (int8 i = 0; i < MINES_MEDIUM; i++)
        {
            GenerateUniqueVector(&mineLocations, data);
        }

        break;

    case EDifficulty::HARD:
        data->SetWidth(WIDTH_HEIGHT_HARD);
        data->SetHeight(WIDTH_HEIGHT_HARD);

        for (int8 i = 0; i < MINES_HARD; i++)
        {
            GenerateUniqueVector(&mineLocations, data);
        }

        break;

    default:
        checkf(false, TEXT("Value for difficulty is not valid"));
        break;
}

data->SetMineLocations(mineLocations);
    return uint32();
}

void GenerateLevelRunnable::Stop()
{
}

void GenerateLevelRunnable::GenerateUniqueVector(TArray<FVector2D>* locations, ULevelData * data)
{
    FVector2D location;
    location.X = FMath::RandRange(1, data->GetWidth());
    location.Y = FMath::RandRange(1, data->GetWidth());

    if (locations->Contains(location))
    {
        GenerateUniqueVector(locations, data);
    }
    else
    {
        locations->Add(location);
    }
}

```

Here is the error I am getting

```
CompilerResultsLog: Error: GeneratBlueprintFunctionLibrary.cpp.obj : error LNK2019: unresolved external symbol "public: virtual __cdecl GenerateLevelRunnable::~GenerateLevelRunnable(void)" (??1GenerateLevelRunnable@@UEAA@XZ) referenced in function "public: virtual void * __cdecl GenerateLevelRunnable::`vector deleting destructor'(unsigned int)" (??_EGenerate
LevelRunnable@@UEAAPEAXI@Z)
CompilerResultsLog: Error: GeneratBlueprintFunctionLibrary.cpp.obj : error LNK2001: unresolved external symbol "public: virtual bool __cdecl GenerateLevelRunnable::Init(void)" (?Init@GenerateLevelRunnable@@UEAA_NXZ)
CompilerResultsLog: Error: GeneratBlueprintFunctionLibrary.cpp.obj : error LNK2001: unresolved external symbol "public: virtual unsigned int __cdecl GenerateLevelRunnable::Run(void)" (?Run@GenerateLevelRunnable@@UEAAIXZ)
CompilerResultsLog: Error: GeneratBlueprintFunctionLibrary.cpp.obj : error LNK2001: unresolved external symbol "public: virtual void __cdecl GenerateLevelRunnable::Stop(void)" (?Stop@GenerateLevelRunnable@@UEAAXXZ)
CompilerResultsLog: Error: C:\dev\projects\ue4\MineSeeker\Binaries\Win64\UE4Editor-MineSeeker-2451.dll : fatal error LNK1120: 4 unresolved externals
CompilerResultsLog: ERROR: UBT ERROR: Failed to produce item: C:\dev\projects\ue4\MineSeeker\Binaries\Win64\UE4Editor-MineSeeker-2451.dll

```

# Answer
> 2 votes
`LNK2019` is a linker error, not a compiler error. The error (the first one, at least) is telling you that the linker cannot find the *definition* of the symbol `GenerateLevelRunnable::~GenerateLevelRunnable` (and various other functions) that you declared in your header. They are in your source file, however, so it's not as simple as you just having forgotten to implement them.

The error states that the reference is within an object file called `GeneratBlueprintFunctionLibrary.cpp.obj`, that is, the object file for the `GeneratBlueprintFunctionLibrary.cpp` file. This suggests then that whatever is linking the `UE4Editor-MineSeeker-2451.dll` output file is not including your `GenerateLevelRunnable` class's compiled object file in the linker input command.

Since this is UE, the Unreal build system is responsible for feeding the appropriate files to the appropriate build tools. One typical reason for a file not being supplied to the linker is that you failed to configure your (Unreal) module's dependencies correctly. You may need to add the module containing your `GenerateLevelRunnable` class to the public or private dependency list of the module being compiled.

---
Tags: c++, unreal-4
---


# Question
Title: What is actually moving in an endless runner?
For example the famous Flappy Bird game, or anything that sort really, is the player(in this case the bird, or the camera whichever you prefer) moving forward or is the whole world moving backwards(the bird only changes Y position and has a constant X position)?

# Answer
> 146 votes
I slightly disagree with Philipp's answer; or at least with how he presented it. It gives the impression that moving the world around the player might be a better idea; when it's the exact opposite. So here is my own answer...

---

Both options *can* work, but it's generally a bad idea to "invert the physics" by moving the world around the player rather than the player around the world.

---

# Performance loss/waste:

The world will usually have a lot of objects; many if not most, static or sleeping. The player will have one, or relatively few, objects. Moving the whole world around the player, means moving everything in the scene except for the player. Static objects, sleeping dynamic objects, active dynamic objects, light-sources, sound-sources, etc; all have to be moved.

That's (obviously) considerably more expensive than moving only what's actually moving (the player, and maybe a few more stuff).

---

# Maintainability & Extensibility:

Moving the world around the player makes the world (and everything in it) be the point where things are most actively happening. Any bug or change in the system means that, potentially, everything changes. This is not a good way to do things; you want bugs/changes to be as isolated as possible, so that you don't get unexpected behaviors somewhere you haven't made changes to.

There are also many other problems with this approach. For example, it breaks many assumptions of how things are supposed to work in-engine. You'd not be able to use dynamic `RigidBody` for anything other than the player, for example; as an object with an attached `RigidBody` not set to kinematic will behave unexpectedly when setting position/rotation/scale (which you'd be doing every frame, for every object in the scene, except the player )

---

# So the answer is to only move the player then!

Well...*yes **and** no*. As mentioned in Philipp's answer, in an infinite-runner type of game (or any game with a large seamless explorable area), going too far from origin would eventually introduce noticeable FPPEs (Floating-Point Precision Errors), and further still, eventually, overflow the numeric type, either causing your game to crash, or, basically, make the game-world smoke crack...***On steroids!*** (because by this point, FPPEs would make the game already be on "normal" crack)

---

# The *actual* solution:

Do neither and do both! You should keep the world static, and move the player around it. But "re-root" ***both***, the player *and* the world, when the player starts getting too far from the *root* *(position `[0, 0, 0]`)* of the scene.

If you keep the relative position of things (player to the world around it), and do this process in a single frame-update, the (actual) player won't even notice!

To do it, you have two primary options:

1. Move the player to the root of the scene, and move the world chunk to it's new position relative to the player.
2. Think of the world like a grid; move the part of the grid that the player is in to the root, and move the player to it's new position relative to that part of the grid.

**Here is an example of this process in action**

---

# But, how far is too far?

If you look at Unity's source-code, they use `1e-5` (`0.00001`) as the basis for considering two floating-point values "equal", inside of `Vector2` and `Vector3` (the data-types responsible for objects' positions, \[euler-\]rotations and scales). Since floating-point precision loss happens both ways away from zero, it's safe to assume that anything under `1e+5` (`100000`) units away from the scene root/origin is safe to work with.

**But!** Since...

1. It's more appropriate to make a system to handle these re-rooting processes automatically.
2. Whatever your game is, there is no need for a contiguous "section" of the world to be 100000 units (usually meters) wide.

... then it's probably a good idea to re-root far sooner/more often than that 100000 units mark. The example video I provided seems to do it every 1000 units or so, for example.

Or, if your project allows it (most do), just have the world be "small enough" and avoid the problem altogether. On this note; congratulations, you've just found out one of the reasons why most games, even "open-world" or "free-roam" type ones like GTA, don't do maps/areas bigger than 10km-by-10km or 100km-by-100km.

# Answer
> 87 votes
Both options work.

But if you want the endless runner to be truly endless, you will have to keep the player stationary and move the world. Otherwise you will eventually hit the limits of the variables you use to store the X-position. An integer would eventually overflow and a floating point variable would become increasingly less accurate which would make the gameplay glitchy after a while. But you can avoid this problem by using a large enough type that nobody will encounter these problems within the timespan one could conceivably play in one session (when a player moves 1000 pixels per second, a 32 bit integer will overflow after 49 days).

So do whatever feels conceptually more intuitive to you.

# Answer
> 37 votes
Building off of XenoRo's answer, instead of the re-rooting method they describe, one could do the following:

Create a circular buffer of parts of your infinite map generated, which your character moves through with position updated with modulo arithmetic (so you just run around the circular buffer). Start replacing parts of your buffer as soon as your character leaves the chunk. The players update equation would be something like:

`player.position = (player.position + player.velocity) % worldBuffer.width;`

here is a pictoral example of what I'm talking about:

Here is an example of what happens on wrapping at the end.

With this method you don't run into precision errors ever, but you may need to make a very large buffer if you intend to do this in 3d with very far view distance (as you will still need to be able to *see* ahead of yourself). If its flappy bird your chunk size will probably only be as large as it needs to be to hold a single scene for a single screen, and your buffer can be very tiny.

Note that you will start to get repeating results with *ANY* prng, and the max number of non repeating sequences of a PRNG generation is typically less than the length of pow(2,number of bits used internally), with merzenne twister this isn't much of an issue, as it uses 2.5k of internal state, but if you use the tiny variant, you have 2^127-1 max iterations before repeat (or worse), this is still an astronomically large number however. You can fix repeating period problems even if your PRNG has a short period via good avalanche mixing functions for the seed (as you add more state implicitly) repeatedly.

# Answer
> 14 votes
As already asked and accepted, it really depends on the scope and style of your game, but since it wasn't mentioned: FlappyBird moves the obstacle across the screen, rather than the player across the world.

A spawner is instantiating objects off screen with a fixed speed in the `Vector2.left` direction.

---
Tags: game-mechanics, platformer
---


# Question
Title: glm rotating quaternion in Y axis deforms object
I'm implementing my own game engine in C++ and I need help here,

I have a game object, its orientation property is a quaternion and I want to rotate it A degrees in the Y axis.

So, I have:

```
currentAngle += 0.01; // currentAngle is a member variable, so yes i initialized it
quat q(currentAngle, vec3(0, 1, 0));
myGameObject->SetOrientation(q);

GameObject::SetOrientation(quat q)
{
 myOrientation  = q;
}

```

but as the game object rotates, it also gets scaled (deformed). So I checked how I am applying the transformation matrices

```
myModelMatrix = Math::CreateTransformationMatrix(
    transformation->GetPosition(),
    transformation->GetOrientation(),
    transformation->GetScale());

mat4& Math::CreateTransformationMatrix(vec3&    translation, quat& orientation, vec3& scaleSize)
{

     mat4 translate = glm::translate(glm::mat4(), translation);
     mat4 rotate = glm::toMat4(orientation);
     mat4 scale = glm::scale(glm::mat4(), scaleSize);

    return  translate * rotate * scale;
}

```

but it looks ok (at least to me), I removed the scale matrix form the multiplication to check if somehow I was doing something with it. However, it didnt fix anything.

I also tried:

```
  quat q(currentAngle, vec3(0, 1, 0));
   quat orientation = myGameObject->GetOrientation();
   orientation  = orientation  *q;
   myGameObject->SetOrientation(orientation);

```

But it didnt work either. I also checked the code in my shaders and I am positive is not the problem.

This is how I send the matrices to the shader:

```
glUseProgram(progarmId);1
    glUniformMatrix4fv(uniforms[name], 1, GL_FALSE, glm::value_ptr(matrix));

```

I tried modifying the 3rd parameter to True and swapping the order of the projection view matrix multiplication and it didnt work either :/

So, guys ... any ideas what could I be doing wrong ? I'm out of ideas :/

# Answer
I'm not sure if it is what's causing the problem but the CreateTransformationMatrix method should not return a reference type because the result is allocated on the stack in the scope of the method. So the resulting matrix is in an undefined state.
> 1 votes

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


title: How to add a bump map in scene kit?

text:
# Question
Title: How to add a bump map in scene kit?
I'm trying to draw an Earth, as I've found the textures in this site: http://planetpixelemporium.com/earth.html

I loaded the diffuse, specular and bump maps:

```
let earthGeometry = SCNSphere(radius: radius)

let earthMap = UIImage(named: "Earth_map")
let earthBump = UIImage(named: "Earth_bump")
let earthSpec = UIImage(named: "Earth_specular")

earthGeometry.firstMaterial!.diffuse.contents = earthMap
earthGeometry.firstMaterial!.specular.contents = earthSpec

let earth = SCNNode(geometry: earthGeometry)

```

But there is no property for the bump map. The only way that comes to my mind is to use a MDLMaterial but I see no way to convert the material back to a SCNMaterial. The method:

```
+ (instancetype)materialWithMDLMaterial:(MDLMaterial *)mdlMaterial

```

Runs just in Objective-C and not in Swift. Does anyone know how to convert it to a SCNMaterial, or alternatively to use another way to apply a bump map in a SCNMaterial?

# Answer
There isn’t a built-in way to apply a grayscale bump map like the one you have; what SceneKit expects is a normal map. It’s pretty straightforward to convert one into the other, though; there’s even an online tool available to do so here.
> 1 votes

# Answer
The property you want to apply your texture to is called "normal", for normal mapping. You can find the documentation for this property here.

```
let earthGeometry = SCNSphere(radius: radius)

let earthMap = UIImage(named: "Earth_map")
let earthBump = UIImage(named: "Earth_bump")
let earthSpec = UIImage(named: "Earth_specular")

earthGeometry.firstMaterial!.diffuse.contents = earthMap
earthGeometry.firstMaterial!.specular.contents = earthSpec
earthGeometry.firstMaterial!.normal.contents = earthBump

let earth = SCNNode(geometry: earthGeometry)

```

As you can see in this image from the documentation, this works with a tangent space normal map:

Here the pale blueish-lavender colour represents a surface normal pointing straight out from the sphere, while the other colours represent normals tilted east/west/north/south by hills and valleys. If your bump map is in a different formal (like a greyscale heightmap), then you can use various tools to convert it to this coloured normal map format.
> 0 votes

---
Tags: ios, swift, scenekit, bump-map
---


# Question
Title: Why do I have delays when pressing a keyboard key continuously to move the character?
What happens is I press right for a fraction of a second then release and my character moves to the right, as it is supposed to. I then press right again but this time for 5 seconds. My character moves immediately to the right and keeps moving with no pause between the first movement and the rest, as it is supposed to. But after 5 seconds of pressing right I then release the key and press left, but my character still keeps moving to the right for another 6 seconds. This effect is worse the longer I press the key. Why is that? I checked the boolean variables I am using to track the pressed and not pressed status of my keys and it seems like the status doesn't change until after the aforementioned 6 seconds during which the character keeps walking right although I am pressing left. However, key presses are still being detected quickly and on time in each iteration of the main game loop.

Based on my checks, key presses are still being checked quickly at each iteration of the main loop, and so is the key down/pressed status of keyboard keys. However, the key up/released status of keys is only checked until after the 6 seconds mentioned. Further checks showed that SDL2 poll event still reports a keydown status even though I am not pressing any keys and only reports a keyup after the 6 seconds. Is it windows 10 interfering with my program? It's like there's another program that keeps pressing right (same issue with other keys) eventhough I am no longer physically pressing that key.

I would appreciate your help and advice. Thank you.

I am programming in Free Pascal using SDL2. Below is a sample of my keyboard and other inputs procedure:

```
if sdl_pollevent(sdlevent)=1 then
begin
    { writeln(sdlevent^.type_,' ',sdl_keydown,' ',sdl_keyup); }
    if sdlevent^.type_=sdl_keydown then
    begin
        joystickactive:=false;
        { writeln(sdlevent^.key.keysym.sym); }
        { writeln(sdl_getkeyname(sdlevent^.key.keysym.sym)); }
        enterkeyintf:=false;
        if enterkeyintf=true then
        begin
            assign(t[1],'tf\tf0.tf');
            append(t[1]);
            settextbuf(t[1],bufin);
            writeln(t[1],sdlevent^.key.keysym.sym);
            writeln(t[1],sdl_getkeyname(sdlevent^.key.keysym.sym));
            close(t[1]);
        end;
        o[1]:=0;
        repeat
            o[1]:=o[1]+1;
            if sdlevent^.key.keysym.sym=keycode[o[1]] then keybool[o[1]]:=true;
        until o[1]=totalkeys;
        o[1]:=0;
        repeat
            o[1]:=o[1]+1;
            if sdlevent^.key.keysym.sym=alphanumm[o[1]] then alphanumbool[o[1]]:=true;
        until o[1]=totalalphanum;
    end;
    if sdlevent^.type_=sdl_keyup then
    begin
        joystickactive:=false;
        o[1]:=0;
        repeat
            o[1]:=o[1]+1;
            if sdlevent^.key.keysym.sym=keycode[o[1]] then keybool[o[1]]:=false;
        until o[1]=totalkeys;
        o[1]:=0;
        repeat
            o[1]:=o[1]+1;
            if sdlevent^.key.keysym.sym=alphanumm[o[1]] then alphanumbool[o[1]]:=false;
        until o[1]=totalalphanum;
    end;
end;

```

# Answer
> 3 votes
I think what was happening is that SDL2 would pollevent once and not again if the key being pressed is still the same. If it's the same it would default to event type 771 (I couldn't find on the internet what that corresponds to). So I added the code to make the program run sdl\_pollevent once more if it gets the code 771. Solved the problem:

```
if sdl_pollevent(sdlevent)=1 then
begin
    if sdlevent^.type_=771 then sdl_pollevent(sdlevent);

```

---
Tags: movement, keyboard
---


# Question
Title: differing methods of Instantiating GameObjects in Unity (what is the difference?)
I have been using Unity a while and always Instantiated objects slightly differently from what many of the tutorials and posts online say (I've seen 3 very similar ways). It seems to have the same outcome much of the time, however now I am trying to instantiate the prefab using my "Resources" folder instead of dragging it from the inspector and on one method it said it was an 'object' not 'gameobject'. I can't really find anything on Unity website or here, so what is the difference between the following:

```
 // These two lines to me seem identical, but most tutorials dont cast, and rather use the latter of the two instead, why?
 currentBall = (GameObject)Instantiate(Resources.Load(prefabName, typeof(GameObject)));
 currentBall = Instantiate(Resources.Load(prefabName, typeof(GameObject))) as GameObject;

  // This one I know is different somehow, because Unity said cannot convert from Object to GameObject, but honestly i do not understand why
  currentBall = GameObject.Instantiate(Resources.Load(prefabName, typeof(GameObject)));

```

# Answer
> 3 votes
The short answer is that it's all about type safety, and how we navigate type guarantees.

Casting like this:

```
(TypeIWant)SomeMethodThatReturnsAMoreGeneralType()

```

will throw an error if the value returned from the method isn't convertible to the `TypeIWant`.

But using the `as` keyword:

```
SomeMethodThatReturnsAMoreGeneralType() as TypeIWant

```

will instead populate the value with `null` if the conversion fails. So if there's a legitimate reason you might get a different return type for your particular application, using `as` lets you detect and handle that case gracefully, without throwing errors and `try/catch` complications.

There's no significant performance difference between the two in modern C#, so the main function here is to clearly show your intent and trap errors where you want them. If your game absolutely expects `TypeIWant` here, then use a cast. If that assumption is ever violated, you'll get the error immediately and can go investigate right at the source.

On the other hand, `as` shows that you knowingly expect the type to sometimes be something else, and that this is not immediate cause for concern. It will be the job of the subsequent code to check for nulls where there shouldn't be nulls and fire a corresponding error if they need to.

The last case is due to the fact that even if we write `GameObject.Instantiate`, it's still calling `UnityEngine.Object.Instantiate`, which is made for cloning *anything* that derives from `UnityEngine.Object` \- that means it can't guarantee you're going to get a `GameObject` out at the end. `GameObject.Instantiate(GetComponent<Renderer>().sharedMaterial)` is also valid syntactically, returning a Material. So we need a cast or `as` to convert the return value to a `GameObject` before we can store it in a variable with type `GameObject`.

Of course you could also skip the cast entirely, and use the generic form or Instantiate/Load if you know in advance what type you want. That way a mismatch is a compile-time error, rather than a runtime error, and can often be faster to catch & correct:

```
TypeIWant myThing = Instantiate<TypeIWant>(Resources.Load<TypeIWant>(path));

```

Wherever possible, I like to type my variables according to the most specific type I need from them. So rather than storing a bullet prefab as a GameObject or Transform, I'll give it a `Projectile` component and expose a slot for it like:

```
public Projectile bulletPrefab;

```

Then I can instantiate it with:

```
 var bullet = Instantiate<Projectile>(bulletPrefab);

```

Now I have strong type guarantees throughout, without casts, and the Inspector will enforce that whatever I assign to `bulletPrefab` has the required component. (Don't worry, Instantiate will still clone the whole prefab, game object, other scripts, child hierarchy, and all - not just a floating Projectile component)

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


# Question
Title: No performance gain from instanced rendering?
I recently worked through this tutorial about instanced rendering. At the end it promises to draw a huge amount of instances of one model without performance drops.
So I tried some simple instanced rendering to see these effects. So I created a VBO containing four times xyz-coordiantes, vertex color and texcoords.

```
float[] backgroundData = new float[] {
            -1.0f, -1.0f, 0.0f, 1f,1f,1f,1f, 0.0f, 0.0f, 0.0f,
            1.0f, -1.0f, 0.0f, 1f,1f,1f,1f, 1.0f, 0.0f, 0.0f,
            -1.0f, 1.0f, 0.0f, 1f,1f,1f,1f, 0.0f, 1.0f, 0.0f,
            1.0f, 1.0f, 0.0f, 1f,1f,1f,1f, 1.0f, 1.0f, 0.0f
    };

```

I also created a VAO and EBO containing the `glVertexAttribPointers` and indices `int[] indices = new int[]{0,1,2,1,2,3};`.

Now I draw everything with `glDrawElementsInstanced(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0, 10_000)`. But the Framerate drops as much as if I had the indices 10.000 times in my EBO. Why is the outcome so different? Did I do something wrong?

# Answer
Instancing is an improvement relative to *multiple draw calls*, with state changes between each draw.

Instancing exists to allow you to provide per-instance data to each instance, so that it can iterate over the same vertices with new data. This allows you to do things like provide offsets or even full transformation matrices to each instance of vertices, all while only issuing one draw.

So that's what you need to compare it to: setting up the data for an instance, then drawing it, then setting up the data for the next instance. It's meaningless to test the performance between rendering 10,000 individual instances and 10,000 copies of the same object using the same rendering state.
> 3 votes

---
Tags: opengl, performance, vbo, frame-rate, instancing
---


# Question
Title: Character automatic movement and rotation
I have problems with a character. I want to move myself at some speed, and by typing on WASD keys to rotate this object and move to the side where the face is. The object moves continuously without pressing the key. Let's say something to the snake game.This is my code, it goes, but I can not do this rotation.

```
private float speed = 0.01f;
private float moveSpeed = 12f;
Vector2 vector = Vector2.up;
Vector2 moveVector;
[HideInInspector] public bool IsMoving = false;
[HideInInspector] public bool canPress = true;
 private void Start()
{
    InvokeRepeating("Movement", 0.5f, speed);
}
   void Update()
{
    if (canPress)
    {
        if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
        {
            canPress = false;
            IsMoving = true;
            vector = Vector2.right;
            //transform.Rotate(0f, 0f, -90f);
            transform.rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y + rotateObj, transform.rotation.z);
          }
          else if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
          {
                canPress = false;
                IsMoving = true;
                vector = Vector2.up;
          }
          else if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S))
          {
                canPress = false;
                IsMoving = true;
                vector = -Vector2.up;
               //transform.Rotate(0f, 0f, -90f);
          }
          else if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
          {
                canPress = false;
                IsMoving = true;
                vector = -Vector2.right;
                //transform.Rotate(0f, 0f, +90f);
          }
      }
      moveVector = vector / moveSpeed;
    }
    void Movement()
    {
        if (IsMoving)
           transform.Translate(moveVector);
    }

```

If anyone knows how to do this I would be grateful. !!!

# Answer
```
public GameObject shipSprite;
private float speed = 0.01f;
private float moveSpeed = 12f;
Vector2 vector = Vector2.up;
Vector2 moveVector;
[HideInInspector] public bool IsMoving = false;
[HideInInspector] public bool canPress = true;
private void Start()
{
    gameObject.GetOrAddComponent<ColliderEventSystem>().TriggerEntered += SpaceShiptTriggerEnter;
    InvokeRepeating("Movement", 0.5f, speed);

}
    void Update()
{
    if (canPress)
    {
        if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
        {
            canPress = false;
            IsMoving = true;
            vector = Vector2.right;
            shipSprite.transform.Rotate(0f, 0f, -90f);
        }
        else if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
        {
            canPress = false;
            IsMoving = true;
            vector = Vector2.up;
            shipSprite.transform.rotation = Quaternion.identity;
        }
        else if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S))
        {
            canPress = false;
            IsMoving = true;
            vector = -Vector2.up;
            shipSprite.transform.rotation = Quaternion.identity;
        }
        else if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
        {
            canPress = false;
            IsMoving = true;
            vector = -Vector2.right;
            shipSprite.transform.Rotate(0f, 0f, 90f);
        }
    }
    moveVector = vector / moveSpeed;
}
void Movement()
{
    if (IsMoving)
        transform.Translate(moveVector);
}

```
> 1 votes

# Answer
To Rotate your character at some specific point use this line first declare public float variable rotateObj = 90; and assign value.

```
 transform.rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y + rotateObj, transform.rotation.z);

```

To move your Character use this line public float speed;

```
private Rigidbody rb;

void Start ()
{
    rb = GetComponent<Rigidbody>();
}

 Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

    rb.AddForce (movement * speed);

```
> 0 votes

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


# Question
Title: How to flush changes in PlayerSettings inside Editor
I have a script which works only in the Editor. The script makes changes inside PlayerSettings. However, the changes made are flushed to the hard drive just after something in Unity is saved for example any scene.

We have a script which increments the build version. The described issue sometimes leads to the wrong version committed to Git as the changes a flushed to the disk later.

How can I flush the changes of PlayerSettings from the code?

# Answer
> 0 votes
Thanks to @DMGregory

`AssetDatabase.SaveAssets();`

Will flush the changes to disk.

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


# Question
Title: How can I fill the interior of a closed loop on a tile map?
In my game the player can dynamically modify terrain. The map is stored within a 2D array of prefabricated 3D objects. This is working well for now. The player modifies terrain by selecting what sort of tile they'd like to create (like cliff going up or down), and then clicking individual tiles, or "painting" over multiple by holding down mouse button and scrolling.

I don't want the player to have to manually click every tile they want to rise or fall in elevation. The most elegant solution I can conceive, is for the player to "paint" a loop of cliff tiles, which is then filled in automatically when the loop closes. Imagine, perhaps, someone drawing a line using MS Paint or Photoshop, until that line closes into a shape which then autofills.

Let's say the player wants a plateau, and so they select cliff going up, and then click and drag the desired shape. Upon closing the loop, when the last cliff tile is created beside the first cliff tile, witchcraft is invoked which fills the inside.

I have no idea how this can be done, never mind elegantly or optimally. There are obvious possible solutions (find the average vector of all tiles in the loop, and then dijkstra algorithm from the average until the space is filled with the correct elevation), but these assume the shape generated is blobby or boxy. An irregular shape where the mid point falls outside of the shape is possible and would probably ruin that solution!

**How can I fill the inside of a closed loop?** I'd like a theoretical solution I can go away and implement in C#. At this point it seems like there is probably conceptual overlap between raster graphics and procedural maps!

# Answer
**Short**: After completing the shape you should have a *multiple of 2* Points for each affected row on your *x-axis*. From there it becomes just a matter of splitting up these Pairs of Points for each row and then *fill the inbetweens*.

---

**Long1**: This is not a complete algorithm. This is just a description of steps to be taken. How to achieve each step is up to the reader and might differ between languages, etc.

*Step 1*: Draw the loop inside your game/editor/whatever and however you want to do that.

*Step 2*: Get the *points* touched by your loop. These are the *edges* of your *shape*.

*Step 3*: Iterate over these *points* and get the ones that have *one or no* neighbours. These are our starts and stops (or whatever name you find fitting).

*Step 4*: Iterate over your starts/stops and create *pairs* of two each.

*Step 4b - Special Case*: If you've got an odd number of stats/stops you can get rid of the central *point*.

*Step 5*: You can now fill the *area*2 between each *pair* of *points*.

1WITH PICTURES! I KNOW, RIGHT?
2Well, it's actually *segments* not *areas*. A line between two *points* is a *segment*. The whole thing is an *area* though.

---

As mentioned in the comments this algorithm is not bulletproof at all, here's one proposed improvement to *Step 4b* by @DMGregory
> 14 votes

# Answer
For simple shapes (i.e. ones that don't self-intersect, so that the interior of the shape is a single connected area) a flood fill algorithm should work fine.

The tricky part of trying to flood fill the interior is that, as you note, you'll need to start the fill from a point that you know to be inside the loop. One way to find such a point could be to pick, say, a point just south of the northernmost point in the loop. As long as your loop shape is clean enough, and doesn't double back on itself, you could be pretty sure that this point will be inside the loop.

However, there's an alternative solution that avoids the need to find such an interior starting point completely, and also handles arbitrary self-intersecting shapes: instead of flood-filling the inside of your loop, **fill the outside instead.**

Of course, it's probably not practical to fill *all* of the outside, since your map will likely be a lot bigger than the shape drawn by the player. But it's pretty easy to compute a bounding box that encloses the shape drawn by the player (and extends at least one map tile around it on all sides, to make sure there's a connected path around the shape inside the box), and then flood-fill the part of the box that lies *outside* the shape, starting e.g. from any corner:

The interior of the loop will then consist of every point inside the bounding box that has *not* been touched by the flood fill algorithm.

The nice thing about this algorithm is that it's dead simple to implement, especially if you're already familiar with things like Dijkstra's algorithm, which is basically a special kind of flood fill. Unlike the scanline fill algorithm suggested by dot\_Sp0T, there are no tricky special cases with corners or with boundary lines that align with the grid; all you need to do is make sure the boundary is continuous and closed, and then flood fill its exterior.

Note that, if the player's loop can self-intersect, these algorithms can give different results. For example, for the self-intersecting boundary shape shown in the image below, the even/odd fill rule obtained from a scanline fill would fill in the purple area on the left, while the exterior flood fill algorithm I describe would treat the entire cyan area on the right as being inside the loop:

It's up to you which behavior you'd consider more reasonable. (Of course, other fill rules are also possible, such as the non-zero winding rule, which would fill in the upper "hole" in the shape above, but not the lower one.)
> 0 votes

---
Tags: algorithm, tilemap
---


# Question
Title: Project transfer, will re-importing all my models damage my project at all?
Recently I had to transfer my Unity game project to another computer and downloaded the same version of Unity I was using for my 3D project and checked that all the files and folders were in the same place and everything.

When I start up the game though my models have vanished and in the hierarchy it just says missing prefab instead of telling me what it was, like it used to if I'd move a model to another folder or something like that.

It shows all my files there and I was about to reimport them all but I got a warning that said:

"Rebuilding assets is only if your project has been corrupted due to an internal Unity bug. It can take several hours to complete, depending on the size of your project.

Please submit a bug report detailing the steps leading up to here."

I am sure that re-importing all my models will fix this but I want to ask if this will have any negative effects on my project or possibly damage anything?

This game is extremely important to me and I've been working on it for the past 3 years(being self taught which is why it's taken so long and I'm still learning)

Thank you guys in advanced! :D

# Answer
> 4 votes
You need to transfer the asset metadata as well as the asset files themselves. The metadata files might be invisible depending on your settings.

On the old computer, go to `Edit>Project Settings>Editor` in Unity and set `Version Control` to `Visible Meta Files`. You should now see `.meta` files appear next to all the assets in your Assets folder. Copy those over and your project should work as normal.

I'd also recommend putting your code in a version control system, especially if you have 3 years of work. That way, you can try changes like this without worrying about destroying your project.

---
Tags: unity, data
---


# Question
Title: Selective Collision Resolution While Rolling
I am working on a 2D action platformer in Pygame, though my question is a general one.

The question concerns selective collision resolution. In short, I want certain collisions to be ignored while my player sprite is rolling.

My player sprite has a roll state during which a controlled force is applied, moving the sprite forward until the roll animation finishes and the sprite's state changes to idle.

The sprite's bounding box doesn't change during this animation, since, as a rule, you don't want a sprite's bounding box to change size from frame to frame (see this answer).

My sprite is 64 pixels tall and I want him to be able to roll through 32 pixel gaps. Here's a diagram:

Currently, I do collision resolution during updates to my sprite's position. I first change his y-position according to his y-velocity, then check if there is rectangular overlap between my sprite and objects of a wall class. If there is, I place him flush with the wall. Then I update his x-position according to his x-velocity and do a similar collision check and resolution.

I was thinking I might be able to achieve my desired goal (rolling under walls) by flagging certain walls as "passable\_while\_rolling". The wall under which I'm rolling could be thus flagged. In my collision code, these walls would be ignored if the sprite was in the rolling state.

A problem would occur, however, if the sprite finished rolling while intersecting one of these walls. In that case, the collision code would kick in and resolve the sprite to one side of the wall in an unattractive manner.

Another option would be to just keep the sprite in the rolling state until he no longer intersects any flagged wall (similar to how you can't shift out of morph ball until you have overhead space in Metroid). I don't want to do this since I think looping the roll animation is ugly and unrealistic.

So, my questions are: **What are my other options? How do other games deal with collision while rolling under walls?**

I am open to drastically changing my collision resolution system.

# Answer
I implemented a solution I am happy with.

I flagged certain walls as "passable\_while\_rolling" and told my collision code to ignore these walls if the player was rolling.

To prevent the ugly scenario where the player stops rolling while clipping the wall, resulting in ugly resolution, I only start ignoring collision if the player is very near the wall on the first or second frame of his roll animation. I reinstate collision at the end of the animation, when the player sprite has safely cleared the wall. This way, if the player starts to roll from too far away, his roll animation will be on a later frame when he meets the wall, and the wall will simply block him from rolling any farther, preventing the ugly clipping.

The resulting gameplay feels good.
> 1 votes

---
Tags: 2d, collision-detection, collision-resolution, pygame
---


# Question
Title: Unity3D: Sudden lighting change in a scene
> Sorry if this is a duplicate question, but I have no idea what this would be considered.

Hello, I have recently been creating an FPS game, but while researching some things on the internet, the lighting changes within only one scene. I actually want to keep this change, but I am not sure what changed to make it look like this.

It unusually changed from this:

To this:

I want to keep the new one, but have this same lighting effect on a different scene, however, I am not sure what can cause this change. I have searched high and low for anything that could've changed, but I couldn't find anything. Any help is greatly appreciated. Thanks!

# Answer
> 2 votes
The way I fixed this is to go to the Lighting menu at `Window > Lighting` and configure the Lightmaps to Auto.

# Answer
> 0 votes
I had the problem of random lighting change. My dark scene suddenly was bright. I went to Window/Lighting Settings/Object maps and turned off Auto Generate and that fixed it for me.

---
Tags: unity, lighting
---


title: Pixel perfect collisions for platforms

text:
# Question
Title: Pixel perfect collisions for platforms
I'm trying to create pixel perfect collision detection but I don't know how to handle collisions when there is a jump. Here I have one image of a sample map:

But maybe I had a bad supposition assuming that all the pixels are little collision points.

I mean , **there is no differences between y-axis collision and x-axis collision** in my collision map.

I have been treating each axis collision split, but that is bad done when diagonal jump have been made, cause you'll get an error in x or in y while correcting the position.

Then I thought that maybe I was wrong in my supposition that I didn't need to split for pixel collision type.

I will resume it in 2 questions:

* **how can I handle pixel perfect collisions for a platformer?**
* **if I'm doing it well, How to manage the x-axis, y-axis problem?**

P.S: My 'player' uses a box collider.

# Answer
I use masks to do pixel-perfect collision checks between my player and enemies. (I don't ever feel the need for pixel-level precision when it comes to platforms and walls.)

A *mask* is essentially a silhouette of a sprite, using 1-bit per pixel to encode where the sprite's image has transparency and where it doesn't. Many engines and libraries have built-in functions for creating masks from images and checking for overlap between masks.

If you do end up using masks for collision tests, you should always test for regular rectangular collision first, and only test for mask collision in the event of rectangular collision. Testing for mask collision is computationally expensive, but testing for rectangular collision is not.

For one-way platforms, I usually create a boolean attribute in my platform class called "is\_one\_way", and set it to true for platforms I want to be one-way. In my collision code, if the wall is one-way, I only resolve in the event that the sprite is above the platform and his y-velocity is positive.
> 1 votes

# Answer
There are different approaches you can use. For a start, I'd use a rather simple (maybe even a bit naive) approach:

You're essentially checking two points on your character for now:

* The position where he's standing (`feet`; actually a bit right below the character).
* The position of his head (`head`).

The character is then moved based on the following rules: \- If `feet` is not solid, drop down. \- While `feet` is solid, move up. \- If `feet` and `head` both are solid, the character dies (squeezed). `If`head`is solid, stop vertical velocity/jumping.
- While`head\` is solid, move down.

Checking left/right works in a similar way. Doing this right will also solve stuff such as ramps instantly for you.

Reading through the poitns above, it should be clear, that you essentially "bounce" the character instead of having him standing still. This is true, but the player won't notice, because you don't draw inbetween these steps.
> 0 votes

---
Tags: collision-detection, collision-resolution, platformer
---


title: Summing forces on an object

text:
# Question
Title: Summing forces on an object
A body in a 3 dimensional friction-less environment experiences a force at 1 meter away from its center of mass, in a direction of a 90 degree offset from the direction of its center of mass.

This will cause the body to rotate, it will not move from its place.

If there is a new force introduced, on the other side of the center of mass but in the same direction, the rotation will be cancelled and instead the body will move in the direction of the force.

There are tonnes of physics examples out there dealing with one force on an object, I find nothing about how to sum up multiple forces into one though.

I'd like an example of how to sum up all forces affecting a body and translate that into how the body will change its momentum and accelerate

Examples in python preferred, examples in pure math are discouraged.

# Answer
First, you should learn how Torque and Angular momentum work, because the simple answer to your question is ("add the forces and add the torques, then integrate over time.")

> I'd like an example of how to sum up all forces affecting a body

With a vector library, the actual math isn't that hard. for each individual force, the *projection* of that force onto the moment arm is the displacement force, and the cross product of that force and the moment arm is the torque vector.

```
Vector3 centerOfMass;
List<(Vector3, Vector3)> forceOnPointPairs;

totalForce = sum(dot(f, (pt - centerOfMass)) / length(pt - centerOfMass) for f, pt in forceOnPointPairs)
totalTorque = sum(cross(f, pt - centerOfMass) for f, pt in forceOnPointPairs)

```

> How the body will change its momentum and accelerate.

This is called integration - in very basic pseudocode, you can think of it as an update loop logic like

```
def update(deltaTime):
   acceleration = sum(forces) / mass
   velocity += deltaTime * acceleration
   position += deltaTime * velocity

   angular_acceleration = sum(torques) / moment_of_inertia
   angular_velocity += deltaTime * angular_acceleration
   orientation += angular_velocity // warning: this bit is hand-wavy

```

I've hand-waved the orientation line because the actual implementation depends on how you store the orientation. For a more complete picture, a good series of article to read on this topic is at Gaffer on Games:

Integrating Position and issues with Euler Integration: https://gafferongames.com/post/integration\_basics/

Integrating Rotation: https://gafferongames.com/post/physics\_in\_3d/
> 1 votes

---
Tags: physics
---


title: TRS Matrix between 2 points

text:
# Question
Title: TRS Matrix between 2 points
I have got 2 Points in 3D Space whose TRS Matrix' from 0.0 to there current place is known. Now I want to change the Matrix of the left point so that the matrix of the right point combined with the new Matrix results in the point being at the same position as before. Here a short illustration that I hope helps a little. Sorry for the bad explanation

# Answer
> 2 votes
The question hardly makes sense for points, since, if I'm not mistaken, there are infinitely many matrices that would fit.

If you mean 'objects' rather than 'points', then the answer simple:

You have

```
B × С = A

```

where `A` is the matrix of the left object, `B` is the matrix of the right object, and `C` is unknown.

```
                B × С = A  ↔
↔  inverse(B) × B × C = inverse(B) × A  ↔
↔                   C = inverse(B) × A

```

Thus you need to multiply the inverse matrix of the right object by the matrix of the left object.

# Answer
> 1 votes
Points have no orientation, only a position.

This means your question does not make sense. There is no "matrix" for a point. If there was a matrix, the point would be a local coordinate frame (three axes and an origin.)

To move a point from B to A, you add a translation vector (not apply a 4x4 matrix.)

---
Tags: 3d, matrix
---


# Question
Title: How can I make the player slide when he does a 180 degree turn?
I'm making a roller skating game and I would like to player to skid or stop moving skating when they try to move in the opposite direction of their current one. But I'm not sure how to go about this.

I tried computing the the dot product of the input of the current frame and the last and if the product was less than or equal 0 that must mean the player did a 180 and the player's velocity was stopped. But it did not work, the product was always greater than 0,

# Answer
The answer to this naturally will depend somewhat on your input method. However, there are some general principles.

The process of skidding occurs when one uses the skates to apply a great deal of force in the opposite direction from that of the skater's movement, and the skates break free. The key takeaway here is that this skidding process is a function of inertia.

The method you describe will tell you whether the input suddenly shifted 180 degrees, but that's not really what you want. What you want to do is determine if the input (which governs the forces the skater is applying) is in the same direction as the skater's momentum, or in the opposite direction. This will tell you if the skater is trying to speed up or slow down.

Depending on your input device, you may want to have a small region around this 180 degree point which causes a skid. It's impossible to reliably input exactly 180 degrees opposite something on most analog devices.
> 1 votes

# Answer
Thats how I would do it:

Having the velocity of the skater, I would detect if the player is trying to accelerate into the direction of a negative multiple of the velocity, hence in the opposite direction. If thats the case, the velocity of the skater should decrease by e.g. v\*0,3 every second, so he should be able to skate into the different direction pretty quickly again. After the deceleration, he should start accelerating into the new direction again.

Maybe you want to play a scratching sound on turning and make his legs stop moving or have some sparks beneath his skaters.
> 0 votes

# Answer
Well, in Java, for example, you'd have a KeyListener check for your movements and IF... on a turn you faced the opposite direction of your velocity vector then it could trigger a stop response. Yeah... you'd have to listen for the left or right arrow keys and check for that and then trigger the stopMovement() response. Fact is... you know what would be easier? Detect turning and do a gradual vector decrease of movement to zero. This could all be done on KeyListener in Java very easily. But I see what you want, because a slight turn could slam you into a wall, right? But a 180 turn could eventually stop you in place. So you'd have to grab the turn degree and match it against the forward movement vector to react it into a gradual stop. Probably a wide range too. So it wouldn't need to be exactly 180 but somewhere within that range of degrees. Fact is, facing direction should equal resistance. In other words, if you're ice skating in a fast forward movement vector and you suddenly start to turn... then the vector should account for the turning resistance you just gave. So you'd add a different vector to the forward one to add into the turn... now then, if you turned completely the other way around... just check for a range for that, not 180 specifically but maybe 170-190 degrees opposite of forward vector and plug in HEAVY to a resistance variable for that vector movement.
> -3 votes

---
Tags: physics
---


# Question
Title: Why the player is never going forward even if the forward direction is selected?
I'm using ThirdPersonController as player i also tried with a cube.

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

public class DirsFinder : MonoBehaviour
{
    enum Directions
    {
        Forward,Backward,Left,Right
    }

    public Transform player;

    private Transform start;
    private Transform end;
    private GridGenerator gridgenerator;
    public List<Vector3> possibleDirections = new List<Vector3>();
    private Vector3 direction;
    private float m_distanceTraveled = 0f;

    public void Find()
    {
        gridgenerator = GetComponent<GridGenerator>();
        GenerateStartEnd();
        FindDirections();
        m_distanceTraveled = 0;
    }

    private void FindDirections()
    {
        possibleDirections = new List<Vector3>();
        Vector3 playerPosition;
        playerPosition = player.localPosition;

        if (playerPosition.x > 0)
        {
            // can go left
            possibleDirections.Add(Vector3.left);
        }

        if (playerPosition.x + 1.5f < gridgenerator.gridWidth * 1.5f)
        {
            // can go right
            possibleDirections.Add(Vector3.right);
        }

        if (playerPosition.z > 0)
        {
            // can go backward
            possibleDirections.Add(Vector3.back);
        }

        if (playerPosition.z + 1.5f < gridgenerator.gridHeight * 1.5f)
        {
            // can go forward
            possibleDirections.Add(Vector3.forward);
            print("I'm moving forward !!!!!");
        }

        direction = possibleDirections[Random.Range(0, possibleDirections.Count - 1)];

        if (player.position == start.position)
            player.forward = direction;
    }

    private void Update()
    {
        if (m_distanceTraveled < 1.5f)
        {
            Vector3 oldPosition = player.position;
            player.position += direction * Time.deltaTime * 1f;
            m_distanceTraveled += Vector3.Distance(oldPosition, player.position);
        }
    }

    private List<Vector3> GenerateStartEnd()
    {
        GameObject walls = GameObject.Find("Walls");
        List<Transform> wallsParents = new List<Transform>();
        List<Vector3> startEndPos = new List<Vector3>();

        foreach (Transform child in walls.transform)
        {
            wallsParents.Add(child);
        }

        for (int i = 0; i < 2; i++)
        {
            wallsParents.Remove(wallsParents[Random.Range(0, wallsParents.Count)]);
        }

        var childsWall0 = wallsParents[0].GetComponentsInChildren<Transform>().ToList();
        var childsWall1 = wallsParents[1].GetComponentsInChildren<Transform>().ToList();
        childsWall0.RemoveAt(0);
        childsWall1.RemoveAt(0);

        start = childsWall0[Random.Range(0, childsWall0.Count)];
        player.position = start.position;
        end = childsWall1[Random.Range(0, childsWall1.Count)];
        end.tag = "End";
        startEndPos.Add(start.position);
        startEndPos.Add(end.position);

        start.GetComponent<Renderer>().material.color = Color.red;
        end.GetComponent<Renderer>().material.color = Color.blue;

        return startEndPos;
    }
}

```

Inside the FindDirections bottom i'm making the player to be facing to the selected direction:

```
if (player.position == start.position)
    player.forward = direction;

```

Then in the Update i'm moving the player by 1.5 fistance on the selected direction.

It's working fine on the 3 directions: Left , Right , Backward

But when it's selecting the forward direction i see the player is moving right. I tried many times and it's never moving forward on the grid.

I can't figure out why it's not moving forward it does selecting the forward direction sometimes but it's not making the player moving forward on the grid.

In the screenshot it's example of a grid the blue circle is the player the red arrows are what the player is moving and the black arrow should be forward but it's never moving that direction. When it's forward it's moving to the right but never to the black arrow direction as forward should be:

# Answer
Unity Documentation: Random.Range

> public static int Range(int min, int max); Description
>
> Returns a random integer number between min \[inclusive\] and max \[exclusive\] (Read Only).
>
> Note that max is exclusive, so using Random.Range( 0, 10 ) will return values between 0 and 9.

You're off by one on your `Random.Range` call, so forward never gets selected.
> 1 votes

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


# Question
Title: Surprisingly, in SpriteKit game engine, "deltaTime" is not frame time?
In Apple's cocos-like 2D enginer, SpriteKit, they have what they call a custom field:

```
testField = SKFieldNode.customField{
      (position: vector_float3, velocity: vector_float3,
      mass: Float, charge: Float, deltaTime: TimeInterval) in

            print("deltaTime \(deltaTime)")
            return vector_float3(0,0,0)
        }
addChild(testField)

```

the values printed out are simply the cumulative time, not the frame delta time!

Interestingly the documentation is ambiguous or just wrong:

https://developer.apple.com/documentation/spritekit/skfieldforceevaluator

1. notce there it uses the argument name "time", however
2. however, the documentation-writer wrote "time that has passed since the last time the simulation was executed" (ie, the usual frame time you'd expect), and
3. each Apple code fragment I've dug up uses "deltaTime" as the argument name, and the author treats it as a normal frame time like you'd expect in any game engine setting

I've tried it on as many devices/OS as at hand - has anyone found the definitive resolution of this? Is it really meant to be (fairly uselessly) time rather than deltaTime?

**Question, Does anyone definitively know if the value returns cumulative time, or, delta time?**

(If the former it would appear that the doco is completely wrong.)

**Question, In the so-called "deltaTime" argument of Apple's spriteKit, what is returned?**

# Answer
Your observations are accurate: the last parameter to `SKFieldForceEvaluator` is the total time elapsed since the simulation began. That doesn't mean "delta time is not frame time" across all of SpriteKit, just that the evaluator callback doesn't get a delta time value.

The documentation on Apple's website *is* wrong; it states that the last parameter is

> The amount of time that has passed since the last time the simulation was executed

but the actual value provided to the block is definitely not a delta (the `@param` for the parameter in the header is "The current time step," which isn't any better).

But this is because `SKFieldNode`s can be sampled on-demand (via `sampleFields:` on a `SKPhysicsWorld` for example) potentially many times per frame, and they aren't meant to be the place where you implement the usual delta-time-based game logic. You should put that in `SKScene`'s `update:`, which gives you the elapsed system time (which is also not a delta, but from which the delta can be trivially computed by storing a previous time in your scene subclass).

The time/deltaTime name discrepancy is just because the block parameters you make can be called anything; “bob” would be fine.
> 2 votes

---
Tags: ios, spritekit
---


# Question
Title: Does Game Maker Studio 2 have a 'room edge' variable or similar?
I made a sort of "floating camera" for a 2-D platforming game set to follow the player by default but can be made to snap to a stationary point in a room for boss battles and the like, but I've encountered a bit of a problem. Namely that this camera has a tendency to show the outside of the room as the player gets closer to its boundaries, which ultimately reveals my levels to be surrounded by an unsightly void beyond the reach of my room tile assets. In short, I need a way to make a camera object only show what's within the boundaries of a room like a Viewport does, without actually resorting to a pure viewport camera as that does not seem capable of changing which object it follows like I need it to. Any advice?

For reference, here is the basic script I am using for this "floating" camera:

Create event:

```
camera = camera_create();

var vm = matrix_build_lookat(x,y,-10,x,y,0,0,1,0);
var pm = matrix_build_projection_ortho(512,384,1,500);

camera_set_view_mat(camera,vm);
camera_set_proj_mat(camera,pm);

view_camera[0] = camera;

follow = obj_player;
xTo = x;
yTo = y;

boss_level = true;

```

Step event:

```
x += (xTo - x)/25;
y += (yTo - y)/25;

if (follow != noone)
{
    xTo = follow.x;
    yTo = follow.y;

}

var vm = matrix_build_lookat(x,y,-9,x,y,0,0,1,0);
camera_set_view_mat(camera,vm);

if(boss_level && distance_to_object(obj_boss_marker) <= 256)
    follow = obj_boss_marker;
else
    follow = obj_player;

```

# Answer
Try something like this:

```
var viewWidth = 512;
var viewHeight = 384;

var posx = clamp(x, viewWidth div 2, room_width - viewWidth div 2 - 1);
var posy = clamp(y, viewHeight div 2, room_height - viewHeight div 2 - 1);

var vm = matrix_build_lookat(posx,posy,-9,posx,posy,0,0,1,0);
camera_set_view_mat(camera,vm);

```
> 1 votes

---
Tags: camera, game-maker
---


# Question
Title: Swing KeyListener doesn't work when pressing Shift X Z and directions at the same time
My code:

```
addKeyListener(new KeyListener() {
    @Override
    public void keyPressed(KeyEvent event) {
        if (event.getKeyCode() >= KeyEvent.VK_LEFT && event.getKeyCode() <= KeyEvent.VK_DOWN)
            direction.set(event.getKeyCode() - KeyEvent.VK_LEFT, true);
        if (event.getKeyCode() == KeyEvent.VK_Z) direction.set(4, true);
        if (event.getKeyCode() == KeyEvent.VK_CONTROL)          System.out.println(event.getKeyCode());
    }

    @Override
    public void keyReleased(KeyEvent event) {
        if (event.getKeyCode() >= KeyEvent.VK_LEFT && event.getKeyCode() <= KeyEvent.VK_DOWN) {
            speed = event.isShiftDown() ? 1 : fastSpeed;
            direction.set(event.getKeyCode() - KeyEvent.VK_LEFT, false);
        }
        if (event.getKeyCode() == KeyEvent.VK_Z) direction.set(4, false);
    }

    @Override
    public void keyTyped(KeyEvent keyEvent) {
    }
});

```

I start my application and press `Shift`, `Z`, and `X` at the same time, at this moment everything was fine (Successfully see command line output).
But when I press UP or DOWN, swing isn't invoking my listener (no command line output).

I've repeated many times and it's all the same.

Is there any work-arounds?

# Answer
From your recapitulation this might be an key rollover problem.

The term *key rollover* describes a tradeoff in keyboard design complexity for reduced production cost. Many standard keyboards have issues detecting more than three keys being pressed simultaneously.

As you are using Swing, that means you are using java. So in order to find out if it is a software or a hardware limitation you could try the following things:

* write a simple Swing application that only outputs the pressed keys and see if the input combo works
* write an even simpler AWT application, instead of using Swing, to really only output key-input to make some tests
* write a simple JavaFX application, instead of either AWT or Swing. JavaFX is the recommended replacement for Swing and if it is a software problem JavaFX is likely to have it fixed
* have a look at LWJGL and it's bindings to the GLFW library which provides an alternative way to get keyboard-inputs (this would allow you to find out if the Java standard libraries are the baddies...)
> 5 votes

---
Tags: java, keyboard, swing
---


title: Saving video to android device (unity)

text:
# Question
Title: Saving video to android device (unity)
How can I create a folder on Android device, download from ftp-server video and save it there?

# Answer
You can create directory in andriod

**using System.IO.Directory.CreateDirectory(path)**

```
string path = "/storage/emulated/0/MyFolder";

 if(!Directory.Exists(path))
      Directory.CreateDirectory(path);

```

and you can download any resource form the web using **WWW**.
> 1 votes

---
Tags: unity, android, client-server
---


# Question
Title: Making a backup of my game and it says it can't find the UnityLockfile?
I am trying to make a backup copy of my game that I have been working on for the past 3 years and I have it saved on an external hard drive and I want to put a copy onto my desktop.

The files and game is copying just fine until it reaches the same issue:

"Item not Found. Could not find this item This is no longer located in F:/Gamefolder/Gamename/Temp. Verify the item's location and try again."

I follow the path and don't see any folder called Temp and I don't recall one being there either but what also bothers me is when I tried it earlier, it said it couldn't copy it because it was open in Unity, long after I close it(and I checked task manager to be sure)

Does anyone know what this file is or what it does? Also I've put the metadata on so that the game opens normally without me having to set up everything again. Does anyone know if this is necessary to do that?

I'm not a beginner but I'm not a pro, I learn as I go so if any screenshots could be provided they would be a massive help :)

# Answer
Files in the `Temp` and `Library` folders can be ignored when copying, backing up, or checking in a Unity project. Aside from being very large and inconvenient to move around, everything in these folders is derived data which will be regenerated by Unity when you reopen the project.
> 3 votes

# Answer
If you do not want the popup saying the lock file not found. you can copy and paste it to the new folder while Unity editor is closed and it will not do that.
> 0 votes

---
Tags: unity
---


# Question
Title: Unity/UNet without a lobby: How do you get an ordered list of participants (network players)?
Please imagine a turn based multiplayer game. Right now there's no lobby in place and connections are established using Unity's `Network Manager HUD`.

Now on the server, how can you get a list of all the match participants? Preferably ordered - something like the player on the host should be player 1, the first player who joined the match should be player two, the second player who joined should be player three....

Any advise is welcome, thank you.

# Answer
as long as you are inheriting a network behavior you can run a check `if (isLocalPlayer)` add to list. Or you can override the `OnStartLocalPlayer ()`

```
public override void OnStartLocalPlayer()
{
    //Add To Player List
}

```
> 1 votes

---
Tags: unity, unity-networking, unet
---


# Question
Title: Why does UE crash when I spawn a tile actor like this?
I'm trying to replicate a version of "Paper.io" using Unreal Engine and C++ as an exercise.

My idea is to have an instance of an Actor (that is my "Grid class" in this case), and another Actor acting like "tiles", so i made another class called "Tile". This is the constructor code of the class "Tile":

```
ATile::ATile()
{
    // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    if (!RootComponent)
    {
        RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));
    }

    TileMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Tile Mesh"));

    static ConstructorHelpers::FObjectFinder<UStaticMesh> PlaneMesh(TEXT("/Engine/BasicShapes/Plane.Plane"));

    if (PlaneMesh.Succeeded())
    {
        TileMesh->SetupAttachment(RootComponent);
        TileMesh->SetStaticMesh(PlaneMesh.Object);
    }
}

```

Each time i drag and drop this file into the scene, i can easily see the Plane Mesh in the World, so i believe this is working so far.

Into my Grid class i defined my array in this way:

```
TArray<ATile*> Grid;

```

And what i'd like to do now, is to populate this array of Tile's instances. I've been looking around for a solution for tons of time but i still can't figure out how to do it. I would do something like this:

```
ATile Tile = ATile();

```

But of course it doesn't work. And i also found this documentation: Spawning Actors

I tried to do a similar thing, but since i'm a beginner, everything exploded. I don't really get an error, UE4 just crash, but Visual Studio still compile it.

```
void AGrid::CreateGrid()
{
    for (int x = 0; x <= 5; x++)
    {
        for (int y = 0; y <= 5; y++)
        {
            ATile* Tile = GetWorld()->SpawnActor<ATile>(ATile::StaticClass());
            Grid.Add(Tile);
        }
    }
}

```

How could i make this work? Am i doing something wrong?

EDIT 1: I added the suggested line of code, but it still keep crashing.

> Access violation - code c0000005 (first/second chance not available)
>
> UE4Editor\_Engine!UWorld::SpawnActor() \[d:\build++ue4+release-4.18+compile\sync\engine\source\runtime\engine\private\levelactor.cpp:303\] UE4Editor\_Engine!UWorld::SpawnActor() \[d:\build++ue4+release-4.18+compile\sync\engine\source\runtime\engine\private\levelactor.cpp:293\] UE4Editor\_Paper!AGrid::CreateGrid() \[c:\users\paradisee\desktop\c++\paper\source\paper\grid.cpp:30\] UE4Editor\_Paper!AGrid::AGrid() \[c:\users\paradisee\desktop\c++\paper\source\paper\grid.cpp:20\] UE4Editor\_CoreUObject!UClass::CreateDefaultObject() \[d:\build++ue4+release-4.18+compile\sync\engine\source\runtime\coreuobject\private\uobject\class.cpp:2728\] UE4Editor\_CoreUObject!UObjectLoadAllCompiledInDefaultProperties() \[d:\build++ue4+release-4.18+compile\sync\engine\source\runtime\coreuobject\private\uobject\uobjectbase.cpp:795\] UE4Editor\_CoreUObject!ProcessNewlyLoadedUObjects() \[d:\build++ue4+release-4.18+compile\sync\engine\source\runtime\coreuobject\private\uobject\uobjectbase.cpp:869\] UE4Editor\_CoreUObject!TBaseStaticDelegateInstance::ExecuteIfSafe() \[d:\build++ue4+release-4.18+compile\sync\engine\source\runtime\core\public\delegates\delegateinstancesimpl.h:1027\] UE4Editor\_Core!TBaseMulticastDelegate::Broadcast() \[d:\build++ue4+release-4.18+compile\sync\engine\source\runtime\core\public\delegates\delegatesignatureimpl.inl:937\] UE4Editor\_Core!FModuleManager::LoadModuleWithFailureReason() \[d:\build++ue4+release-4.18+compile\sync\engine\source\runtime\core\private\modules\modulemanager.cpp:487\] UE4Editor\_Projects!FModuleDescriptor::LoadModulesForPhase() \[d:\build++ue4+release-4.18+compile\sync\engine\source\runtime\projects\private\moduledescriptor.cpp:476\] UE4Editor\_Projects!FProjectManager::LoadModulesForProject() \[d:\build++ue4+release-4.18+compile\sync\engine\source\runtime\projects\private\projectmanager.cpp:69\] UE4Editor!FEngineLoop::LoadStartupModules() \[d:\build++ue4+release-4.18+compile\sync\engine\source\runtime\launch\private\launchengineloop.cpp:2577\] UE4Editor!FEngineLoop::PreInit() \[d:\build++ue4+release-4.18+compile\sync\engine\source\runtime\launch\private\launchengineloop.cpp:1992\] UE4Editor!GuardedMain() \[d:\build++ue4+release-4.18+compile\sync\engine\source\runtime\launch\private\launch.cpp:127\] UE4Editor!GuardedMainWrapper() \[d:\build++ue4+release-4.18+compile\sync\engine\source\runtime\launch\private\windows\launchwindows.cpp:134\] UE4Editor!WinMain() \[d:\build++ue4+release-4.18+compile\sync\engine\source\runtime\launch\private\windows\launchwindows.cpp:210\] UE4Editor!\__scrt\_common\_main\_seh() \[f:\dd\vctools\crt\vcstartup\src\startup\exe\_common.inl:253\] kernel32 ntdll

# Answer
> 4 votes
In your original code:

```
ATile* Tile = GetWorld()->SpawnActor<ATile>(GetClass());

```

The parameter to this overload of `SpawnActor` is the type of the actor to *spawn*. You're calling `GetClass()` on the `AGrid`, but trying to cast the resulting `AGrid` actor to an `ATile`. This is legal C++, which is why it compiles; it will fail at runtime.

You want:

```
ATile* Tile = GetWorld()->SpawnActor<ATile>(ATile::StaticClass());

```

(e.g., the type of the thing you want to *create*, not the type of the thing creating it)

Based on your edit, it's also apparent that you're calling `CreateGrid()` inside the constructor for `AGrid`, where `GetWorld()` may (and does, in the case of the class default object that you're constructing -- the `UClass::CreateDefaultObject` call on the stack) return a null pointer.

You should probably call `CreateGrid` during the `BeginPlay` overload of the `AGrid` actor, or a similarly later call (such as `OnConstruction`), depending on your specific needs.

You could also just check the result of `GetWorld()`, and if it is null, skip the spawn attempt.

---
Tags: c++, unreal-4, spawning
---


# Question
Title: Unity C# combining two areas each represented by a vector
have two areas, which are both given in there bounds.size. Now the z-axis doesnt matter for me, since im working in 2D. I want to add these vectors so i have a vector, which represents the jointed area. Simply adding these vectors the normal way does not work. The way the area looks in the end is not important, its just important that the size is the same as, both areas combined.

I have the bounds.size of two polygoncolliders and i want to get a value that represents the bounds.size of the two polygoncolliders combined

https://i.stack.imgur.com/avmcl.png

area 1 and area 2

Edit: it has to work in this scenario also:

# Answer
> I have the bounds.size of two polygoncolliders

```
Bounds CombineBounds(Bounds a, Bounds b) {
    // Grow a copy of the first Bounds to include
    // the min & max points of the second Bounds.
    a.Encapsulate(b.min);
    a.Encapsulate(b.max);
    return a;
}

```

You can check the returned `Bounds` object's `size` property to get the total size of the combined bounds.
> 2 votes

# Answer
Credits for this answer go to Flater: https://stackoverflow.com/users/952296/flater

As there are nigh infinite possibilities otherwise, I'm going to limit myself to results where x = y, for the simple reason that you don't end up with silly vectors like (0.5,80000) but rather a more balanced (200,200).

This isn't all that hard when you look at it algebraically:

float result\_area = first\_area + second\_area;

Calculating the area is easy:

float area = myVector.X * myVector.Y;

Thus rendering the sum of the areas also easy:

float result\_area = myFirstVector.X * myFirstVector.Y + mySecondVector.X * mySecondVector.Y;

For the sake of example, let's say first\_area = 50 and second\_area = 350, thus resulting in result\_area = 400;

Since we are limited to results where x = y, the result is the square root of the area:

float theSquareRoot = Math.Sqrt(result\_area); myResultVector.X = theSquareRoot; myResultVector.Y = theSquareRoot;

As I said, there are many other possible result vectors. For other cases, you're either going to have to define a given ratio (e.g. a ratio of 1 : 4 would give you (10,40) for the same example), but the calculation is a bit harder and you mentioned that you don't care about the exact shape anyway.

You could also just make a vector where X = result\_area and Y = 1 (or vice versa), without having to calculate a square root.

Note that you've overengineered it. The area of an object is a onedimensional value (a number); yet you're expressing it using a twodimensional value (a number pair) to represent them. Since you don't care about particular X/Y values, only what their product is, I would suggest you avoid vectors where possible, so you don't make it unnecessarily complicated.
> 0 votes

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