# Question
Title: ASSIMP library imports wrong number of bones from COLLADA file
I have a COLLADA(.dae) file exported from Blender, also I have program that read all data from structure generated with Assimp and I want to translate all data in more readable format. Problem appears when I want to read aiBone structure from aiMesh from aiNode from aiScene: my program shows wrong number of bones. It's only a simple figure with few bones, without animation. I don't know where is problem. In my program logic or Assimp or Blender...

* Assimp 3.3.1
* OpenGL 4.0.
* Blender 2.78c

My code

```
void start(){
    Importer importer;
    unsigned int flags = 0;// aiProcess_Triangulate | aiProcess_GenNormals | aiProcess_FlipUVs;
    const aiScene* scene = importer.ReadFile(filePath, flags);
    if (!scene || scene->mFlags&& AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) {
        cout << "Model::'" << filePath << "':" << importer.GetErrorString() << endl;
        system("pause");
        return;
    }
    cout << "Model loaded" << endl;
    showHierarchy(scene, scene->mRootNode);
}

void showHierarchy(const aiScene* scene, aiNode* currNode) {
        string boneName = currNode->mName.C_Str();
        aiNode* parent = currNode->mParent;
        string parentName = parent == NULL ? "NO ROOT" : parent->mName.C_Str();

        unsigned int* meshesIndexes = currNode->mMeshes;
        cout << "Num. meshes: " << currNode->mNumMeshes << endl;

        for (int nrMesh = 0; nrMesh < currNode->mNumMeshes; ++nrMesh) {
            aiMesh* mesh = scene->mMeshes[meshesIndexes[nrMesh]];
            if (mesh->mNumBones > 0) {
                cout << "Num. bones: " << mesh->mNumBones << endl;
                aiBone** bones = mesh->mBones;
                for (int nrBone = 0; nrBone < mesh->mNumBones; ++nrBone) {
                    aiBone* bone = bones[nrBone];
                    cout << "Bone "<<nrBone<<": " << bone->mName.C_Str() << endl;
                }
            }
        }

        //for each child do the same operations
        for (int nrChild = 0; nrChild < currNode->mNumChildren; ++nrChild) {
            showHierarchy(scene, currNode->mChildren[nrChild]);
        }
}

```

Maybe will help

```
<node id="Armature" name="Armature" type="NODE">
        <translate sid="location">-1.290625 0.08518557 -3.139279</translate>
        <rotate sid="rotationZ">0 0 1 0</rotate>
        <rotate sid="rotationY">0 1 0 0</rotate>
        <rotate sid="rotationX">1 0 0 0</rotate>
        <scale sid="scale">2.297401 2.297401 2.297401</scale>
        <node id="Bone" name="Bone" sid="Bone" type="JOINT">
          <matrix sid="transform">1 0 2.38419e-7 0.5586469 2.38419e-7 0 -1 -0.01256594 0 1 0 0.9420496 0 0 0 1</matrix>
          <node id="Bone_001" name="Bone.001" sid="Bone_001" type="JOINT">
            <matrix sid="transform">1 6.41312e-9 -7.15169e-7 0 1.28262e-8 0.9996382 0.02689855 0.48549 7.15083e-7 -0.02689855 0.9996381 0 0 0 0 1</matrix>
            <node id="Bone_002" name="Bone.002" sid="Bone_002" type="JOINT">
              <matrix sid="transform">1 -3.70967e-8 2.378e-7 0 1.85446e-8 0.9997111 0.02403316 0.3515059 -2.38796e-7 -0.02403316 0.9997112 3.72529e-9 0 0 0 1</matrix>
              <node id="Bone_006" name="Bone.006" sid="Bone_006" type="JOINT">
                <matrix sid="transform">1 1.94806e-7 2.73368e-6 0 2.50534e-6 -0.4732692 -0.8809178 0.5466702 1.11965e-6 0.880918 -0.4732695 0 0 0 0 1</matrix>
                <node id="Bone_007" name="Bone.007" sid="Bone_007" type="JOINT">
                  <matrix sid="transform">-0.9999999 -2.50612e-6 4.84192e-6 0 3.08088e-6 0.4735363 0.8807744 0.3267682 -4.50835e-6 0.8807743 -0.4735363 0 0 0 0 1</matrix>
                  <node id="Bone_008" name="Bone.008" sid="Bone_008" type="JOINT">
                    <matrix sid="transform">1 -4.58268e-7 3.0653e-6 0 2.77133e-8 0.9891911 0.1466312 0.3368657 -3.1009e-6 -0.1466312 0.9891911 -5.96046e-8 0 0 0 1</matrix>
                    <extra>
                      <technique profile="blender">
                        <connect>1</connect>
                        <layer>0</layer>
                        <roll>3.141592</roll>
                        <tip_x>0</tip_x>
                        <tip_y>0.0444796</tip_y>
                        <tip_z>-0.4622855</tip_z>
                      </technique>
                    </extra>
                  </node>
                  <extra>
                    <technique profile="blender">
                      <connect>1</connect>
                      <layer>0</layer>
                      <roll>-3.141596</roll>
                    </technique>
                  </extra>
                </node>
                <extra>
                  <technique profile="blender">
                    <connect>1</connect>
                    <layer>0</layer>
                    <roll>2.86102e-6</roll>
                  </technique>
                </extra>
              </node>
              <node id="Bone_003" name="Bone.003" sid="Bone_003" type="JOINT">
                <matrix sid="transform">1 -2.14772e-7 -9.97458e-8 0 -1.29403e-8 -0.4887015 0.8724509 0.5466702 -2.38636e-7 -0.872451 -0.4887016 0 0 0 0 1</matrix>
                <node id="Bone_004" name="Bone.004" sid="Bone_004" type="JOINT">
                  <matrix sid="transform">1 -2.70245e-8 -2.22184e-7 0 1.97028e-7 0.6096119 0.7927001 0.2557451 1.34571e-7 -0.7927002 0.6096118 0 0 0 0 1</matrix>
                  <node id="Bone_005" name="Bone.005" sid="Bone_005" type="JOINT">
                    <matrix sid="transform">1 -3.3895e-8 -4.78732e-7 0 1.69833e-7 0.9634752 0.2677974 0.4389689 4.5297e-7 -0.2677974 0.9634753 0 0 0 0 1</matrix>
                    <extra>
                      <technique profile="blender">
                        <connect>1</connect>
                        <layer>0</layer>
                        <roll>-7.15256e-7</roll>
                        <tip_x>0</tip_x>
                        <tip_y>-0.08205157</tip_y>
                        <tip_z>-0.4585228</tip_z>
                      </technique>
                    </extra>
                  </node>
                  <extra>
                    <technique profile="blender">
                      <connect>1</connect>
                      <layer>0</layer>
                      <roll>-2.38419e-7</roll>
                    </technique>
                  </extra>
                </node>
                <extra>
                  <technique profile="blender">
                    <connect>1</connect>
                    <layer>0</layer>
                  </technique>
                </extra>
              </node>
              <extra>
                <technique profile="blender">
                  <connect>1</connect>
                  <layer>0</layer>
                  <roll>-2.38419e-7</roll>
                </technique>
              </extra>
            </node>
            <extra>
              <technique profile="blender">
                <connect>1</connect>
                <layer>0</layer>
                <roll>-4.76837e-7</roll>
              </technique>
            </extra>
          </node>
          <extra>
            <technique profile="blender">
              <layer>0</layer>
              <roll>2.38419e-7</roll>
            </technique>
          </extra>
        </node>
      </node>

```

# Answer
> 3 votes
Finally I found the solution. Problem was in vertices. aiBone structure contain, among other things, vertices weights. My 3D model has too few weights and exists bones that don't affect vertices, so Assimp didn't loaded bones that affected 0 vertices.

---
Tags: opengl, assimp
---


# Question
Title: How to add prefabs to the terrain and still retain scripts, colliders, etc.?
I have been working on an old DOS-styled game, and I began work on the trees for my terrain. Here is a group of them:

They, right now, are simply objects in the scene. This works, but is very cumbersome when mass placing them. I want to have them part of the terrain. I tried simply adding them as a detail mesh, but they didn't retain scripts nor colliders. Is there a way to accomplish this?

# Answer
There’s no way to do it directly because they are no longer GameObjects for performance reasons. However, if you add them as tree objects on the terrain, you can write a script that runs on awake which gets the position of the trees and replaces them all programmatically with an instantiated prefab. Use `Terrain.terrainData.treeInstances` for this purpose:

(Note: This is untested)

```
using UnityEngine;

[RequireComponent(typeof(Terrain))]
public class TreeSwapper : MonoBehaviour
{
    //Fill this in the inspector with the prefabs to use in place of the tree prototypes defined in the Terrain object.
    public GameObject[] TreePrototypes;

    void Awake()
    {
        var data = GetComponent<Terrain>().terrainData;

        foreach (var instance in data.treeInstances) {
            var tree = Instantiate(TreePrototypes[instance.prototypeIndex], instance.position, Quaternion.euler(0,Mathf.Rad2Deg * instance.rotation,0), transform);
            tree.transform.localScale = new Vector3(instance.widthScale, instance.heightScale, instance.widthScale);
        }
        data.treeInstances = new TreeInstance[0];
    }
}

```

Note to anybody using this: Terrain does what it does for a very good reason: performance. Don’t expect to be able to put down a ton of trees, run this script, and expect continued good performance.

For that matter, having a script on every tree is a very uncommon use case. You may want to re-examine what you’re doing. Does each tree really need to be doing its own thing?
> 2 votes

---
Tags: unity, terrain
---


# Question
Title: What is the correct order to multiply scale, rotation and translation matrices for a proper world matrix?
Assume DirectX as the platform, if that is important. (Pretty sure it isn't)

Assuming I have a proper scale, rotation and translation matrix, in what order do I multiply them to result in a proper world matrix and why?

By "proper", I mean "I could throw them straight into DirectX and get the most commonly-used 3D frame."

# Answer
*Usually* it is scale, then rotation and lastly translation. With matrix denotation (i.e. \\$T\\$ for translation matrix, \\$R\\$ for the rotation matrix and \\$S\\$ for the scaling matrix) that would be:

$$ T * R * S $$

However, if you want to rotate an object around a certain point, then it is scale, point translation, rotation and lastly object translation.

Why: First you want to scale the object so that the translations work properly. Then you rotate the axes so the translation takes place on the adjusted axes. Finally, you translate the object to its position.

In OpenGL, you can use `gluLookAt` to get a full camera transformation in one call. There is likely a similar call for DirectX.
> 94 votes

# Answer
translation rotation and scaling is the sequence to perform operation
> -4 votes

# Answer
I do believe it is Translation Rotation and Dialation
> -6 votes

---
Tags: matrix
---


title: How can I fix my shadow caster problem?

text:
# Question
Title: How can I fix my shadow caster problem?
I'm trying to make invisible object with shadow by using it's shadow castting pass it additionaly shades back side of object itself. I mean object shades his back side and draws shadow on the background surface.(my unity version is Unity 5.6)

you can see this problem in below animated gif:

this is my shader for unity's shadow pass:

```
Shader "Test/ShadowCaster"
{
    SubShader
    {
    Tags{ "LightMode" = "ShadowCaster"  }
    Name "ShadowCaster"
        Pass
    {
        CGPROGRAM

#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_shadowcaster
#pragma fragmentoption ARB_precision_hint_fastest

#include "UnityCG.cginc"

        struct v2f
    {
        V2F_SHADOW_CASTER;
    };

    v2f vert(appdata_base v)
    {
        v2f o;
        TRANSFER_SHADOW_CASTER_NORMALOFFSET(o)
        return o;
    }

    float4 frag(v2f i) : COLOR
    {
        SHADOW_CASTER_FRAGMENT(i)
    }
        ENDCG
    }
    }
        FallBack Off
}

```

# Answer
I solved this problem by adding `Transparent` Queue tag to my shader.

```
Tags{ "Queue" = "Transparent" "LightMode" = "ShadowCaster" }

```

> Transparent - this render queue is rendered after Geometry and AlphaTest, in back-to-front order. Anything alpha-blended (i.e. shaders that don’t write to depth buffer) should go here (glass, particle effects).
>
> https://docs.unity3d.com/Manual/SL-SubShaderTags.html

Useful link for learning shadow casters in unity.
> 1 votes

---
Tags: unity, fragment-shader, shadows, shaderlab
---


# Question
Title: How much detail should I provide in reference material to potential contract composers?
I'm not very good with music, so when the time comes I'll need help from a composer for my game. I'm unsure of how to actually work with one.

Despite my lack of musical understanding, I know what I like. I might listen to some music and think "Hey, this kind of music would be awesome to have in the epic chase scene near the end of the game, where our heroes just *barely* manage to escape!"

When I go to hire a composer to make music for my game, how much detail and reference music should I provide? Should I provide lots of long descriptions of what I'm after, lots of links to music that I think fits the theme? Or should I just let the composer play the silent game and work it out themselves?

# Answer
I think it's going to vary from composer to composer really. And whether you are giving them wide creative freedom to compose, or are restricting them by asking for a very specific style or sound.

It's like asking a 3D artist to create something for you. You might be very vague and just say, "I want the content to convey the idea of great age and decay" and let them ask you questions back and try things out. Or you might say, "I want a style that is exactly like game X" and they will be more of a copier as opposed to originator of content.

If you're looking for a composer (as opposed to a copier), I would highly recommend you read some interviews with the Grammy-nominated composer Austin Wintory. In many interviews, he talks quite a bit about how he works with game developers.

Here are some links to interviews where he describes the process...

https://www.keengamer.com/article/17144\_interview-with-gaming-composer-austin-wintory

https://www.polygon.com/features/2016/2/16/10970474/journey-live-austin-wintory-fifth-house-ensemble-kickstarter

https://popgeeks.net/award-winning-composer-austin-wintory-on-working-in-video-games-interview/

https://www.rollingstone.com/glixel/interviews/a-day-with-grammy-nominated-game-composer-austin-wintory-w471406

http://www.zam.com/article/1493/austin-wintory-on-composing-absolver-a-game-about-friendship-through-fighting

Again it may not be how everyone works, but should give you some good insights into the process as others have experienced it.
> 0 votes

# Answer
I'd say that the answer to this evolves depending on where exactly you are in the game development process. If you're just starting out and are trying to figure out the mood and style of a game, perhaps you would spend more time allowing the composer to experiment, bouncing their music to inspire your concept artists' and writers' work and vice versa.

However, if you have a clear idea of the mood that you want in a game, it's better to be specific. However, I'd say try to avoid direct comparisons to other games, as then your music just ends up sounding like that other composer's and not your team's. What you come up with to fit your own unique world will end up being better if it matches **your** world and not someone else's. Give them concept art, bits of writing, etc. that define your world, then have them ask you questions. Each person's creative process is different, so some things will help one composer but not others.
> 0 votes

---
Tags: music, teamwork
---


title: A question about SharpDx Colored Cube

text:
# Question
Title: A question about SharpDx Colored Cube
Recently I start to study SharpDx, so I am a newbie for it. I try to create a cube which has difference color on each vertex such as the picture below.

However, what I created after my coding is something I'm not understand such as the picture below.

I have checked my code many time but still couldn't find out what was wrong with it. I hope somebody can point it out for me. Many Thanks.

Hear is My Code

InitializeDirectX:

```
    int width = renderForm.ClientSize.Width;
    int height = renderForm.ClientSize.Height;
    Rational rational = new Rational(60, 1);
    ModeDescription backBufferDesc = new ModeDescription(width, height, rational, Format.R8G8B8A8_UNorm);
    SwapChainDescription swapchainDesc = new SwapChainDescription
            {
                ModeDescription = backBufferDesc,
                SampleDescription = new SampleDescription(1, 0),
                Usage = Usage.RenderTargetOutput,
                BufferCount = 1,
                OutputHandle = renderForm.Handle,
                IsWindowed = true,
                SwapEffect = SwapEffect.Discard
            };
    SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapchainDesc, out device, out swapChain);
    context = device.ImmediateContext;

    RasterizerStateDescription rasterDescription = RasterizerStateDescription.Default();
    rasterDescription.FillMode = FillMode.Solid;
    rasterDescription.CullMode = CullMode.None;
    rasterDescription.IsDepthClipEnabled = false;
    RasterizerState rasterizerState = new RasterizerState(device, rasterDescription);
    context.Rasterizer.State = rasterizerState;

    DepthStencilStateDescription depthStencilDesciption = DepthStencilStateDescription.Default();
    depthStencilDesciption.DepthComparison = Comparison.LessEqual;
    depthStencilDesciption.IsDepthEnabled = true;
    DepthStencilState depthStencilState = new DepthStencilState(device, depthStencilDesciption);
    context.OutputMerger.SetDepthStencilState(depthStencilState);

    Utilities.Dispose<RenderTargetView>(ref renderTargetView);
    Texture2D backBuffer = swapChain.GetBackBuffer<Texture2D>(0);
    renderTargetView = new RenderTargetView(device, backBuffer);
    backBuffer.Dispose();

    Texture2D zBuffer = new Texture2D(device, new Texture2DDescription
            {
                Format = Format.D16_UNorm,
                ArraySize = 1,
                MipLevels = 1,
                Width = renderForm.ClientSize.Width,
                Height = renderForm.ClientSize.Height,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            });
    depthStencilView = new DepthStencilView(device, zBuffer);
    zBuffer.Dispose();

    context.Rasterizer.SetViewport(0, 0, renderForm.ClientSize.Width, renderForm.ClientSize.Height);
    context.OutputMerger.SetTargets(depthStencilView, renderTargetView);

```

My Hlsl:

```
    cbuffer CameraConstant:register(b0) {
        matrix World;
        matrix View;
        matrix Projection;
    };

    struct VS_IN
    {
        float4 position : POSITION;
        float4 color : COLOR;
    };

    struct PS_IN
    {
        float4 position : SV_POSITION;
        float4 color : COLOR;
    };

    PS_IN VS(VS_IN input)
    {
        PS_IN output = (PS_IN)0;
        output.position = mul(input.position, World);
        output.position = mul(output.position, View);
        output.position = mul(output.position, Projection);
        output.color = input.color;

        return output;
     }

     float4 PS(PS_IN input) : SV_Target
     {
        return input.color;
     }

```

LoadContent：

```
    filename = "Hlsls\\cube.txt";
    shaderByteCode = ShaderBytecode.CompileFromFile(filename, "VS", "vs_5_0");
    vertexShader = new VertexShader(device, shaderByteCode);
    shaderSignature = ShaderSignature.GetInputSignature(shaderByteCode);
    inputLayout = new InputLayout(device, shaderSignature, new InputElement[]
            {
                new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
                new InputElement("COLOR",0,Format.R32G32B32_Float,12,0)
            });

    shaderByteCode = ShaderBytecode.CompileFromFile(filename, "PS", "ps_5_0");
    pixelShader = new PixelShader(device, shaderByteCode);

    Eye = new Vector3(0.0f, 1.0f, 1.5f);
    Target = new Vector3(0.0f, -0.1f, 0.0f);
    CameraUp = Vector3.UnitY;

    Angle = (float)Math.PI / 3.0f;
    Ratio = (float)(renderForm.ClientSize.Width) / (float)(renderForm.ClientSize.Height);
    NearestSight = 0.1f;
    FarrestSight = 100.0f;

    Projection = Matrix.Transpose(Matrix.PerspectiveFovLH(Angle, Ratio, NearestSight, FarrestSight));
    View = Matrix.Transpose(Matrix.LookAtLH(Eye, Target, CameraUp));
    World = Matrix.Transpose(Matrix.RotationY(0));
    CameraConstant camera = new CameraConstant();
    camera.World = World;
    camera.View = View;
    camera.Projection = Projection;
    constantBuffer = SharpDX.Direct3D11.Buffer.Create(device, BindFlags.ConstantBuffer, ref camera);

    verts = new PositionColorVertex[]
            {
                new PositionColorVertex(new Vector3(-0.5f,-0.5f,-0.5f),new Vector3(0.0f,0.0f,0.0f)),
                new PositionColorVertex(new Vector3(-0.5f,-0.5f,0.5f),new Vector3(0.0f,0.0f,1.0f)),
                new PositionColorVertex(new Vector3(-0.5f,0.5f,-0.5f),new Vector3(0.0f,1.0f,0.0f)),
                new PositionColorVertex(new Vector3(-0.5f,0.5f,0.5f),new Vector3(0.0f,1.0f,1.0f)),
                new PositionColorVertex(new Vector3(0.5f,-0.5f,-0.5f),new Vector3(1.0f,0.0f,1.0f)),
                new PositionColorVertex(new Vector3(0.5f,-0.5f,0.5f),new Vector3(1.0f,0.0f,1.0f)),
                new PositionColorVertex(new Vector3(0.5f,0.5f,-0.5f),new Vector3(1.0f,1.0f,0.0f)),
                new PositionColorVertex(new Vector3(0.5f,0.5f,0.5f),new Vector3(1.0f,1.0f,1.0f))
            };
    vertexBuffer = SharpDX.Direct3D11.Buffer.Create(device, BindFlags.VertexBuffer, verts);

    indeces = new int[]
            {
                0,2,1,1,2,3,
                4,5,6,5,7,6,
                0,1,5,0,5,4,
                2,6,7,2,7,3,
                0,4,6,0,6,2,
                1,3,7,1,7,5
            };
    indexBuffer = SharpDX.Direct3D11.Buffer.Create(device, BindFlags.IndexBuffer, indeces);

```

RenderEffect:

```
    context.ClearRenderTargetView(renderTargetView, backgroundColor);
    context.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth, 1.0f, 0);
    context.VertexShader.Set(vertexShader);
    context.VertexShader.SetConstantBuffer(0, constantBuffer);
    context.PixelShader.Set(pixelShader);
    context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, Utilities.SizeOf<PositionColorVertex>(), 0));
    context.InputAssembler.SetIndexBuffer(indexBuffer, Format.R16_UInt, 0);
    context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
    context.InputAssembler.InputLayout = inputLayout;
    context.DrawIndexed(indeces.Length, 0, 0);
    swapChain.Present(1, PresentFlags.None);

```

Many Thanks to the one who can point out my problems in these codes.

# Answer
> 1 votes
Finally, I found what the problem is. My indeces is an array which type is int, so during my render period, I should set my index buffer format 32byte such as Format.R32\_UInt, rather than Format.R16\_UInt. After I update the format that related to the indexbuffer and , bingo, the problem is solved.

---
Tags: c#, directx11, sharpdx, vertex-buffer, index-buffer
---


title: Change Material color programmatically

text:
# Question
Title: Change Material color programmatically
I'm writing a simple C# Script to change Materials color of a object.

```
public class Highlight : MonoBehaviour {

    public bool Mouse_Over = false;
    public Color Highlight_Color = Color.white;
    private Renderer rend;
    private Material[] mats;

    // Use this for initialization
    void Start () {
        rend = this.GetComponentInChildren< Renderer >();
        mats = rend.materials;
    }

    public void ToggleHighlight(bool t){
        if (mats.Length == 0) {
            return;
        }
        for(int i=0; i < mats.Length; i++){
            if (t) {
                rend.materials[i].color = Highlight_Color;
            } else {
                rend.materials[i].color = mats[i].color;
            }
            Debug.Log ("Material_" + i + ".Color = " + mats[i].color.ToHexStringRGBA());
        }
    }

    void OnMouseEnter(){
        if (Mouse_Over) {
            ToggleHighlight (true);
            Debug.Log ("MouseEnter");
        }
    }

    void OnMouseExit(){
        if (Mouse_Over) {
            ToggleHighlight (false);
            Debug.Log ("MouseExit");
        }
    }
}

```

As you can see, I store my original Materials inside the `mats` array, in the `Start` function. This is to revert the renderer Materials to the original Materials, but it isn't working. The color doesn't change to the original value.

I tried to check where the problem was, and in the Debug statement inside the for loop, the color is getting updated also inside `mats` Array. Why is this happening?

Seems like that `mats` is only a pointer to `rend.materials`, am I wrong?

# Answer
I am answering my own question because i have found the problem, it may be useful for someone else.

The problem is that `mats` is just a reference to `rend.Materials`, so changing values inside `rend.Materials`, also changes the values inside `mats`.

I had to create an `Array` of `Colors` to store the original Color of the materials, and then use that array to set the color when I want to revert back to the original color.

```
public class Highlight : MonoBehaviour {

public bool Mouse_Over = false;
public Color Highlight_Color = Color.white;

private Color[] oldColors;
private Renderer rend;

// Use this for initialization
void Start () {
    rend = this.GetComponentInChildren< Renderer >();
    CacheColors ();
}

private void CacheColors(){
    oldColors = new Color[rend.materials.Length];
    for (int i = 0; i < oldColors.Length; i++) {
        oldColors[i] = rend.materials[i].color;
    }
}

public void ToggleHighlight(bool t){
    if (rend.materials.Length == 0) {
        return;
    }
    for(int i=0; i < rend.materials.Length; i++){
        if (t) {
            rend.materials[i].color = Highlight_Color;
        } else {
            rend.materials[i].color = oldColors[i];
        }
    }
}

void OnMouseEnter(){
    if (Mouse_Over) {
        ToggleHighlight (true);
        Debug.Log ("MouseEnter");
    }
}

void OnMouseExit(){
    if (Mouse_Over) {
        ToggleHighlight (false);
        Debug.Log ("MouseExit");
    }
}

```
> 3 votes

# Answer
Just came across this problem myself, many of the answers were old so will update with my solution that works

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

public class Mat_library2 : MonoBehaviour
{
  [Header("Materials")]
  public Material[] myMaterials;
  private Material newMaterial;
  public GameObject elypseTile;
  public int RequiredColorIndex;

  public void Start()
  {
    findAllMaterials();
  }

  public void findAllMaterials()
  {
    //find all materials in resources folder Assets>Resources>Materials>
    myMaterials = Resources.LoadAll("Materials",
    typeof(Material)).Cast<Material>().ToArray();
    Debug.Log("Materials " +
    Resources.FindObjectsOfTypeAll(typeof(Material)).Length);

    foreach (Material mat in myMaterials)
    {
      Debug.Log("Material is: " + mat);
      Debug.Log("RequiredColorIndex: " + RequiredColorIndex);
    }

    //Apply material from indes to game object
    elypseTile.GetComponent<Renderer>().material.color =
    myMaterials[RequiredColorIndex].color;
  }
}

```
> 0 votes

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


# Question
Title: What is the best practice for creating a system of platforms that does not use Unity's tag system?
Right now I'm finalizing my character raycast controller, but have come to the realization that Unity's tag system, which I'm using as a way for my raycasts to detect different types of platforms, is limited and may cause issues further into development when I start adding more platform types, or use the controller for AI (do I want my AI to be affected the same way the player is affected by platforms?).

So far I've got a bunch of different platforms, like passable platforms, icy blocks and jump boosts. These all work great, and change the character's default movement parameters, but I rely on things like this in order for changes to be made:

```
if (hit.collider.tag == "platformPassable")

```

Is there a better way to do this? I am not the most experienced programmer, but my initial solution was to create a Platform class with a TypeOfPlatform enum that will allow me to make sub classes that implement changes based on this type, but I'm worried that having to access a component for each raycast on a platform on which the character or AI is standing will lead to horrible performance issues. Would I have to reference the base class in the character controller, or would I access the character controller in the base class?

I'm just not very comfortable with inheritances like this and would appreciate some guidance.

Update: here's a segment of my code (there are many other likes this) that hopefully helps illustrate what I believe will become problematic as I continue development:

```
private void MoveVertically(ref Vector3 deltaMovement)
{
    float directionY = Mathf.Sign(deltaMovement.y);
    float rayLength = Mathf.Abs(deltaMovement.y) + skinWidth;

    for (int i = 0; i < verticalRayCount; i++)
    {
        Vector2 rayOrigin = (directionY == -1) ? raycastOrigins.bottomLeft : raycastOrigins.topLeft;
        rayOrigin += Vector2.right * (verticalRaySpacing * i + deltaMovement.x);

        RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up * directionY, rayLength, collisionMask);

        Debug.DrawRay(rayOrigin, Vector2.up * directionY * rayLength, Color.red);

        if (hit)
        {
            if (hit.collider.tag == "platformPassable" || hit.collider.tag == "icePassable")
            {
                State.IsCollidingWithPassablePlatform = true;

                if (directionY == 1)
                {
                    State.IsCollidingAbove = false;
                    continue;
                }

                if (CanJumpDown)
                {
                    State.IsCollidingBelow = false;
                    continue;
                }
            }

            if (hit.collider.tag == "iceNormal" || hit.collider.tag == "icePassable")
            {
                Parameters.accelerationTimeGrounded = 1.0f;
                Parameters.accelerationTimeAirborne = 3.0f;
            }

            else if (overrideParameters == null)
            {
                Parameters.accelerationTimeGrounded = defaultParameters.accelerationTimeGrounded;
                Parameters.accelerationTimeAirborne = defaultParameters.accelerationTimeAirborne;
            }

            deltaMovement.y = (hit.distance - skinWidth) * directionY;
            rayLength = hit.distance;

            if (State.IsClimbingSlope)
            {
                deltaMovement.x = deltaMovement.y / Mathf.Tan(State.SlopeAngle * Mathf.Deg2Rad) * Mathf.Sign(deltaMovement.x);
            }

            State.IsCollidingBelow = directionY == -1;
            State.IsCollidingAbove = directionY == 1;
            CanJumpDown = false;
        }
    }

```

As you can see there are a lot of platform types that are somewhat similar. Plus, since this script will be placed on any character, such as the player or the enemy, both of these entities will be bound to the same movement parameters. What if I didn't want an enemy to slide around on an ice block? I'm not sure there's a way to prevent this in my code in its current structure.

# Answer
> 3 votes
Depending on the level of complexity required you could go one of two routes:

If you have a set of GameObjects that represent the different block types and all you need are a set of properties to pass into your player controller, then you could create a simple class that exposes those properties that you can add to the GameObject and create some prefabs for each type:

```
public class Platform : MonoBehaviour {
  public float AccelerationTimeGrounded;
  public float AccelerationTimeAirborne;
  public bool IsPassable;
}

```

The you can just add a "platform" tag to your platforms and grab the `Platform` component:

```
if (hit) {
  if (hit.collider.CompareTag("platform")) {
    var platform = hit.collider.gameObject.GetComponent<Platform>();

    // grab the properties as needed:
    Parameters.accelerationTimeGrounded = platform.AccelerationTimeGrounded;
    Parameters.accelerationTimeAirborne = platform.AccelerationTimeAirborne;
    Parameters.isPassable = platform.IsPassable;
  }
}

```

If however you need more complex requirements (for example you need to calculate some value in different ways depending on the type of platform - for example you want to multiply a value if it's an Ice platform, but only add a value if it's a Rock platform you can use an Interface within the scripts and then have the different types of platform implement them to pass the appropriate values to your player controller:

```
// Interface for all platform classes to inherit from.
interface IPlatform {
  float AccelerationTimeGrounded { get; }
  float AccelerationTimeAirborne { get; }
  bool IsPassable { get; }

  float FinalAcceleration (float current);
}

```

Then you can implement some concrete classes:

```
public class IcePlatform : IPlatform, MonoBehaviour {
   // Expose the properties to the editor with a reasonable default
   [SerializeField]
   private float _accelerationTimeGrounded = 1.0f;
   [SerializeField]
   private float _accelerationTimeAirborne = 3.0f;

   public float AccelerationTimeGrounded { get { return _accelerationTimeGrounded; } }
   public float AccelerationTimeAirborne { get { return _accelerationTimeAirborne; } }
   public bool IsPassable { get { return false; } }

   public bool FinalAcceleration (float current) {
     return current * AccelerationTimeGrounded;
   }
}

// Technically this could inherit from IcePlatform and just override
// the IsPassable property.
public class PassableIcePlatform : IPlatform, MonoBehaviour {
   // Expose the properties to the editor
   [SerializeField]
   private float _accelerationTimeGrounded = 1.0f;
   [SerializeField]
   private float _accelerationTimeAirborne = 3.0f;

   public float AccelerationTimeGrounded { get { return _accelerationTimeGrounded; } }
   public float AccelerationTimeAirborne { get { return _accelerationTimeAirborne; } }
   public bool IsPassable { get { return true; } }

   public bool FinalAcceleration (float current) {
     return current * AccelerationTimeGrounded;
   }
}

public class RockPlatform : IPlatform, MonoBehaviour {
   // Expose the properties to the editor with a reasonable default
   [SerializeField]
   private float _accelerationTimeGrounded = 0.5f;
   [SerializeField]
   private float _accelerationTimeAirborne = 1.0f;

   public float AccelerationTimeGrounded { get { return _accelerationTimeGrounded; } }
   public float AccelerationTimeAirborne { get { return _accelerationTimeAirborne; } }
   public bool IsPassable { get { return false; } }

   public bool FinalAcceleration (float current) {
     return current + AccelerationTimeGrounded;
   }
}

```

You can then use the Interface in your hit check without having to care about what type of `IPlatform` it is:

```
if (hit) {
  if (hit.collider.CompareTag("platform")) {
    // Get the component that implements IPlatform
    var platform = hit.collider.gameObject.GetComponent<IPlatform>();

    // grab the properties as needed:
    Parameters.accelerationTimeGrounded = platform.AccelerationTimeGrounded;
    Parameters.accelerationTimeAirborne = platform.AccelerationTimeAirborne;
    Parameters.isPassable = platform.IsPassable;

    // Call the method:
    float final = platform.FinalAcceleration(someCurrentValue);
  }
}

```

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


# Question
Title: Trying to get an object to move in the mouse direction XNA C#
Right, so in my Player class where I call the object I got an if statement which gets the coordinates for the mouse

```
        bool PickedCoords = true;
        MouseState mouseState = Mouse.GetState();
        if (newState.LeftButton == ButtonState.Pressed && oldState.LeftButton == ButtonState.Released)
        {
            PickedCoords = true;
            int MouseX = mouseState.X;
            int MouseY = mouseState.Y;
        }
        else
        {
            PickedCoords = false;
        }
        oldState = newState; // this reassigns the old state so that it is ready for next time

```

Now how would I make MouseX and MouseY be used as the direction of the vector of my object moving in the specified X and Y coordinates? What I'm, almost trying to do is move the object in the direction of the mouse click and make it continue to move in that direction until it's stopped by whatever.

# Answer
> 1 votes
First you must subtract the the two position vectors, like so:

The Object I use here is just an example as I did not see any in your code snippet.

```
Vector2 Difference = Vector2.Subtract(Object.Position,new Vector2(MouseX,MouseY));

```

This will give you the vector pointing from the object's position to the mouse's position with the actual distance between the two.

After that, as Steven mentioned in the comments you can normalize this vector to get a standard direction vector.

```
Vector2 Direction = Vector2.Normalize(Difference);

```

This will return a standard 1 length direction vector that you can use with a velocity or speed variable to move the Object.

eg.

```
Object.Position += Direction * Velocity;

```

If you want the object to keep moving in the direction, you just don't change the Direction and Velocity, unless a collision or something else happens with the object.

I hope this helps your problem. :)

---
Tags: c#, xna, vector, mouse, gameobject
---


# Question
Title: how to handle server tick update for multiple rooms? (Nodejs)
I'm making a multiplayer game using socketio + nodejs. Currently I use setInterval on my server and requestAnimation on my client render. Now I want to create multiple game instances for each room and so I ask how to do so efficiently:

1. Do I initialize a new setInterval for every game created and call clearInterval when that game ends? or...
2. Should I create only one instance of setInterval and loop through each active game and update them?
3. Should I be using setInterval at all?

EDIT: For clarification, my current single setInterval simply does this at about 15hz:

-update each player position based on input

-notify all clients of new positions

input is received as soon as the client sends them, handled by socketio. Sending this many emits is intentional because my server is authoritative and my game is slow (imagine a snakes clone). I intend to allow as many games as there are rooms, which is indefinite (or as many as one server can handle)

# Answer
> 1 votes
You should remember that nodejs are single-thread. So if you start few setInterval timers with about 15hz - some of times timers may and will start skipping ticks (as setIntercal can do it when loop execution takes more time than interval, or garbage collector doing something every few seconds).

I strongly recommend to NOT start many intervals/loops in single node process. Localize play room into separeted single process, and start as many rooms as want. You can communicate between room's processes using IPC or websockets, with or w/o master process.

---
Tags: node.js, websocket
---


# Question
Title: How to reverse or create a group sprites pinned to other objects on a specific pattern.
Hey guy i am creating a game, where i am facing some problem.

I am creating a sprite, SpriteT on runtime with a rope effect like snake with proper instances. Also am creating Text object pinned on the rope style sprites with instances and need to handle those sprites objects with text instances.

I gave the leadsprite 8 directions where other families are attached to leadsprite.

Now i want is when i rotate the leadsprite to 90 and then to 180 that is top left movement. I need is to compare the instances of equal positions of sprite Whenever i do this the system never compares each value of sprites. i don't know how to compare the elements of one single array that is definately instances to each other's position record and if they match i want to destroy the sprites objects.

this includes i think there must be some pattern now i need to reverse the remaining spriteT to the Leadsprite on the same pattern.. This is where i am lacking whenever i do this

```
  // On Destroyed
    OnObjectDestroyed() {
     // This contain let 10 number of sprite to attached with the center of one next sprite.
         SpriteTObjectFamily.setPositionTowardsObject(ImagePoint0);
    }

```

I have just started and a Noob. Please help this is actually doing in Construct2. Any help would be great. Thanks in Advance!

# Answer
Create the node as parent and inherit other nodes as child. Set position of child nodes as position.parentNode.x and position.parentNode.y which follows the position of your rootNode.
> 1 votes

---
Tags: construct-2
---


title: HLSL MipMap sampling in pixel shader

text:
# Question
Title: HLSL MipMap sampling in pixel shader
Using the Texture2D.Sample function, how does the pixel shader infer the mipmap level to use? Or does it use mipmap level 0? I am using the ps\_4\_0 shader model. And replacing Sample, with SampleLevel(state, pos, 0.0), does that give same results? In what cases does it give same results?

```
struct PS_INPUT
{
    float4 pos                   : SV_POSITION;
    float3 tex : TEXCOORD0;   // texture coordinate
};

struct PS_OUTPUT
{
    float4 color                   : SV_Target0;
};

Texture2D tex;

SamplerState state {
    Filter      = MIN_MAG_LINEAR_MIP_POINT;
    AddressU    = CLAMP;
    AddressV    = CLAMP;
};

PS_OUTPUT main(PS_INPUT input) : SV_Target
{
    PS_OUTPUT output;

    output.color = tex.Sample(state, input.pos);

    return output;
}

```

# Answer
> 4 votes
Sample calculates the mip level to sample based on screen space derivatives of the texture coordinates provided. Derivatives of texture coordinates can be computed as follows:

```
float2 derivX = ddx(myTexCoord.xy);
float2 derivY = ddy(myTexCoord.xy);

```

But this is hidden inside the Sample function implementation. You can achieve the same result by using SampleGrad function and providing the derivatives yourself:

```
float4 textureColor = myTexture.SampleGrad(mySampler, myTexCoord.xy, derivX, derivY);

```

If you use SampleLevel, that expects the mip level instead of the derivatives, but you could compute a mip level from the derivatives yourself and use SampleLevel:

```
float delta_max_sqr = max(dot(derivX, derivX), dot(derivY, derivY));
float mip = 0.5 * log2(delta_max_sqr) * myTexture_NumberOfMIPLevels;
float4 textureColor = myTexture.SampleLevel(mySampler, myTexCoord.xy, mip);

```

However the SampleLevel might not give the exact results of the Sample method because Sample can use a different method based on the sampler descriptor's MipFilter and MipLODBias settings.

Use case:

Calculating derivatives using ddx and ddy needs information from neighbour pixels, so you can't use the functions inside dynamic branches or loops (which are maybe not running for neighboring pixels). In those cases the derivatives could be precomputed and you can use the SampleGrad or SampleLevel instructions inside the dynamic branches/loops.

---
Tags: directx, hlsl
---


# Question
Title: Multiplayer Game - Node.js syncing other players' position
I'm creating a multiplayer platformer game with 4 players in multiple rooms. I've read a lot of articles and researched about client prediction and lag compensations. I think I can somehow manage to understand how to update "my client". But what would be the best approach in the multiplayer platformer game to update "other clients". This is what I'm thinking:

Approach 1: the client sends input "left" to the server -\> server increases the velocity of the player -\> the server sends the actual input "left" of this client to all other clients -\> other clients run the physics on the input.

Apporach 2: the client sends the input to the server -\> server adds velocity, update state -\> game loop in server updates the position of every single client back to everyone, sends it to all clients -\> client gets it and updates.

What would be a better approach? or please if there is a better approach, tell me I am very stuck..

# Answer
> 2 votes
Approach 1) is traditionally used in RTS types of games where timing is very important. However, this approach has the downside of increasing by *a lot* the chances of clients cheating. Since the client simulates the physics and everything else, it has to know the whole state to keep it in sync with other clients. In order to do that, it has to know of the whole state of your simulated world. A clever cheater could just sniff the current state of the memory and know everything there is to know and take advantage of it.

You did not mention it, and I think that's what you're missing: With approach 2), you can broadcast only what the client needs to know: limit that to a region of interest. If the screen covers only a 300 units diameter, there is absolutely no need to tell the player's client what's going on above this region of interest. This limits the amount of data the server needs to send to the client, and reduces the range of available cheats.

# Answer
> 1 votes
1 - Client send input.

2 - Server calculate and broadcast: **destination**, direction, velocity and timing function (if you need acceleration or jump curve).

3 - Unit start moving (on server and on clients with tiny lag difference).

Don't send anything until unit vector changed or user input comes.

---
Tags: multiplayer, client-server, node.js, synchronization
---


# Question
Title: Issue With setting Mesh.triangles in Unity Script
I have been having an issue in making floating islands. For this i have created an array filled with the position data for both the top and bottom half of the island. Everything works fine when i only have the top half of the triangles implimented, but when i add the bottom half of the triangles become triangles that are shifted to the top half of the island.

To be more precise, the traingle index data seems to change while writing it to mesh.triangles.

This happens after mesh.triangles = triangles in the following code

```
    mesh.Clear();

    transform.position = new Vector3(-width/2,0 * scale,-height/2 * scale);

    positionsAll = new Vector3[2 * width * height];

    setupHeightMap();
    int[] triangles = getTriangles();

    mesh.vertices = positionsAll;
    mesh.triangles = triangles;
    mesh.RecalculateNormals();

```

An example watch can be seen here, witth the first four showing the change in index, and the final four showing how the point is the same point but on the above surface.

```
    triangles[0]    30785   System.Int32
    triangles[4]    96322   System.Int32
    mesh.triangles[0]   30785   System.Int32
    mesh.triangles[4]   30786   System.Int32
    mesh.vertices[triangles[0]] "(65.0, 0.0, 120.0)"    UnityEngine.Vector3
    mesh.vertices[triangles[4]] "(66.0, -0.2, 120.0)"   UnityEngine.Vector3
    mesh.vertices[mesh.triangles[0]]    "(65.0, 0.0, 120.0)"    UnityEngine.Vector3
    mesh.vertices[mesh.triangles[4]]    "(66.0, 0.2, 120.0)"    UnityEngine.Vector3

```

This watch data was generated in an instance where all triangles that had positive values were not instanciated, but the same problem hapens if all Triangles are instanciated.

If anyone can tell me why this happens and/or how i can fix this problem that would be extremly helpful. thank you!

# Answer
> 0 votes
It looks like you are trying to create meshes with quite a few vertices. More than 65,536 (2^16) vertices in fact. Until Unity 2017.3 this is not supported, so you would need to split it into two separate meshes. In 2017.3 they added support for 32-bit indices, but you have to enable it per mesh:

```
mesh.IndexFormat = IndexFormat.UInt32;

```

---
Tags: unity, c#, 3d-meshes
---


# Question
Title: Difference between WM_KEYDOWN and GetAsyncKeyState()
I am programming a simple Ping-Pong game in C++ but I don't know how to handle key presses. At first I intended to use WM\_KEYDOWN, but I don't know how to track two pressed keys at once since the window processing function always gets only one wParam right? Basicaly I have two paddles on each side of the screen and when user presses W/S, left paddle moves, when Up/Down keys are pressed, right paddle moves. However when I press two keys at once only one paddle moves.

Another problem is that there is always a short pause after key is pressed - the paddle moves once in desired direction, then pauses and then continues to move. I have no idea why this happens. On the other hand when I use GetAsyncKeyState() like this:

```
if (GetAsyncKeyState('S') & 0x8000)
{
    PingPong.MoveLeftPaddleDown(hWnd);
}

```

everything works as intended - both paddles can move at the same time and there is no short pause on the beginning of movement. On the internet I read everywhere that I should use WM\_KEYDOWN insead of GetAsyncKeyState() but how to configure it properly? Thank you

# Answer
The issue with using `WM_KEYDOWN` they way you are using is, that it's only sent once when the key is pressed down and after that in a fixed interval defined by the OS (key repeat events).

So, if you want to make the `WM_KEYDOWN` approach work like your `GetAsyncKeyState` approach, you need to set a boolean flag in `WM_KEYDOWN`, and remove said flag in `WM_KEYUP`.

Then, in your update method, check the state of the flag, and if it's set, call `PingPong.MoveLeftPaddleDown` . That way your paddle behaviour will be independent from the operating system's key repeat interval.
> 1 votes

---
Tags: c++
---


# Question
Title: How to prevent cube intersecting with other objects when moved around with mouse?
I want to allow the player to freely place cubes anywhere they like in 3D space, but the cube being moved around is not allowed to intersect with other objects.

Currently I do a ray cast based on where the mouse is (ScreenPointToRay), and position the cube at the hit point. This allows me to move the cube around, but it's possible to intersect other objects if the raycast hit is right next to an object.

I see that there is a Physics.BoxCast method, but I can't get this working based on where the mouse position is. Am not sure if this is even the best solution.

I was thinking of ray casting out from each 4 points of each face on the cube (4 up, 4 down, 4 right, 4 left, 4 forward, 4 back), but I feel this is a lot of raycasts just to prevent intersecting on movement and placement for a cube.

How can I prevent a cube that is being moved around, and then placed with the mouse from intersecting other objects?

# Answer
> 2 votes
I can think of three different approaches to your problem. One involves using an object silhouette or shape as a preview of where it's going to be placed; another is a real-time positioning of the object, providing interaction with surrounding instances; the last one is again real-time positioning though by computing the last valid position.

### Paintbrush method

This method allows the user to place the cube in your 3D space by instantiating sort of ghost version of it (e.g. making it look translucent) and moving it around with the mouse, showing where user is going to actually draw it, like if they were using a brush.

All positions are valid for the brush preview, as long as no other objects are intersected; illegal coordinates will highlight the brush model in red hue, for example. You can check if a given position is valid with a simple AABB collision detection algorithm, given axis-aligned cubes.

Clicking a valid position will create a new instance of a cube, allowing the user to instantiate more.

### Follow mouse method #1

With this method you create an actual cube in the first valid position using raycasting at creation only. Next, the cube will try to move as close as possible towards the position in space pointed by the cursor arrow, taking into account collisions with other object.

This way, the cube will be placed in the best possible position with respect to mouse position, being never misplaced since collision detection is active and the cube starting position is valid by definition.

To accomplish such behaviour you must check if the mouse position is a valid position for the cube. If so, place the cube there; otherwise, move the cube as close as possible to the mouse position, taking collisions into account.

### Follow mouse method #2

Similar to the previous one, but if the current mouse position is not valid for the cube, place the cube there and then push it outside from any other instance it may be intersecting with. More tricky, but better results than the first variant.

### Last valid position method

This is pretty much the **Follow Mouse #1** method, but you update the cube position only when the mouse position points to a valid place for the cube; otherwise, the cube stands still.

Concerning implementation, all these methods require only collision detection to make sure cubes don't intersect, not a heavy workload for the CPU since AABB is quite simple and fast. Raycasting is used once only, by one single method. Colliders can be a solution, but you can write your own AABB collision detection algorithm (Jonathan Whiting's tutorial, at "Detecting Rectangle Collision) without the need to import that library, and dealing with such a simple collision tecnique on your own.

---
Tags: unity, raycasting, collision-avoidance
---


# Question
Title: What is the order of postprocessing effects?
I am newbie in game development. I have read how many shader effects are implemented usually, and I have implemented msot of them by myself. However, now, I have the situation when I have to program my post process pipelines and so is the question: in what order should I do post process effects? Mostly I ask about: SSAO, blur, motion blur, chromatic abberation, fog, shadows... Actually, I am curios about all of them. So, the basic idea of my engine is:

1. Always draw everything to the texture.
2. Apply (so called by me - "prePostProcess") effects (lighting, for example).
3. Apply post process fx (blur and so on).

I understand that as I change the texture sequentially then the result will be different if I change the order in which programs are used to change the texture. Like: `chromatic aberration` and then `blur` is different between `blur` and then `chromatic aberration`.

I code my game with `opengl 4.4` at this moment, so I tagged it so.

# Answer
> 2 votes
First of all, you can't list all of the available post processing effects, because only some of them are pre-defined algorithms.

Second, some shaders aren't used in a combination with others. For example, an outline shader would look strange with an SSAO one.

Third, some of the things you mentioned aren't post-processing effects. Shadows are never created with post processing, blur is useless (if you don't use it in a depth of field for example).

Now to get to the actual order:

* SSAO relies on changes in the depth of the fragments, so applying it after a blur would be pointless (for example depth of field, motion blur, bloom and lens flare counts as blur).
* Chromatic aberration should happen after any kind of blur. A blur would just make the red and blue regions more smeared out.
* The same problem occurs with lens flare, an additional blur would just make it worse.
* Fog also operates in the depth buffer, so it should come before any blur. The order of SSAO and fog shouldn't matter.
* Every film-like effect (like grain or dithering) should come at the end.

And if you need a different opinion, this is the order Unity does it in:

As a last note, stuff like chromatic aberration, lens flare, motion blur, depth of field, bloom and many others are usually not very welcome in games, especially the latter three. They create a layer of abstraction between the player and his/her character. Keep in mind, that most of these effects were created for movies and not for games (for instance chromatic aberration simulates a defected camera).

# Answer
> 3 votes
@Bálint's above answer is mostly correct, but you need to be aware Unity postprocess stack you see above is only editor display order. Unity handles it in pretty different order (which is actually objective - like pushing motion blur before colorgrading). In Unity's Postprocess stack (v1) the order is like this:

1. Ambient occlusion
2. Screenspace reflection
3. Motion blur (input is HDR so bright reflections smear badly into solid bright streaks which doesn't look good)
4. TAA (yes - for me it's weird to stabilize motion blurred, mostly noisy pixels)
5. DoF
6. Chromatic abberration
7. Bloom
8. Vignette
9. Colorgrading (with tonemapping that brings values from HDR to LDR)

Next steps operates on LDR values:

10. User LUT
11. Grain
12. Dithering (if grain is inactive)

Eye adaptation is different step which outputs auto exposure multiplier used then in bloom & colorgrading (they use compute shader for it).

Better order would be moving motion blur after colorgrading.

---
Tags: opengl, graphic-effects
---


# Question
Title: Deterministic turn based navmesh pathfinding algorithm with agent avoidance
I am developing a game in Unity.

In this game, 2 teams will fight without any human interaction. The fight results must be always the same, if the same teams are the same. This way, I must reproduce the same fight in many devices, getting the same results in each device.

The map where the fight happens is a 3d environment, so, my soldiers can move in any direction. And the soldiers cannot walk in the same space of another soldier, so I need an agent avoidance algorithm.

I am having some trouble to find a solution to the problem above. To achieve the 'always the same results' I am treating this fight as Turn Based Strategy game, with little fixed time intervals between the turns.

To calculate the paths of the soldiers, I am using the Unity navmesh framework. And then I manually move my agents according to the 'NavMeshAgent' 'steeringTarget' property.

But this method doesn't cover the obstacle avoidance algorithm, and my agents overlap each other.

So, I am looking for a solution to my problems, It should be a manual obstacle avoidance algorithm, or a way for Unity's navmeshbto work in fixed time intervals, or a completely new approach to my path-finding problems.

# Answer
The way to solve it in two steps:

1. Make your 'avoidance algorithm' prevent NavMesh movement from navmesh.SetDestination() when near another object with navmesh.Stop()
2. With Random.seed you will be able to set destinations of your navmeshobjects exactly the same on every device so outcome will be exactly the same if people are using the same seed.
> 0 votes

---
Tags: unity, path-finding, navmesh, collision-avoidance
---


title: How can I control two events at once?

text:
# Question
Title: How can I control two events at once?
I am trying to make a doorway that is 2 tiles high. I have created an item called, `Door Key`. But I want both event tiles To hide or remove when I use the `Door Key`. The problem is I have to create two events to cover the doorway but can only get 1 event to change. So is there a way to change 2 events at once?

# Answer
> 2 votes
You can represent the door with a single event, because an event graphic isn't constrained to be 1 x 1 tile. Examples of larger event graphics can be found in the files !Crystal, !Other2, !$Gate1, !$Gate2, $BigMonster1, and $BigMonster2 in the menu displayed when you double click the image panel in the event editor.

For a door 1 tile wide and 2 tiles high, you would need to create an image 144 pixels wide and 384 pixels high - four rows of three 48 x 96 pixel animation frames - and the file name will need to start with at least a $ (to indicate that it contains only the four rows of three animation frames for single event graphic instead of eight rows of twelve animation frames divided into eight (four by two) blocks of four rows of three frames for eight event graphics) and probably a ! before that (to indicate that it shouldn't be displaced upward by a few pixels).

When you select a large image for an event, don't let yourself be misled by the map editor cropping the image to the dimensions of a single tile. The whole image will be visible when you play the game.

# Answer
> 2 votes
If there are other reasons why the door needs to be represented with two events, in addition to it needing a 1 x 2 tile graphic, the event code can set a movement route for both events and wait for neither of them to complete - the animations for both events will play simultaneously.

Assuming that the graphics for both parts of the door are typical door graphics where the down facing frames represent the closed door, the left facing frames represent the nearly closed door, the right facing frames represent the nearly open door, and the up facing frames represent the open door, the event code to open both sections of the door simultaneously could look like this:

```
Set Movement Route : Door Lower
                   : Turn Left
                   : Wait : 5 frames
                   : Turn Right
                   : Wait : 5 frames
                   : Turn Up
                   : Through ON
Set Movement Route : Door Upper
                   : Turn Left
                   : Wait : 5 frames
                   : Turn Right
                   : Wait : 5 frames
                   : Turn Up
                   : Through ON

```

When editing the Set Movement Route commands, remember to uncheck "Wait for Completion" - it's checked by default, and if you leave it checked, the first line of your Set Movement Route command will look like:

```
Set Movement Route : Door Lower (Wait)

```

instead of:

```
Set Movement Route: Door Lower

```

and the animation for the second event won't start until the animation for the first one has completed.

---
Tags: tiles, maps, rpg, events, rpg-maker-mv
---


# Question
Title: How to move while a timer is going in an event
I'm trying to make a switch activated gate and this is what I have setup so far "picture #1"

but what happens when the timer is going on, I cannot move. so what I'm trying to do is go through the gate "while the gate is open" but have a timer to reset the gate to close.

# Answer
> 1 votes
First, you need to check "Direction Fix" for the switch event. If you leave it unchecked, the event will turn to face the player when it's activated, and the facings for the graphic you've chosen for the switch have been used for something else: the states of the switch (down is switch left, left is switch middle, right is switch right, up is switch missing).

Assuming that 132 frames is the period for which the gate needs to be passable, and that the gate has a typical door graphic (down is closed, left is nearly closed, right is nearly open, up is open), your event code could set movement routes for both the gate and the switch, waiting for neither to complete (uncheck wait for completion when editing the movement routes).

The movement routes flip the switch and open the gate, wait for 132 frames, and finally close the gate and reset the switch:

```
Text : None, Window, Bottom
     : you flip the switch
If : door opened is OFF
  Set Movement Route : This Event
                     : Switch ON : 0001
                     : Direction Fix OFF
                     : Turn Left
                     : Wait : 5 frames
                     : Turn Right
                     : Wait : 142 frames
                     : Turn Left
                     : Wait : 5 frames
                     : Turn Down
                     : Direction Fix ON
                     : Switch OFF : 0001
  Set Movement Route : The Gate
                     : Wait : 5 frames
                     : Turn Left
                     : Wait : 5 frames
                     : Turn Right
                     : Wait : 5 frames
                     : Turn Up
                     : Through ON
                     : Wait : 132 frames
                     : Through OFF
                     : Turn Right
                     : Wait : 5 frames
                     : Turn Left
                     : Wait : 5 frames
                     : Turn Down
End

```

---
Tags: events, timestep, rpg-maker
---


# Question
Title: Spotlight turns off on and based on distance and angle, even in editor
I have cloned a spotlight 3 times. The original and one clone are near eachother and both work as expected. However, the other two are a few meters away, and behave oddly. I initially noticed in the player, but it also happens in the editor. If you get a few meters away they go out. I eventually noticed it also happens based on angle, as demonstrated below.

I am relatively new to Unity, but I've asked the other devs and they are stumped. **What could cause this?**

# Answer
I can think of 3 things that might help.

1. Edit-\>Project Settings-\>Quality Settings and then set Pixel Light Count to something higher. The default is 2 or 3.
2. Use Deferred rendering mode on your main camera. This is Done by selecting the camera and under the camera componet Rendering Path-\> Deferred
3. Set the Render MOde of the light from Auto to Important.
> 1 votes

---
Tags: unity
---


# Question
Title: How can I animate shadow in surface shader?
I wrote wind shader that works but as you can see it have shadow problem! when I animating vertices shadow is fixed!

```
Shader "Smkgames/Wind Shader" {
        Properties{
            _MainTex("Albedo and alpha (RGBA)", 2D) = "white" {}
            _BumpTex("BumpTex",2D) = "bump"{}
            _WindMap ("WindMap", 2D) = "white" {} // Add noies map like fbm noises
            _Cutoff ("Cutoff", Range(0,1)) = 0.5
            _Speed("Speed",float) = 1
            _Direction("Direction",Vector) = (0,0.2,0,0)
        }

        SubShader{
            Cull Off

            Tags{ "Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "TransparentCutout" "DisableBatching"="True" }
            LOD 200

            CGPROGRAM
            #pragma surface surf Standard alphatest:_Cutoff vertex:vert

            #pragma target 3.0

            sampler2D _MainTex,_WindMap,_BumpTex;
            fixed4 _Direction;
            fixed _Speed, _WindAmount;
            half _Glossiness, _Metallic;
            fixed4 _Color;

            void vert(inout appdata_full v) {
            float4 tex = tex2Dlod(_WindMap, float4(v.texcoord.xy + (_Time.x * _Speed), 0, 0));
            v.vertex.xyz += tex.y *  _Direction.xyz * _Speed;
            }

            struct Input {
                float2 uv_MainTex;
                float2 uv_BumpTex;
            };

            void surf(Input IN, inout SurfaceOutputStandard o) {
                fixed4 c = tex2D(_MainTex, IN.uv_MainTex);
                o.Albedo = c.rgb;
                o.Alpha = c.a;
                o.Normal = UnpackNormal(tex2D(_BumpTex,IN.uv_BumpTex));
            }
            ENDCG
        }
                FallBack "VertexLit"
    }

```

I couldn't fix it! so I tried to add shadow to my object from scratch by using vertex and fragment shader shadow caster and worked correctly but I want know Is there a way to fixing this problem in surface shader?

# Answer
> 1 votes
Just add "addshadow" to your `#pragma surface surf Standard alphatest:_Cutoff vertex:vert` line. Boom Unity does the rest. So it looks like this :

```
#pragma surface surf Standard alphatest:_Cutoff vertex:vert addshadow

```

---
Tags: unity, shadows, surface-shader
---


title: Location of drawables

text:
# Question
Title: Location of drawables
Is it possible to get the location of a drawable in Android Studio?

Example: `drawable.getLocationonScreen();`

I want to use it for collision detection.

# Answer
If its for a player sprite you can create an object for the drawable (such as a player class) and create a Rect based on the drawable dimensions, this can be used to check for collisions using the Intersecting method. Is this what you are looking for? I can provide some example code if needed.

**Edit:** Examples and explanation.

For this method I would recommend creating separate classes for the objects you're checking. In this example I will use a player and enemy. In both the player and enemy class you will define a bitmap for the sprite and then create a Rect based on the sprite: `rect = new Rect(x, y, x+sprite.getWidth(), y+sprite.getHeight());`. Once you have done this for both the player and sprite you will want to create a thread in your logic class and use it to check the following statement:

```
if (Rect.intersects(player.getRect(), enemy.getRect())){
    //Collision between player and enemy.
}

```

Detecting a collision between two objects is as simple as this.It will be more complicated when you want to detect collisions between multiple different items (which is what I assume this will lead to). In order to do this I recomend that you create ArrayLists and Iterators for your objects and run for loops in your threads to check for collisions. You will also need to ensure that you're accessing the same instances of the objects - just things to keep in mind moving forward! I hope this helps and wish you all the best.
> 1 votes

---
Tags: android
---


# Question
Title: How does OpenGL know which buffer to draw?
I have been trying out some OpenGL things and was wondering something:

How does OpenGL know which buffer to draw when `glDrawElements` is called (since there are three)?

Here's a code snippet (from a tutorial):

```
    // Use our shader
    glUseProgram(programID);

    glm::vec3 lightPos = glm::vec3(4,4,4);
    glUniform3f(LightID, lightPos.x, lightPos.y, lightPos.z);
    glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]); // This one doesn't change between objects, so this can be done once for all objects that use "programID"

    glm::mat4 ModelMatrix1 = glm::mat4(1.0);
    glm::mat4 MVP1 = ProjectionMatrix * ViewMatrix * ModelMatrix1;

    // Send our transformation to the currently bound shader,
    // in the "MVP" uniform
    glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP1[0][0]);
    glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &ModelMatrix1[0][0]);

    // Bind our texture in Texture Unit 0
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, Texture);
    // Set our "myTextureSampler" sampler to use Texture Unit 0
    glUniform1i(TextureID, 0);

    // 1rst attribute buffer : vertices
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glVertexAttribPointer(
        0,                  // attribute
        3,                  // size
        GL_FLOAT,           // type
        GL_FALSE,           // normalized?
        0,                  // stride
        (void*)0            // array buffer offset
    );

    // 2nd attribute buffer : UVs
    glEnableVertexAttribArray(1);
    glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
    glVertexAttribPointer(
        1,                                // attribute
        2,                                // size
        GL_FLOAT,                         // type
        GL_FALSE,                         // normalized?
        0,                                // stride
        (void*)0                          // array buffer offset
    );

    // 3rd attribute buffer : normals
    glEnableVertexAttribArray(2);
    glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
    glVertexAttribPointer(
        2,                                // attribute
        3,                                // size
        GL_FLOAT,                         // type
        GL_FALSE,                         // normalized?
        0,                                // stride
        (void*)0                          // array buffer offset
    );

    // Index buffer
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);

    // Draw the triangles !
    glDrawElements(
        GL_TRIANGLES,      // mode
        indices.size(),    // count
        GL_UNSIGNED_SHORT,   // type
        (void*)0           // element array buffer offset
    );

```

I have absolutely no idea how it would possibly know that the first buffer is the one that contains the vertices, and the others non-drawable information like UVs.

Can someone help me with this?

Thanks

# Answer
> How does opengl know which buffer to draw when glDrawElements is called(since there are 3)?

It uses all three; it uses all the buffers you enabled, bound and referenced. They're all "drawable information."

> i have absolutely no idea how it would possibly know that the first buffer is the one that contains the vertexes, and the others non drawable information like UV's.

It doesn't. What OpenGL knows (because you tell it, via `glVertexAttribPointer'`s first argument) is that the first buffer is assigned to attribute 0, and the second to attribute 1, and so on.

You also need to ensure these attributes match up with how you use the corresponding variables in your shader (the `in`-qualified variables). Generally you do this via `glBindAttribLocation` in your C++ code or by using `layout(location = X)` in the shader code. If you do neither of those, OpenGL automatically assigns them, which is somewhat brittle.
> 3 votes

# Answer
When `glVertexAttribPointer` is called opengl looks at the buffer bound to `GL_ARRAY_BUFFER` and associates that buffer to the attribute you are setting.

---

There is a second method to associate the buffer with the attributes using separate vertex format. (available from opengl 4.3+ or with the associated extension)

```
constexpr int vertexBindingPoint = 0;
constexpr int uvBindingPoint = 1;
constexpr int normalBindingPoint = 1;// free to choose, must be less than the GL_MAX_VERTEX_ATTRIB_BINDINGS limit

// 1rst attribute buffer : vertices
glEnableVertexAttribArray(0);
glVertexAttribFormat(
    0,                  // attribute
    3,                  // size
    GL_FLOAT,           // type
    GL_FALSE,           // normalized?
    0                   // attr offset
);
glVertexAttribBinding(0, vertexBindingPoint);

// 2nd attribute buffer : UVs
glEnableVertexAttribArray(1);
glVertexAttribFormat(
    1,                                // attribute
    2,                                // size
    GL_FLOAT,                         // type
    GL_FALSE,                         // normalized?
    0                                 // attr offset
);
glVertexAttribBinding(1, uvBindingPoint);

// 3rd attribute buffer : normals
glEnableVertexAttribArray(2);
glVertexAttribFormat(
    2,                                // attribute
    3,                                // size
    GL_FLOAT,                         // type
    GL_FALSE,                         // normalized?
    0                                 // attr offset
);
glVertexAttribBinding(2, normalBindingPoint);
//at this point the VAO is set up

//this can be done per mesh that uses the same vertex format while reusing the same VAO
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);
glBindVertexBuffer(vertexBindingPoint, vertexbuffer, 0, 3*sizeof(float));
glBindVertexBuffer(uvBindingPoint, uvbuffer, 0, 2*sizeof(float));
glBindVertexBuffer(normalBindingPoint, normalbuffer, 0, 3*sizeof(float));

// Draw the triangles !
glDrawElements(
    GL_TRIANGLES,      // mode
    indices.size(),    // count
    GL_UNSIGNED_SHORT,   // type
    (void*)0           // element array buffer offset
);

```

this has the advantage of letting the driver know that the format doesn't change and it can avoid patching the vertex shader each time you change the vao.
> 0 votes

---
Tags: opengl, vbo, vertex-buffer, vao
---


# Question
Title: Spawning enemies in four different positions with a fixed trajectory in android game
This is my first android game, I appreciate all the help. I want to define 4 spawning zones starting from out of the screen (left, right, up and down). Enemies coming from this areas have a fixed trajectory to the center, when this enemies come into the screen the player can move them to a specific corner, but if it lets go of it a new trajectory has to be calculated so it keeps moving to the center.

I am having trouble thinking on how to define this 4 areas, there is also 4 types enemies (they are the same, but they have a different color), should I place this 4 enemies on an arrayList ?. If I know how to define this 4 spawning areas which randomly decides where to spawn I then don't exactly know how to define the fixed trajectory to the center. Also, need to lower the speed to a more adecuate one. (Sorry if this seems like a lot am asking)

Current code looks like this (I am using AndEngine library):

```
public class gameEscene extends baseScene {

    // Regions for images
    private ITextureRegion BackgroundRegion;
    private ITextureRegion Corner;
    private ITextureRegion Center;
    private ITextureRegion Marco;
    // Sprites
    private Sprite spriteBackground;
    private Sprite spriteCorner;
    private Sprite spriteCenter;
    private Sprite spriteMarco;

    //  Enemies
    private ArrayList<Enemies> listEnemies;
    private ITextureRegion regionEnemy;
    //  Time to generate enemies
    private float timeEnemies = 0;              //  Counter
    private float   TIME_LIMIT  =   2.5f;       //  Every 2.5s it creates

    @Override
    public void loadResources() {
        BackgroundRegion = loadImage("black.jpg");
       Corner = loadImage("Corner_T.png");
        Center = loadImage("Center.png");
        Marco = loadImage("m.png");
        regionEnemy = loadimage("ship.png");
    }

    private void createEnemies() {
        for (int x = 700; x <= 1200; x += 100) {
            for (int y = 100; y <= 700; y += 100) {
                Sprite ship = loadSprite(x, y, regionEnemy);
                attachChild(ship);
                Enemies enemy = new Enemies(ship);
                listEnemies.add(enemy);
            }
        }

    }

    @Override
    public void createScene() {
        listEnemies = new ArrayList<>();
        spriteBackground = loadSprite(GameControl.CAMARA_WIDTH/2, GameControl.CAMARA_HEIGHT/2, BackgroundRegion);
        spriteCorner = loadSprite(GameControl.CAMARA_WIDTH/2, GameControl.CAMARA_HEIGHT/2, Corner);
        spriteCenter = loadSprite(GameControl.CAMARA_WIDTH/2, GameControl.CAMARA_HEIGHT/2, Center);
        spriteMarco = loadSprite(GameControl.CAMARA_WIDTH/2, GameControl.CAMARA_HEIGHT/2, Marco);
        attachChild(spriteBackground);
        attachChild(spriteCorner);
        attachChild(spriteCenter);
        attachChild(spriteMarco);
        createEnemies();
    }

    @Override
    public void onBackKeyPressed() {
        // Regresar al menú principal
        admScenes.createMenuScenes();
        admScenes.setScene(SceneType.MENU_SCENE);
        admScene.liberateGameScene();
    }

    @Override
    public sceneType getSceneType() {
        return sceneType.GAME_SCENE;
    }

    @Override
    public void liberateScene() {
        this.detachSelf();
        this.dispose();
    }

    @Override
    public void liberateResources() {
       BackgroundRegion.getTexture().unload();
        Corner.getTexture().unload();
        Center.getTexture().unload();
        Marco.getTexture().unload();
        regionEnemy.getTexture().unload();
        BackgroundRegion = null;
        Corner = null;
        Center = null;
        Marco = null;
        regionEnemy = null;
    }

    @Override
    protected void onManagedUpdate(float pSecondsElapsed)   {

        super.onManagedUpdate(pSecondsElapsed);
        timeEnemies +=  pSecondsElapsed;        //  Acumulates time
        if  (timeEnemies>TIME_LIMIT)    {   //  Time has completed
            tiemeEnemies    =   0;
            Sprite spriteEnemy  =   loadSprite(GameControl.CAMARA_WIDTH+regionEnemy.getWidth(),
                    (float)(Math.random()*GameControl.CAMARA_HEIGHT-regionEnemy.getHeight())    +
                            regionEnemy.getHeight(),regionEnemy);

            Enemies newEnemy = new Enemies(spriteEnemies);
            //newEnemies.mover(0,10);
            listEnemies.add(newEnemy);  //  Adds it to the scene
            attachChild(newEnemy.getSpriteEnemy()); //  Adds it to the list
        }

        //  Updates every enemy and sees if any has gotten out of the screen
        for (int    i=listEnemies.size()-1; i>=0;   i--)    {
            Enemies enemy   =   listEnemies.get(i);
            enemy.mover(-10, 0);
            if  (enemy.getSpriteEnemy().getX()<-enemy.getSpriteEnemy().getWidth())  {
                detachChild(enemy.getSpriteEnemy());        //  Deletes it from the scene
                listEnemies.remove(enemy);                                                                  //  eliminates it from the list
            }
            //  Checks the collision of enemy with another sprite

            if  (spriteCenter.collidesWith(enemy.getSpriteEnemy())) {
                detachChild(enemy.getSpriteEnemy());
                //enemies.remove(enemy);

            }
        }
    }

}

```

`Enemies` class looks like this:

```
public class Enemies {

    private Sprite sprite;

    public Enemies(Sprite sprite) {
        this.sprite = sprite;
    }

    public Sprite getSpriteEnemy() {
        return sprite;
    }

    public void setSprite(Sprite sprite) {
        this.sprite = sprite;
    }

    public void mover(int dx, int dy) {
        sprite.setPosition( sprite.getX()+dx, sprite.getY()+dy );
    }

}

```

Thanks in advance for the help.

Edit: Screenshot of idea

# Answer
It looks to me like you are not saving the enemies locations in their class, try using a `random` to generate Their location (from presets ranges) and then using ArrayLists and Itteraters together to spawn and ammend their positions?
> 0 votes

---
Tags: java, android, andengine, android-studio
---


# Question
Title: Is programming skill required for game development?
I do not know how to program. Can I contribute in any way to game development?

# Answer
Yes, you can.

Developing games requires, generally, a variety of skills. Programming is one of those skills, but it's not the *only* skill involved. Games generally require art and sound, gameplay mechanics design. They often require writing. Voice acting, marketing, QA testing, and so on.

If you can offer any of those skills, you can potentially find yourself in a position where you can contribute to the development of a game.
> 9 votes

# Answer
Even if you don't know how to program, you can still contribute to game development in a variety of ways by being one of the following:

-- Artist - Nearly every image you see in a game was drawn by an artist. If there weren't artists, then game graphics would be just as good as doodles. However, special effects (flashes, explosions, etc.) and lighting require programming to make (techniclaly, you can draw anything frame by frame, but special effects are the ideal and more performant way of drawing special effects). Also, the technical details of how to use and animate the images are handled by the programmer. OpenGL and DirectX are used for the programmer-side of things.

-- Musician - A game needs music and sound effects, of course. Programmers can also participate in this by doing interesting things with the sound card (OpenSL, Direct Sound, something similar is for this)

-- Translator - Needed for when you need a game in a country whose language you don't know.
> 0 votes

---
Tags: game-design
---


# Question
Title: How can I load and store JSON data in UE Blueprints?
For a college project that spans a few months, I'm working on a text adventure game in Unreal. I would like to state up-front that even if I wanted to use code, I can't. For some reason my college computers don't have Visual Studio or any other IDE UE supports.

I've made multiple text adventures before (in Flash and Unity) using custom frameworks that get and parse JSON data for the game.

I have no idea how I can accomplish a similar task (loading and parsing JSON data) using UE4's Blueprints. Can anyone help me come up with some sort of way I could go about doing this?

# Answer
> 4 votes
If you don't need to keep the files in .json, you can simply create a "Data Table", Unreal's desireble method for storing static data. Note that "static" is the key word here, since a data table is not a data base, and the entrys cannot be update during gameplay, only in engine. Right clicking the data table at the content explorer will give you an option to export it to JSON or CSV, and then you can edit it in your prefered IDE. After editing, you can import it back, to update your data table.

If you do need to use .json files (or store data as blueprint variables), you need to get or create a JSON parser, probably in C++, I'm not quite sure if you can do it with blueprints or not. Since it's a bit more complex, you have to study it, and explaning here is not viable.

This may help you as "search words":

* PublicDependencyModuleNames.AddRange(new string\[\] { "Json", "JsonUtilities" })
* FJsonObject
* Unreal Engine json parser

---
Tags: unreal-4
---


# Question
Title: Best way to create icon for UI , based on 3d model player can use in game
I'm trying to figure the best way to create icon (for UI) from my 3d model (object) that player can use in the game. Maybe this is a silly question, but: how do you create icon ? Do you create a new scene, place object and use a "shift-print" to take screenshots ?

Others way ?

Thanks

# Answer
> 2 votes
This should probably be a comment, but I want to post a screen shot. I have used the model preview screen to do screen grab in the past. You can move the model around in all 3 axis with your mouse.

---
Tags: unity, gui
---


# Question
Title: How do I find out where a script is attached to in Unity?
*I'm using Unity 2017.03.0f3 and I have a scripts folder with scripts (C#).*

Suppose I forget, or am working on someone else's project:

How do I know exactly which scripts are attached to what GameObjects or PreFabs, without clicking and going through all the Hierarchy objects please, and by first clicking on a script in the Project view?

I hope that's specific enough.

# Answer
> 1 votes
The hierarchy search allows you to filter by component. You'll need to type the entire name of the component or script. It will gray out the other objects and show only the objects with that script attached in the hierarchy. More details here: http://blog.theknightsofunity.com/can-search-scene-objects-components-type/

---
Tags: unity
---


# Question
Title: Unity, Player isnt following along the waypoints
I have a player with a Rigidbody, I want it to follow along the Waypoints, I have a script for it I tested it first on a Cube, everything worked fine, but on my character it just moves Towards the first waypoint then stays on the first waypoint instead of going ahead. Even if I comment out the LookAt Code section its not working. It could maybe cause the Y position of the waypoints that my player is stuttering, I changed it now. It is now moving along but stuttering much.

Here is a picture of the problem:

Here is my code:

---

```
public GameObject[] waypoints;

public float grindSpeed;
public float turnSpeed;

public int currentWaypoint;

private Animator anim;
private Rigidbody rb;

public bool isGrinding = false;

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

void Update()
{
    MoveAlongWaypoints();

    if(isGrinding)
        anim.SetBool ("isOnGrinding", true);
    else if(!isGrinding)
        anim.SetBool("isOnGrinding", false);
}

void MoveAlongWaypoints()
{
    if(isGrinding)
    {
        //TRANSLATE
        transform.position = Vector3.MoveTowards(transform.position, waypoints[currentWaypoint].transform.position, grindSpeed * Time.deltaTime);
        //ROTATE
        var rotation = Quaternion.LookRotation(waypoints[currentWaypoint].transform.position - transform.position);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, turnSpeed * Time.deltaTime);

        if(transform.position == waypoints[currentWaypoint].transform.position)
        {
            currentWaypoint++;
        }
    }
}

void OnTriggerEnter(Collider other)
{
    if(other.gameObject.tag == "GrindWayPoint")
    {
        Debug.Log ("Waypoint!!");
        isGrinding = true;
    }
}

```

# Answer
Position is made up of floats. Most likely the 2 values in this check never equal each other because of roundoff errors:

`// These will probably never equal each other
if(transform.position == waypoints[currentWaypoint].transform.position)`

When comparing floats you need to set some tolerance range to do the comparison and call it "good enough". e.g.

`if((Math.Abs(transform.position.x - waypoints[currentWaypoint].transform.position.x) < 0.01)
&& (Math.Abs(transform.position.y - waypoints[currentWaypoint].transform.position.y) < 0.01)
&& (Math.Abs(transform.position.z - waypoints[currentWaypoint].transform.position.z) < 0.01))
{
 //close enough...assume they are equal...so do some stuff
 currentWaypoint++;
}`
> 0 votes

---
Tags: unity, c#, rotation, movement, waypoints
---