# Question
Title: How can I fade player character when he goes inside or outside of the area?
I want to fade the player when he goes out of the area.

For example, suppose a person enters a building. When a person is outside of the building, he shouldn't be seen, but when he enters he gradually becomes visible (using fading effect).

**when elephant is inside green area his alpha should be 1**

**when elephant is outside of green area his alpha should be 0**

# Answer
> 36 votes
You can use world space to fade your character.

> The object space (or object coordinate system) is specific to each game object; however, all game objects are transformed into one common coordinate system — the world space.
>
> If a game object is put directly into the world space, the object-to-world transformation is specified by the Transform component of the game object.
>
> https://en.wikibooks.org/wiki/Cg\_Programming/Unity/Shading\_in\_World\_Space

# Fading by world space

```
Shader "Smkgames/worldSpaceFade" {
      Properties{
         _Size("Size",Vector) = (2,2,0,0)
      }
   SubShader {
      Pass {
         CGPROGRAM

         #pragma vertex vert
         #pragma fragment frag

         struct vertexInput {
            float4 vertex : POSITION;
         };
         struct vertexOutput {
            float4 pos : SV_POSITION;
            float4 position_in_world_space : TEXCOORD0;
         };

         vertexOutput vert(vertexInput input)
         {
            vertexOutput output;

            output.pos =  UnityObjectToClipPos(input.vertex);
            output.position_in_world_space =
               mul(unity_ObjectToWorld, input.vertex);

            return output;
         }
         float2 _Size;

         float4 frag(vertexOutput input) : COLOR
         {
             float3 world = input.position_in_world_space;

          float4 equation = pow(world.x/_Size.x,8) + pow(world.z/_Size.y,8);
          return smoothstep(1,0,equation);
         }

         ENDCG
      }
   }
}

```

# Surface Shader

After understanding world space we can use it in our surface shader:

```
Shader "Smkgames/worldSpaceFade" {
    Properties {
         _Size("Size",Vector) = (2,2,0,0)
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0
    }
    SubShader {
 Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
     Pass {
        ZWrite On
        ColorMask 0
    }
        LOD 200

        CGPROGRAM
        #pragma surface surf Standard fullforwardshadows alpha:fade

        #pragma target 3.0

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
            float3 worldPos: TEXCOORD2;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;
        float2 _Size;

        void vert (inout appdata_full v, out Input o){
            UNITY_INITIALIZE_OUTPUT(Input,o);
            o.worldPos = mul(unity_ObjectToWorld, v.vertex);
        }

        UNITY_INSTANCING_BUFFER_START(Props)
        UNITY_INSTANCING_BUFFER_END(Props)

        void surf (Input IN, inout SurfaceOutputStandard o) {
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
            float4 equation = pow(IN.worldPos.x/_Size.x,8) + pow(IN.worldPos.z/_Size.y,8);
            o.Albedo = c.rgb;
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = smoothstep(1,0,equation);
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

---
Tags: unity, shaders
---


# Question
Title: vertex manipulation in instanced shader hlsl SHARPDX 4.2
I am using the same vertex shader and pixel shader for my instances. I am sending ONE FLAT array that contains all the instanced chunk bytes that make the cube of the Minecraft terrain. My goal is to make ONE DRAW CALL... Nothing is working. I am able to use an input element that has the specific index of the vertex logged in memory so all of the instances vertexes share the same index. It should be super easy after that to fetch the byte 0 or 1 inside of the flat chunk array that contains all of the data.

It should be working. The indexes of the vertices are perfect. The indexes of the instanced chunks are perfect...

It feels as if something is wrong with the array as the chunks bytes are rendered randomly on my computer display. I padded all of my structs to send to the shader and padded correctly the InputElements...??? I tried sending an array of Matrices instead... Each Matrix M11 to M44 contains the index of the bytes and I send that as an array to the shader and BAM... nothing is still working... Doing it on the cpu would be completely fine as i've done it a thousand times already.

```
cbuffer MatrixBuffer :register(b0)
{
    float4x4 world;
    float4x4 view;
    float4x4 proj;
};

cbuffer inData:register(b1)
{
    int chunkMap[4096];
}

struct VertexInputType
{
    float4 position : POSITION;
    float4 indexPos : POSITION1;
    float4 instancePosition1 : INSTANCEPOSITION1;
};

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

float planeSize = 1;

static int mapWidth = 4;
static int mapHeight = 4;
static int mapDepth = 4;

static int tinyChunkWidth = 4;
static int tinyChunkHeight = 4;
static int tinyChunkDepth = 4;

bool IsTransparent(int xMain, int yMain, int zMain, int x, int y, int z)
{
    int indexMain = xMain + mapWidth * (yMain + mapHeight * zMain);
    int indexSec = x + tinyChunkWidth * (y + tinyChunkHeight * z);

    if ((x < 0) || (y < 0) || (z < 0) || (x >= tinyChunkWidth) || (y >= tinyChunkHeight) || (z >= tinyChunkDepth)) return true;
    {
        return chunkMap[(indexMain * 64) + indexSec] == 0;
    }
}
PixelInputType TextureVertexShader(VertexInputType input)
{
    PixelInputType output;

    input.position.w = 1.0f;

    int xMain = 0;
    int yMain = 0;
    int zMain = 0;

xMain = round(fmod((input.instancePosition1.x*10), mapWidth*tinyChunkWidth));
yMain = round(fmod((input.instancePosition1.y*10), mapHeight*tinyChunkHeight));
zMain = round(fmod((input.instancePosition1.z*10), mapDepth*tinyChunkDepth));

xMain = round(xMain / mapWidth);
yMain = round(yMain / mapHeight);
zMain = round(zMain / mapDepth);

    int x = input.indexPos.x;
    int y = input.indexPos.y;
    int z = input.indexPos.z;

    int indexMain = xMain + mapWidth * (yMain + mapHeight * zMain);

    int indexSec = x + tinyChunkWidth * (y + tinyChunkHeight * z);

    int currentByte = chunkMap[(indexMain * 64) + indexSec];

    input.position.x += input.instancePosition1.x;
    input.position.y += input.instancePosition1.y;
    input.position.z += input.instancePosition1.z;

    output.position = mul(input.position, world);
    output.position = mul(output.position, view);
    output.position = mul(output.position, proj);

    if (currentByte == 1)
    {
        output.color = float4(0,1,0,1);
        return output;
    }
    else
    {

        output.color = float4(0,0,1,1);
        return output;
    }
}

```

This is my current result. And it doesn't make sense and I don't understand why...

Seriously though. What is going on. I am sending a simple array to the GPU. Whatever padding I put shouldnt really matter since there is a single element in the struct for the buffer. Is it the GPU pipeline that is causing issues? is it because the GPU randomly puts data in the array which doesnt make any sense if it does? It is IMPOSSIBLE that the problem is my index of each vertex because I am setting those up BEFORE even starting rendering, they are setup as an input element Vector4 with x,y,z beeing the index position of the byte.

Or what I am trying is impossible? It shouldn't be unless it's related to some funky things the GPU is doing when instancing objects.

Below is what it should look like - pic of chunk data that are drawn individually - more draw calls as each instance has its own draw calls...But this tiny picture shows instanced chunks with 4096 total instances. Each object created has 64 instances and there is 64 objects. There is 4096 draw calls in here at which point you can argue those aren't really instanced at all but they are! Each instance has its own draw call in order to modify the vertexes and indexes of each instances. It's a very bad programing test and no one should ever attempt this as it's completely useless... I mean, I could probably have better results even without instancing the chunks.

Update: Below is what it looks now - I am almost there but again it's not working yet. I am able to send chunk data another way instead of a constant buffer and it seems to do "half" of the job. I'm gonna keep at it. 1 draw call and i could make the terrain as big as I want it. Same thing with the chunks, 64 objects and 64 instances per object. BUT there is only 64 draw calls here hehe. Of course, I benchmarking at the same time and the final version won't be tiny chunksBytes of 4*4*4 by instances 4*4*4 by objects 4*4*4, they will be bigger.

As you can see, I got some good results finally where the chunks are correctly aligned and it seems that they are in the right position, but the chunks are missing bytes... I am wondering if it is a padding/packing issue because again, I went over the c# script many times to check the index position and it seems fine. Thanks for the response DMGregory. By the way, I am NOW using floats as the inputElements. Each float contains 16 digits that are made up of bytes 1 and 0. Each bytes represent if the chunkBytes faces should be drawn or not. The inputElement is instanced and 4 floats of 16 digits gives me 64 .... wow wait a minute. is this where I am doing it wrong? brb on this

nevermind, i am doing it right as I am building the VertexBufferBinding with an array of floats dismantled into a single float containing 16 digits for each slot. In the shader, i am accessing the vertexBinding and it really is giving me the correct float bytes, i think, for each instance. So everything should be ok. but its not ok.

**EDIT 2019-03-31: I have changed my shader to this instead.**

```
cbuffer MatrixBuffer :register(b0)
{
    float4x4 world;
    float4x4 view;
    float4x4 proj;
};

struct VertexInputType
{
    float4 position : POSITION;
    float4 indexPos : POSITION1;
    float4 color : COLOR;
    float3 normal : NORMAL;
    float2 tex : TEXCOORD;
    float3 dummyPad : NORMAL1;
    float4 indexPosMain : INSTANCEPOSITION;
    float4 instancePosition1 : INSTANCEPOSITION1;
};

struct PixelInputType
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
    float3 normal : NORMAL;
    float2 tex : TEXCOORD;
};

float planeSize = 0.1f;

static int mapWidth = 4;
static int mapHeight = 4;
static int mapDepth = 4;

static int tinyChunkWidth = 4;
static int tinyChunkHeight = 4;
static int tinyChunkDepth = 4;

//[maxvertexcount(96)]
PixelInputType TextureVertexShader(VertexInputType input)
{
    PixelInputType output;
    input.position.w = 1.0f;

    //int mainX = input.indexPosMain.x;
    //int mainY = input.indexPosMain.y;
    //int mainZ = input.indexPosMain.z;

    int x = (input.indexPos.x);
    int y = (input.indexPos.y);
    int z = (input.indexPos.z);

    float currentMapData;
    float currentByte;

    int currentIndex = x + tinyChunkWidth * (y + tinyChunkHeight * z);

    if(currentIndex >= 0 && currentIndex <= 15)
    {
        currentMapData = input.indexPosMain.x;
        currentIndex =  currentIndex;
        currentIndex = 15-currentIndex;
    }
    else if(currentIndex >= 16 && currentIndex <= 31)
    {
        currentMapData = input.indexPosMain.y;
        currentIndex = 31 - currentIndex;
        currentIndex = 15-currentIndex;
    }
    else if(currentIndex >= 32 && currentIndex <= 47)
    {
        currentMapData = input.indexPosMain.z;
        currentIndex = 47 - currentIndex;
        currentIndex = 15-currentIndex;
    }
    else if(currentIndex >= 48 && currentIndex <= 63)
    {
        currentMapData = input.indexPosMain.w;
        currentIndex = 63 - currentIndex;
        currentIndex = 15 - currentIndex;
    }

    if(currentIndex == 0)
    {
        float before = currentMapData * 0.1f;
        float newIndex1 = round(before);
        float lastIndex = before - newIndex1;
        currentByte = round(lastIndex * 10);
    }
    else
    {
        int tempData = currentMapData;
        for(int i = 0;i < 15-currentIndex; i++)
        {
            tempData = currentMapData * 0.1f;
            currentMapData = round(tempData);
        }

        float before = currentMapData * 0.1f;
        float newIndex1 = round(before);
        float lastIndex = before - newIndex1;
        float otherByte = lastIndex * 10;
        currentByte = round(otherByte);

    }

    int current = currentByte;

    if(current == 1) //current >= 5 || wtf
    {
        input.position.x += input.instancePosition1.x;
        input.position.y += input.instancePosition1.y;
        input.position.z += input.instancePosition1.z;

        output.position = mul(input.position, world);
        output.position = mul(output.position, view);
        output.position = mul(output.position, proj);
    }
    else
    {
        input.position.x = input.instancePosition1.x;
        input.position.y = input.instancePosition1.y;
        input.position.z = input.instancePosition1.z;

        output.position = mul(input.position, world);
        output.position = mul(output.position, view);
        output.position = mul(output.position, proj);
    }

    output.color = input.color;
    output.tex = input.tex;

    output.normal = mul(input.normal, world);
    output.normal = normalize(output.normal);

    return output;
}

```

# Answer
The goal is achieved. It was to modify the vertex position inside of a Vertex Shader with using Vertex Binding Elements. The vertex binding is used both for storing the index of each byte (to which each vertex is assigned to) inside of each chunk instanced or not and also used to send the instance bytes in the form of integers.

In the end, the positions of each vertex is manipulated inside of the vertex shader but they are NOT removed from the scene.

Special thanks to Craig Perko for creating the Minecraft Terrain Tutorial series 1 & 2 on YouTube.

My 1st version is a very powerful instanced chunk placement system for the position of an area chunk that contains the instances of the tiny chunks and those bytes inside of that chunk also are coming in the shader. With the use of byte shift operator to lock the position inside of a float, i am able to get those necessary "1s" and "0s" that decides if yes or no to build the 6 faces of that tiny cubes that is the mesh of a chunk that is an instance of the area chunk that contains those chunk instances.

rounding only wasnt working. flooring only wasnt working.

it's all due to finding this here: https://stackoverflow.com/questions/46312893/how-do-you-use-bit-shift-operators-to-find-out-a-certain-digit-of-a-number-in-ba

My 1st Version is not a complicated example but it has absolutely no comments and some stupid variable names as i was tired after many attempts in that shader always rewritting new variable names or commenting the code out etc, to make my byte/float vertex binding system, instead i just add a "vowel" and then a consonant" or vice-versa, to move on forward but that was in september 2019. yes i name my variable names right this time around and i make sure to leave myself better hints. hopefully this will help anyone researching and trying to improve their instancing techniques even though there is nothing perfect inside of that program and it is a draft.

Shader:

```
      cbuffer MatrixBuffer :register(b0)
      {
        float4x4 world;
        float4x4 view;
        float4x4 proj;
      };

      /*cbuffer MatrixBuffer :register(b1)
      {
        int mapper[][]
      };*/

      struct VertexInputType
      {
          float4 position : POSITION0;
          float4 indexPos : POSITION1;
          float4 color : COLOR0;
          float3 normal : NORMAL0;
          float2 tex : TEXCOORD0;
          int one : PSIZE0;
          int two : PSIZE1;
          int three : PSIZE2;
          int four : PSIZE3;
          int oneTwo : PSIZE4;
          int twoTwo : PSIZE5;
          int threeTwo : PSIZE6;
          int fourTwo : PSIZE7;
          float4 instancePosition1 : POSITION2;
      };

      //row_major matrix instancePosition1 : WORLD;

      struct PixelInputType
      {
        float4 position : SV_POSITION;
        float4 color : COLOR0;
        float3 normal : NORMAL0;
        float2 tex : TEXCOORD0;
      };

      //float planeSize = 0.1f;

      static int mapWidth = 4;
      static int mapHeight = 4;
      static int mapDepth = 4;

      static int tinyChunkWidth = 4;
      static int tinyChunkHeight = 4;
      static int tinyChunkDepth = 4;

      //[maxvertexcount(96)]
      PixelInputType TextureVertexShader(VertexInputType                     input)
      {
        PixelInputType output;
          input.position.w = 1.0f;

        int x = input.indexPos.x;
        int y = input.indexPos.y;
        int z = input.indexPos.z;

        int currentMapData;
        int currentByte;

        int currentIndex = x + (tinyChunkWidth * (y+(tinyChunkHeight*z)));
        int someOtherIndex = currentIndex;

        int theNumber = tinyChunkWidth;
        int remainder = 0;
        int totalTimes = 0;

        for (int i = 0;i <= currentIndex; i++)
        {
            if (remainder == theNumber)
            {
                remainder = 0;
                totalTimes++;
            }
            if (totalTimes * theNumber >= currentIndex)//>=?? why not only >
            {
                break;
            }
            remainder++;
        }

        int arrayIndex = int(floor(totalTimes *0.5));

        switch(arrayIndex)
        {
            case 0:
                currentMapData = input.one;
                break;
                    case 1:
                currentMapData = input.oneTwo;
                break;
            case 2:
                currentMapData = input.two;
                break;
            case 3:
                currentMapData = input.twoTwo;
                break;
            case 4:
                currentMapData = input.three;
                break;
              case 5:
                currentMapData = input.threeTwo;
                break;
              case 6:
                currentMapData = input.four;
                break;
              case 7:
                currentMapData = input.fourTwo;
                break;
          }

          //0-4-1-5-2-6-3-7
          //8-12-9-13-10-14-11-15
          //16-20-17-21-18-22-19-23
          //24-28-25-29-26-30-27-31
          //32-36-33-37-34-38-35-39
          //40-44-41-45-42-46-43-47
          //48-52-49-53-50-54-51-55
          //56-60-57-61-58-62-59-63

          int baser = totalTimes;

          int someAdder = totalTimes % 2;

          someOtherIndex=7-(((someOtherIndex-(tinyChunkWidth*baser))*2)+someAdder);

          int testera = 0;
          int substract = 0;
          int before0 = 0;

          if (someOtherIndex == 0)
          {
              testera = currentMapData >> 1 << 1;
              currentByte = currentMapData - testera;
          }
          else
          {
            float someData0 = currentMapData;

            for (int i = 0; i < someOtherIndex; i++)
            {
                someData0 = int(someData0 * 0.1f);
            }
              before0 = int(trunc(someData0));
            //https://stackoverflow.com/questions/46312893/how-do-you-use-bit-shift-operators-to-find-out-a-certain-digit-of-a-number-in-ba
              testera = before0 >> 1 << 1;
              currentByte = before0 - testera;
          }

          //currentByte = 1;

          if(currentByte == 1)
          {
            input.position.x += input.instancePosition1.x;
            input.position.y += input.instancePosition1.y;
            input.position.z += input.instancePosition1.z;

            output.position = mul(input.position, world);
            output.position = mul(output.position, view);
            output.position = mul(output.position, proj);
            output.color = input.color;
          }
          else
          {
            input.position.x = input.instancePosition1.x;
            input.position.y = input.instancePosition1.y;
            input.position.z = input.instancePosition1.z;

            output.position = mul(input.position, world);
            output.position = mul(output.position, view);
            output.position = mul(output.position, proj);
            output.color = input.color * float4(0.5f,0.5f,0.5f,1);
          }

          output.tex = input.tex;

          output.normal = mul(input.normal, world);
          output.normal = normalize(output.normal);

          return output;
      }

      /*technique Test
      {
          pass pass0 //pass1
          {
              VertexShader = compile vs_5_0 TextureVertexShader();
              //PixelShader  = compile ps_5_0 TexturePixelShader();
          }
      }*/

```
> 1 votes

---
Tags: c#, sharpdx
---


# Question
Title: Unity Moving and rotating part of a model
I have downloaded a high quality head model which includes the shoulder, and I have want to move and rotate the head model, but its shoulder fixed, as if it is looking at the certain points that I have as list. I am not sure what is the best way to implement this -- should I split the model into two parts with blender, and just move the head model? Or should write a script that only moves the part of the model. If I write a script, how do I locate specific vertices in the model(in my case, the tip of the nose would be best) to follow the coordinates in the list, and how do I specify other vertices in meshes that needs to be follow the change so that the movement would look natural?

Thank you!

# Answer
The usual way to do this is through the Unity animation system. When a 3d artist creates a model of a character in a 3d modeling program, they usually also add a "rig" to it (a collection of bones connected to vertices which can be moved in order to move parts of the whole 3d model) and also define a couple animations.

Another important component of a good character rig are Inverse Kinematic ("IK") Targets. They allow to animate parts of a model in a way which takes an arbitrary point in 3d space as input. This is often used to implement abilities like grabbing things or (relevant in your use-case) looking at things.

A 3d engine like Unity can then use that rig to modify the 3d model in real-time by playing animations, moving bones or moving IK target points.

If the 3d model you got doesn't have a rig which allows to move the head separately from the shoulders, then you might have to build your own rig. Consult the documentation of your preferred 3d modeling program for details. If you want to use Blender and have any Blender-specific questions about character rigging and animation, then you might want to check out our sister site Blender Stack Exchange.
> 0 votes

---
Tags: unity
---


# Question
Title: instantiate with arrays of objects and transforms
Instead of using a list, I want to use a two-dimensional array of objects and a two-dimensional array of transforms.

But instantiations do not work with this code in C sharp:

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

public class try_array_instantiate : MonoBehaviour {

  //entity declaration
  public GameObject[,] cube;
  public GameObject cube_initial;
  public GameObject[,] cubeCree;
  public Transform[,] origine;
  public Transform origine_initial;
  public float moveSpeed=5f;

  int i;

 void Start() {
    // take the transformation composantres of the initial cube
    origine_initial=cube_initial.GetComponent<Transform>();
  }

  void Update() {

    if (Input.GetKeyDown (KeyCode.Q)) {
      //create the first shot duplication from the single initial cube
      cube[1,1]=Instantiate (cubeCree[1,1], origine_initial.position, origine_initial.rotation) as GameObject;
      cube[1,1].transform.Translate(Time.deltaTime*moveSpeed,0,Time.deltaTime*moveSpeed,Space.Self);

      cube[1,2]=Instantiate (cubeCree[1,1], origine_initial.position, origine_initial.rotation) as GameObject;
      cube[1,2].transform.Translate(Time.deltaTime*moveSpeed,0,-Time.deltaTime*moveSpeed,Space.Self);
      //destruction of the initial cube
      Destroy(cube_initial);
    }
  }
}

```

What should I modify in this code so that the instantations are created?

In fact, I can't adapt your correction at this code I would like to do initially which makes a duplicate shot with each press of the Q key.

Here's this code:

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

public class tir_duplique_pas_encore_bon : MonoBehaviour {

    // If what we want to work with are Transforms, then store that reference directly.
    public Transform[,] cubeInitial;
    public Transform[,] cubePrefab;
    public Transform cubePrefab0;
    public Transform cubeInitial0;

    public float moveSpeed = 5f;
    int i;
    int p=0;

    // Private variables for the content we populate at runtime.
    Transform[,] cubes;
    Vector3 originPosition;
    Quaternion originRotation;

    void Start() {
        // Initialize the array before we try to use it.
        // Note that arrays are 0-based, so if we later want to access [1, 2],
        // that means we need at least a 2x3 array (ie. {0, 1} x {0, 1, 2})
        cubes = new Transform[100000,1];
        cubeInitial = new Transform[100000,1];
        cubePrefab = new Transform[100000,1];
        cubePrefab0 = cubePrefab [0, 0];
        cubeInitial0 = cubeInitial [0, 0];

    }

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

            // Capture the transformation of our reference object before we delete it.
            if(cubeInitial[0,0] != null) {
                originPosition = cubeInitial[0,0].position;
                originRotation = cubeInitial[0,0].rotation;
                //Destroy(cubeInitial[0,0]);
                //cubeInitial[0,0] = null;
            }

            // Instantiate our cube instances using the prefab.
            cubes[0, 0] = Instantiate<Transform>(cubePrefab[0,0], originPosition, originRotation);
            cubes[0, 1] = Instantiate<Transform>(cubePrefab[0,1], originPosition, originRotation);

        // If you want these objects to move over time, then don't
        // put the Translate() call inside a block that runs only
        // when the player presses "Q". Move them every frame.

        float step = Time.deltaTime * moveSpeed;

        if(cubes[0,0] != null)
            cubes[0,0].Translate(step, 0, step, Space.Self);

        if(cubes[0,1] != null)
            cubes[0,1].Translate(step, 0, -step, Space.Self);

    }
        if (Input.GetKeyDown (KeyCode.Q)) {

            for (i=(int)Mathf.Pow (2, p+1)-1; i <=2*((int)Mathf.Pow (2, p+1)-1) ;i++ )
            {if(cubeInitial[i-1,0] != null) {
                    originPosition = cubeInitial[i-1,0].position;
                    originRotation = cubeInitial[i-1,0].rotation;
                    Destroy(cubeInitial[i-1,0]);
                    cubeInitial[i-1,0] = null;
                }

            if(cubeInitial[i-1,1] != null) {
                    originPosition = cubeInitial[i-1,1].position;
                    originRotation = cubeInitial[i-1,1].rotation;
                    Destroy(cubeInitial[i-1,1]);
                    cubeInitial[i-1,1] = null;
                }

                cubes[i, 0] = Instantiate<Transform>(cubePrefab[i,0], originPosition, originRotation);
                cubes[i, 1] = Instantiate<Transform>(cubePrefab[i,1], originPosition, originRotation);

                float step = Time.deltaTime * moveSpeed;

                if(cubes[i,0] != null)
                        cubes[0,0].Translate(step, 0, step, Space.Self);

                if(cubes[i,1] != null)
                        cubes[i,1].Translate(step, 0, -step, Space.Self);

}
                        p++;
}
}
}

```

I try to apply your answer to my update code and I have problem here:

Instead of declaring `transform cubePrefab` and `cubeInitial`, I declare:

```
public transform[,] cubeInitial;
public transform[,] cubePrefab;

```

To adapt the following of my new code updated which must uses arrays to classify shoot which are multiplying

So,no possible to slip in the inspector in the script the `firstcube(shoot)` like I did it with your first code thanks to:

```
public Transform cubeInitial;
public Transform cubePrefab;

```

After,i tried to to that:

```
public Transform[,] cubeInitial;
public Transform[,] cubePrefab;
public Transform cubePrefab0;
public Transform cubeInitial0;

```

and after:

```
cubes = new Transform[100000,1];
cubeInitial = new Transform[100000,1];
cubePrefab = new Transform[100000,1];
cubePrefab0 = cubePrefab [0, 0];
cubeInitial0 = cubeInitial [0, 0];

```

So, compile was good but shoot doesn't work on play unity

Then,to adapt your update,i write this last code:

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

public class tir_duplique_pas_encore_bon : MonoBehaviour {
    // If what we want to work with are Transforms, then store that reference directly.
    public Transform[,] cubeInitial;
    public Transform[,] cubePrefab;
    public Transform cubePrefab0;
    public Transform cubeInitial0;
    public float moveSpeed = 5f;
    int i;
    int p=1;
    // Private variables for the content we populate at runtime.
    Transform[,] cubes;
    Vector3 originPosition;
    Quaternion originRotation;

    void Start() {
        // Initialize the array before we try to use it.
        // Note that arrays are 0-based, so if we later want to access [1, 2],
        // that means we need at least a 2x3 array (ie. {0, 1} x {0, 1, 2})
        cubes = new Transform[100000,1];
        cubeInitial = new Transform[100000,1];
        cubePrefab = new Transform[100000,1];
        cubePrefab0 = cubePrefab [0, 0];
        cubeInitial0 = cubeInitial [0, 0];

    }

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

            // Capture the transformation of our reference object before we delete it.
            if(cubeInitial[0,0] != null) {
                originPosition = cubeInitial[0,0].position;
                originRotation = cubeInitial[0,0].rotation;
                Destroy(cubeInitial[0,0]);
                cubeInitial[0,0] = null;
            }

            // Instantiate our cube instances using the prefab.
            cubes[0, 0] = Instantiate<Transform>(cubePrefab[0,0], originPosition, originRotation);
            cubes[0, 1] = Instantiate<Transform>(cubePrefab[0,0], originPosition, originRotation);

            // If you want these objects to move over time, then don't
            // put the Translate() call inside a block that runs only
            // when the player presses "Q". Move them every frame.

            float step = Time.deltaTime * moveSpeed;

            if(cubes[0,0] != null)
                cubes[0,0].Translate(step, 0, step, Space.Self);

            if(cubes[0,1] != null)
                cubes[0,1].Translate(step, 0, -step, Space.Self);
        }
        if (Input.GetKeyDown (KeyCode.Q)) {
            for (i=(int)Mathf.Pow (2, p); i <= (int)Mathf.Pow (2, p + 1) - 1;i++ )
            {
                if(cubeInitial[i,0] != null) {
                    originPosition = cubeInitial[i,0].position;
                    originRotation = cubeInitial[i,0].rotation;
                    Destroy(cubeInitial[i,0]);
                    cubeInitial[i,0] = null;
                }

                if(cubeInitial[i,1] != null) {
                    originPosition = cubeInitial[i,1].position;
                    originRotation = cubeInitial[i,1].rotation;
                    Destroy(cubeInitial[i,1]);
                    cubeInitial[i,1] = null;
                }

                cubes[i, 0] = Instantiate<Transform>(cubePrefab[i,0], originPosition, originRotation);
                cubes[i, 1] = Instantiate<Transform>(cubePrefab[i,1], originPosition, originRotation);

                float step = Time.deltaTime * moveSpeed;

                if(cubes[i,0] != null)
                    cubes[0,0].Translate(step, 0, step, Space.Self);

                if(cubes[i,1] != null)
                    cubes[i,1].Translate(step, 0, -step, Space.Self);
            }
            p++;
        }
    }
}

```

But it doesn't work on play Unity

Yes sorry the console of Unity indicate:

ArgumentException: The Object you want to instantiate is null. UnityEngine.Object.CheckNullArgument (System.Object arg, System.String message) (at C:/buildslave/unity/build/Runtime/Export/UnityEngineObject.cs:239) UnityEngine.Object.Instantiate (UnityEngine.Object original, Vector3 position, Quaternion rotation) (at C:/buildslave/unity/build/Runtime/Export/UnityEngineObject.cs:151) UnityEngine.Object.Instantiate\[Transform\] (UnityEngine.Transform original, Vector3 position, Quaternion rotation) (at C:/buildslave/unity/build/Runtime/Export/UnityEngineObject.cs:206) tir\_duplique\_pas\_encore\_bon.Update () (at Assets/tir\_duplique\_pas\_encore\_bon.cs:54)

code source contains at the beginning:

cubePrefab0 = cubePrefab \[0, 0\]; cubeInitial0 = cubeInitial \[0, 0\];

so 2 fields appear in the script of the inspector. Then,in thes 2 fields,I slid another same cube in the hierarchy that has no script Is it no sufficient?

# Answer
The main errors here are:

1. Failing to create your array with `cubeCree = new GameObject[2,3];` before trying to assign contents to it. Always ensure you've created the array with the appropriate dimensions before trying to use it, otherwise you'll get a null reference or out of bounds exception.
2. Destroying the `cube_initial` object when your code is going to try to read from it again the next time the "Q" key is pressed. Be sure to save the properties from it that you'll need, and check for `null` before trying to access the destroyed object.
3. Trying to use multidimensional arrays as public variables - the Unity Inspector won't let you initialize multidimensional arrays that way.

Corrected code might look something like this:

```
public class ArrayInstantiate : MonoBehaviour {

  // If what we want to work with are Transforms, then store that reference directly.
  public Transform cubeInitial;
  public Transform cubePrefab;

  public float moveSpeed = 5f;

  // Private variables for the content we populate at runtime.
  Transform[,] cubes;
  Vector3 originPosition;
  Quaternion originRotation;

  void Start() {
      // Initialize the array before we try to use it.
      // Note that arrays are 0-based, so if we later want to access [1, 2],
      // that means we need at least a 2x3 array (ie. {0, 1} x {0, 1, 2})
      cubes = new Transform[2,3];
  }

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

      // Capture the transformation of our reference object before we delete it.
      if(cubeInitial != null) {
        originPosition = cubeInitial.position;
        originRotation = cubeInitial.rotation;
        Destroy(cubeInitial);
        cubeInitial = null;
      }

      // Instantiate our cube instances using the prefab.
      cubes[1, 1] = Instantiate<Transform>(cubePrefab, originPosition, originRotation);
      cubes[1, 2] = Instantiate<Transform>(cubePrefab, originPosition, originRotation);
    }

    // If you want these objects to move over time, then don't
    // put the Translate() call inside a block that runs only
    // when the player presses "Q". Move them every frame.

    float step = Time.deltaTime * moveSpeed;

    if(cubes[1,1] != null)
        cubes[1,1].Translate(step, 0, step, Space.Self);

    if(cubes[1,2] != null)
        cubes[1,2].Translate(step, 0, -step, Space.Self);
  }
}

```

It's not clear to me why you've moving your cubes within the ArrayInstantiate class, nor why you're using only indices \[1, 1\] and \[1, 2\] out of your array, but I've left these as-is in this version of the code. I'd recommend sizing the array to contain only the indices you need, and putting the cube movement in a separate script on the cubes themselves, so you don't need to manage their ongoing behaviour from the script that spawns them.

---

Based on the edit, you seem to be very confused about how arrays in C# work. For example, you initialize your arrays like this in Start:

```
cubeInitial = new Transform[100000,1];
cubeInitial0 = cubeInitial [0, 0];

```

but then try to access it like this:

```
cubeInitial[i,1].position

```

This is wrong for a few reasons:

1. You told the compiler you wanted only one entry along the second dimension (`new Transform[100000, 1]`), so that means that while `cubeInitial[i,0]` is a valid index (for i \< 100000), `cubeInitial[i,1]` is not. You're trying to use two entries for each `i`, but you allocated only one.
2. You've created a new, empty array in Start, so every entry of `cubeInitial[,]` is `null` (an empty slot). It will not have a `position` or `rotation` until you assign a `Transform` instance to that index.
3. It looks like you tried to initialize `cubeInitial[0,0]` with this line: `cubeInitial0 = cubeInitial [0, 0];` but this assigns the value of `cubeInitial[0,0]` (which is `null`) *into* `cubeInitial0`, so now *both* variables hold the value of `null`, and this doesn't help you at all.

Maybe you meant to assign the value of `cubeInitial0` into `cubeInitial[0,0]` like so: `cubeInitial[0,0] = cubeInitial0;`, but that still leaves `null`s in all entries of the form `cubeInitial[i,1]`, provided you solve the array size issue mentioned in point 1.

Because of confusion like this, it's very difficult to understand how you expected this code to work, or what you want it to accomplish.

I'd recommend taking some time to brush up on your C# fundamentals: maybe take a break from your game development project and work through some beginner tutorials for the language.

The other thing you can do is to try phrasing your questions to ask about the feature you want to achieve, not the coding syntax you're using to try to achieve it. Since you don't yet understand the syntax, this is leading to garbled questions and X/Y Problems. Instead, walk us step by step through how this game feature should work, what happens when everything goes as planned. Include diagrams or animations, or examples from similar games, if they help you to communicate clearly.
> 3 votes

---
Tags: unity
---


# Question
Title: Perform intersection (horizontal and vertical) checking in raycasting
I want to check the horizontal and vertical intersections on my raycasting view, and I can't exactly understand what is ALPHA using this drawing

source : https://www.permadi.com/tutorial/raycast/rayc7.html

I wrote something that makes the walls straights and with less stairs on top and bottom, but i have some columns which go out of the view row, i can't figure out where i failed my operations (rounds)

this is the code of the vertical and the horizontal intersections :

```
static inline void      inter_hor(t_wolf3d *w, int i, double angle){
t_vec2f a; // first intersection point
t_vec2f o; // offset
double  tangent;

tangent = ttan(angle) + 0.001;
a.y = (angle <= 180) ? floor(w->cam->position.y / 32) *
32 - 1 : ceil(w->cam->position.y / 32) * 32 + 32;
o.y = (angle < 180) ? -32 : 32;
o.x = (angle < 90 || angle > 270) ? 32 / tangent : -32 / tangent;
a.x = (angle != 180.0 && angle < 359.97) ? w->cam->position.x + (w->cam->position.y - a.y) / tangent :
w->cam->position.x + (w->cam->position.y - a.y) / -tangent; //w->mini_h is the w->map->h  * 32 and so on for w->mini_w
a.x = (angle >= 179.97 && angle <= 180) ? w->cam->position.x + (w->cam->position.y - a.y) / -tangent : a.x;
if (ceil(a.x / 32) < 0 || ceil(a.x / 32) >= w->map->w)
    a.x = (ceil(a.x / 32) < 0) ? 0 : w->mini_w - 1;
while (w->map->board[(int)a.y / 32][(int)a.x / 32] == 0)
{
    a.x += ((angle >= 90 && angle < 180) || angle >= 270) ? -o.x : o.x;
    a.y += o.y;
if (ceil(a.x / 32) < 0 || ceil(a.x / 32) >= w->map->w)
    a.x = (ceil(a.x / 32) < 0) ? 0 : w->mini_w - 1;
    if (a.y < 0 || a.y > w->mini_h - 1)
        break;
}
w->cam->interh[i].x = a.x;
w->cam->interh[i].y = a.y;}
static inline void      inter_ver(t_wolf3d *w, int i, double angle){
t_vec2f a; // intersection point
t_vec2f o; // offset
double  tangent;

tangent = ttan(angle) + 0.001;
a.x = (angle >= 90 && angle < 270) ? ceil(w->cam->position.x / 32) *
32 - 1 : floor(w->cam->position.x / 32) * 32 + 32;
o.x = (angle > 90 && angle < 270) ? -32 : 32;
o.y = (angle > 0 &&  angle < 180) ? -32 * tangent : 32 * tangent;
a.y = (angle != 270 && angle != 90) ? w->cam->position.y + (w->cam->position.x - a.x) * tangent :
w->cam->position.y + (w->cam->position.x - a.x) * -tangent;
if (ceil(a.y / 32) < 0 || ceil(a.y / 32) >= w->map->h)
    a.y = (ceil(a.y / 32) < 0) ? 0 : w->mini_h - 1;
while (w->map->board[(int)ceil(a.y / 32)][(int)a.x / 32] == 0)
{
    a.y += ((angle > 90 && angle < 180) || angle > 270) ? -o.y : o.y;
    a.x += o.x;
    if (ceil(a.y / 32) < 0 || ceil(a.y / 32) >=  w->map->h)
        a.y = (ceil(a.y / 32) < 0) ? 0 : w->mini_h - 1;
    if (a.x < 0 || a.x > w->mini_w - 1)
        break;
}
w->cam->interv[i].x = a.x;
w->cam->interv[i].y = a.y;}

```

I could use the dir.y / dir.x computed before for my tangent, but i didn't cause i had some divisions by zero when my rays was facing at 180, 360, 0 degrees, angles are complexes and i dont understand completely the vectors method to do that way; these are some screeshots :

# Answer
> 1 votes
\\$\alpha\\$ is the angle between the X-axis (horizontal) and the ray you're casting.

\\$Tan(\alpha)\\$ is also called the slope, which is \\$opposite/adjacent\\$ so in the triangle on the right it's \\$Ya/Xa = Ya/64\\$, thus, if you know the slope and one intersection you can get the next intersection in the grid by adding \\$64\times Tan(\alpha)\\$ to they coordinate and \\$64\\$ to the x coordinate.

# Answer
> -1 votes
I actually got it by myself, it was a mistake inside the minimap raycasting! First of all, i decided to print my rays part by part (example : ray 0 to 200), i noticed that the rendering in my minimap was not exactly what i had on my screen by moving left or right (rotating); i figured out that the mistake was not the rendering itself but the fact that i used different widths of screen to do the minimap and the 3d rendering raycast

---
Tags: raycasting
---


# Question
Title: How to make an object towards the mouse on one Axis - Gamemaker Studio 2
I am trying to have my "obj\_playership" move towards the Cursor on a single Axis. Prefer it to be the Vertical Axis. I tried doing this is an "Execute Code Box" in a step event

"direction = mouse\_x" "speed = 1 " but the movement looks weird and does not do what I am trying to do.

To better refine my question I'm trying to have my "obj\_playership" move just up and down in relation to the mouse, so if I'm moving my mouse up or down the obj\_playership" will follow towards the mouse either up or down.

# Answer
> 2 votes
Just check where is the mouse based on the object's position:

```
if (mouse_y - y) > 0 {
    y+=1;
} else if(mouse_y - y) < 0 {
    y-=1;
}

```

This same code could be written in different ways but are a little bit complex to understand XD

```
y += sign(mouse_y - y);

```

The "direction" must be an angle, that's why it looks weird like this.

---
Tags: game-design, movement, game-maker, mouse
---


title: How to set Godot's events as handled

text:
# Question
Title: How to set Godot's events as handled
My root node adds a scene - GameScene - in it's \_ready function:

```
const game_scene = preload('res://scenes/game_states/game_state.tscn')
func _ready():
    var game_scene_instance = game_scene.instance()
    add_child(game_scene_instance)

```

And my GameScene, it adds my Level1 scene in it's \_ready() function:

```
const level_1 = preload("res://scenes/stages/stage01.tscn")
func _ready():
    var level_instance = level_1.instance()
    add_child(level_instance)

```

In my stage01 scene, I have a Player scene that looks at input thru \_unhandled\_input() function, and does something based on that input.

```
func _unhandled_input(event):
    if event.is_action_pressed('ui_down'):
        print("Adding 15 points to the player's score")

```

But, I do not want my Player scene to receive any input. So, in my GameScene, I implemented it's \_unhandled\_input() function to mark every input it receives as handled.

```
func _unhandled_input(event):
    get_tree().set_input_as_handled()

```

But, if I press the 'ui\_down' key on my keyboard, I still see "Adding 15 points to the player's score" printed in the console. Because I set the input as handled in the grandparent node, I thought that it wouldn't propagate downward?

# Answer
> 4 votes
After looking some more into how Godot handles input(and events in general), I found that instead of events propagating from the root downward, they propagate upwards from the rightmost node of the rightmost branch.

Since events are handled in the order of \_input, \_input\_event, and then \_unhandled\_input, I just changed \_unhandled\_input in my GameScene to \_input.

---
Tags: godot
---


# Question
Title: Face culling all faces that cannot be seen
I'm working on a simple 3d game using the Processing Java environment. I want to optimise my code so I can draw many many 'objects' (the world is made up of many different shaped objects that live inside the volume of a cube) without the framerate dropping. How can I detect which faces cannot be seen and stop drawing them? I have tried this code:

```
pgl = (PJOGL) beginPGL();
gl = pgl.gl.getGL2ES2();
gl.glEnable(GL.GL_CULL_FACE);
gl.glCullFace(GL.GL_BACK);

```

which does do backface culling but it is not all that I want. I want to stop rendering *any* face that the camera cannot see, i.e. inside faces etc.

The code used to draw the objects (just a simple cube for testing) is as follows:

```
    noFill();
    noStroke();
    noSmooth();
    push();
    lights();
    translate(this.x * this.size, this.y * this.size, this.z * this.size);
    beginShape(QUADS);
    texture(this.texture_image);
    vertex(-this.size / 2, -this.size / 2, this.size / 2, 0, 0);
    vertex( this.size / 2, -this.size / 2, this.size / 2, this.size / 2, 0);
    vertex( this.size / 2, this.size / 2, this.size / 2, this.size / 2, this.size / 2);
    vertex(-this.size / 2, this.size / 2, this.size / 2, 0, this.size / 2);

    // -Z "back" face
    vertex( this.size / 2, -this.size / 2, -this.size / 2, 0, 0);
    vertex(-this.size / 2, -this.size / 2, -this.size / 2, this.size / 2, 0);
    vertex(-this.size / 2, this.size / 2, -this.size / 2, this.size / 2, this.size / 2);
    vertex( this.size / 2, this.size / 2, -this.size / 2, 0, this.size / 2);

    // +Y "bottom" face
    vertex(-this.size / 2, this.size / 2, this.size / 2, 0, 0);
    vertex( this.size / 2, this.size / 2, this.size / 2, this.size / 2, 0);
    vertex( this.size / 2, this.size / 2, -this.size / 2, this.size / 2, this.size / 2);
    vertex(-this.size / 2, this.size / 2, -this.size / 2, 0, this.size / 2);

    // -Y "top" face
    vertex(-this.size / 2, -this.size / 2, -this.size / 2, 0, 0);
    vertex( this.size / 2, -this.size / 2, -this.size / 2, this.size / 2, 0);
    vertex( this.size / 2, -this.size / 2, this.size / 2, this.size / 2, this.size / 2);
    vertex(-this.size / 2, -this.size / 2, this.size / 2, 0, this.size / 2);

    // +X "right" face
    vertex( this.size / 2, -this.size / 2, this.size / 2, 0, 0);
    vertex( this.size / 2, -this.size / 2, -this.size / 2, this.size / 2, 0);
    vertex( this.size / 2, this.size / 2, -this.size / 2, this.size / 2, this.size / 2);
    vertex( this.size / 2, this.size / 2, this.size / 2, 0, this.size / 2);

    // -X "left" face
    vertex(-this.size / 2, -this.size / 2, -this.size / 2, 0, 0);
    vertex(-this.size / 2, -this.size / 2, this.size / 2, this.size / 2, 0);
    vertex(-this.size / 2, this.size / 2, this.size / 2, this.size / 2, this.size / 2);
    vertex(-this.size / 2, this.size / 2, -this.size / 2, 0, this.size / 2);

    endShape();
    pop();

```

Sorry for the long code.

Thanks in advance.

# Answer
> 0 votes
It not always beneficial to cull absolutely everything, not even in voxel games. Loading new geometry or dealing with faces as separate objects can really cost a lot of computational power, especially given how 3 of those sides gets culled by backface culling automatically 100% of the time.

What you could do instead is to render only what's roughly in front of the player and rendering everything starting from the players position and going outward. That way the blocks will obstruct everything coming after them and depth culling will kick in reducing the time spent in the fragment shader to close to zero.

You can combine that with instanced rendering (and possibly geometry buffers) and you'll get a pretty fast system

---
Tags: java, 3d, camera, culling, processing
---


# Question
Title: Minecraft-Style Voxel Sunlight Algorithm
I'm implementing a pure Minecraft clone, and I want to implement sunlight. I have a basic sunlight algorithm working perfectly in 2D, and I understand how to scale it to 3D. But how do I make it so I don't have to recompute the entire sunlight every time I place a block?

Pseudocode, because the actual algorithm is not written very well :)

```
FUNC propogateSunlight(x,y,z):
    IF (x,y,z) is out of bounds then RETURN
    IF light_at(x,y,z) is <= 0 then RETURN

    # PROPOGATE
    IF light_can_spread(x,y-1,z) AND light_at(x,y-1,z)<light_at(x,y,z) then:
        set_light_at(x,y-1,z) to light_at(x,y,z)
        propogateSunlight(x,y-1,z)
    IF light_can_spread(x-1,y,z) AND light_at(x-1,y,z)<light_at(x,y,z) then:
        set_light_at(x-1,y,z) to light_at(x,y,z)-1
        propogateSunlight(x-1,y,z)
    *repeat above IF statement for (x-1,y,z), (x+1,y,z), (x,y,z-1), (x,y,z+1) and (x,y+1,z)

```

Then it sets the top layer to 16 (the max light level) and calls `propogateSunlight` on the top level.

This algorithm does what I want it to *PERFECTLY*. The only downside is that it is really really slow.

So what (psuedocode) algorithm is there to place / remove blocks (without transparency) that make it so I don't have to recalculate the entire world?

P.S. The coordinate system is standard 3d graphics, XZ is ground plane, +Y is up and -Y is down.

# Answer
> 4 votes
For each block that you visit as you're doing your light propagation, store an offset/direction to the brightest light shining onto it from a neighbour (eg. if a block is receiving a value of 5 from above and 4 from the left, its offset should point up). Do this for both empty cells and filled cells at the light's boundary.

Now, when you remove a block, you can propagate light again from this brightest neighbouring source, without recalculating the whole shebang.

When you place a block, you can inspect its neighbours to the sides and below. Any that were pointing to your now-occluded block as their brightest light source should search their immediate neighbours for a new light source, and update their brightness accordingly. If they get dimmer, then repeat, looking for neighbours that relied on *this* cell for their brightest light, and updating them in turn.

This keeps your lighting updates restricted to the "downstream" cone of light from the site you modified, pruning the edges where the lighting doesn't change due to occlusion / backup sources.

---

You can probably also make the initial light propagation faster by moving away from a recursive method that might touch the same cells many times, to one that processes the cells once each, in order. You could look at it as using Djikstra's algorithm to find the lowest-cost (least attenuation) path to each cell from the sun. Steps downward cost zero, steps sideways cost one, and the search bottoms-out at a light value of zero or on opaque cells.

You use a priority queue to handle the cells in order of brightness - so by the time you get to propagating light downward from a cell, you know you'll never have to do that a second time for that cell if a brighter light reaches it later in the algorithm: if there were a brighter source reaching this cell, it would have been evaluated already. In this form, the offset described above always points to the parent cell that last added/bumped this cell in the queue.

# Answer
> 1 votes
When you place/remove a block mark it and the surrounding blocks as dirty.

Every tick you compute `n` dirty block based on the neighbours.

Every time a light value changes in a block its neighbours get marked as dirty again.

This allows you to spread the work over time and the changes are localized.

However this does have the downside that darkness propagation is slow. Because you end up visiting each block that was at `max` up to `max` times until the light values stabilize.

```
FUNC propogateSunlight(x,y,z):
    IF (x,y,z) is out of bounds then RETURN
    IF light_at(x,y,z) is <= 0 then RETURN

    # PROPOGATE
    IF light_can_spread(x,y-1,z) AND light_at(x,y-1,z)<light_at(x,y,z) then:
        set_light_at(x,y-1,z) to light_at(x,y,z)
        SchedulePropogateSunlight(x,y-1,z)
    IF light_can_spread(x-1,y,z) AND light_at(x-1,y,z)<light_at(x,y,z) then:
        set_light_at(x-1,y,z) to light_at(x,y,z)-1
        SchedulePropogateSunlight(x-1,y,z)
    *repeat above IF statement for (x-1,y,z), (x+1,y,z), (x,y,z-1), (x,y,z+1) and (x,y+1,z)

FUNC SchedulePropogateSunlight(block):
    if lightQueue.contains(block) then:
       return
    lightQueue.add(block)

//call in main loop once
FUNC doPropagation():
    for 0...256 do:
        block = lightQueue.take()
        if block is null then:
            return
        propogateSunlight(block)

```

---
Tags: lighting, voxels
---


# Question
Title: Rotating objects in an random rotation around center point
I almost have what I'm looking for. Still trying to understand rotation and spawning of objects.

I have a ground field with a number of spawn points (and they are placed randomly in a circle). It's working quite well.

I have the issue tho, that I'm spawning them in an angle I'm not intending to and I have troubles finding the issue and understanding the math to it.

This is what it looks like:

I want the rocks to be spawned around the circle on the ground, not 90° to it.

I have the following code:

```
Vector3 RandomCircle(Vector3 center, float diameter) {
    float r = diameter / 2;
    float ang = Random.value * 360;
    Vector3 pos;
    pos.y = center.y + r * Mathf.Sin(ang * Mathf.Deg2Rad);
    pos.x = center.x + r * Mathf.Cos(ang * Mathf.Deg2Rad);
    pos.z = center.z;
    return pos;
}

```

# Answer
> 0 votes
Thanks again to @DMGregory, the answer as quite simple. I made an mistake and needed to include Y and Z.

with this I was able to get my wished result.

```
pos.z = center.y + r * Mathf.Sin(ang * Mathf.Deg2Rad);
pos.x = center.x + r * Mathf.Cos(ang * Mathf.Deg2Rad);
pos.y = center.z;

```

---
Tags: unity, rotation
---


# Question
Title: In Cricket games, how is the ball synced with batsman's shot animation? How does the ball hit right at the center of the bat? How does this work?
I've been trying to figure this out for quite some time now.

In Cricket games, when the bowler bowls, and batsman takes a shot, how does the ball sync with batsman's shot animation? For example, let's say the batsman hits a straight drive, how does the ball hit the bat perfectly?

Can anyone help me out with this?

I'm also curious about how in football games, the player animations sync with the football. How does the player's foot correctly hit the ball?

Thanks in advance.

# Answer
Found some useful info in this thread (works with Unity) - Manipulating an animation towards a target object (ie. The hand and arm lean towards the target)

One useful approach would be to use IK to target the bat to position of the ball and blend it with the shot animation.
> 1 votes

---
Tags: unity, physics, animation, unreal-4, animation-states
---


# Question
Title: How can I convert screen coordinates from a click to 2D scaled world coordinates?
I need a way to convert screen coordinates obtained from mouse clicks to world coordinates in my 2D game.

To create a zoom effect controlled by the user, before drawing a model I will scale all of it's points by a world scale value.

The screen origin (0,0) is at the top left corner while the world has it's center (0,0) at the center of the screen (width/2, height/2).

I need a function to convert the coords obtained by mouse clicks (screen coords) to the corresponding scaled-world coordinates, so that I can determine what world element is clicked by the user in this scaled world.

Any of my approaches worked as required and unfortunately none of the found solutions where aplicable to my case.

This is a very simple example JS Bin:

* Use the mouse wheel to zoom in/out
* Click on the screen to set a point

Thanks!

# Answer
You're almost there.

The theory: for each "transform" you apply to the world coordinates to turn them into screen coordinates, you need to *undo* each one of them.

You have three transforms.

1. The `ctx.translate(centerX, centerY)`. You correctly undo this transform with `const x = -centerX + coords.x; const y = -centerY + coords.y;`.
2. You've told the browser to scale the canvas output but not scale the input clicks. For now, take out the `width:100%; height:100%` on the canvas. Without that, if you don't use mousewheel to zoom, you will see that your code works correctly. (yay!)
3. But we still need to handle the mousewheel zoom: the `converted.x * worldScale, converted.y * worldScale`. You haven't undone this one. In the convert function, use `const x = (coords.x - centerX) / worldScale; const y = (coords.y - centerY) / worldScale;`

Here's a JS Bin: https://jsbin.com/nexitukime/1/edit?html,output

If you want to have the canvas sized to 100% you'll need to undo the browser scaling by using `getBoundingClientRect()` to find out how big the browser has made the output, and then undo that *first* before you run convert().
> 2 votes

---
Tags: javascript, html-canvas, coordinates, scale
---


title: Culling mask don't work

text:
# Question
Title: Culling mask don't work
I have the following setup: MainCamera render everything except ImageTurret layer. TurretCamera render only ImageTurret layer on a RawImage

My problem is: MainCamera render everything and TurretCamera render nothing TurretCamera render only if set to default layer.

# Answer
It seems I was changing Layers but not all the children layers
> -1 votes

---
Tags: unity, camera, culling, layers
---


title: OnMouseDown() execute only once

text:
# Question
Title: OnMouseDown() execute only once
I have the following OnMouseDown() function:

```
private void OnMouseDown()
{
    Debug.Log("This turret is: " + thisTurret.ToString());
    if (EventSystem.current.IsPointerOverGameObject())
    {
        return;
    }

    if (thisTurret != null)
    {
        buildManager.SelectTurret(thisTurret);
    }

```

which send to the following functions:

```
public void SelectTurret(GameObject turret)
{
    if(selectedTurret == turret)
    {
        Debug.Log("Selected turret is: " + selectedTurret.ToString());
        DeselectTurret(selectedTurret);
        return;
    }

    selectedTurret = turret;
    Debug.Log("Selected turret here is: " + selectedTurret.ToString());
    Debug.Log("Pasted turret here is: " + turret.ToString());
    if (oldSelectedTurret == null)
    {
        oldSelectedTurret = selectedTurret;
    }

    //Debug.Log("Selected turret is: " + selectedTurret.ToString());

    if (oldSelectedTurret != selectedTurret)
    {
        turretUI.Hide(oldSelectedTurret);

        //Debug.Log("Old in if Selected turret is: " + oldSelectedTurret.ToString());

        oldSelectedTurret = selectedTurret;
    }
    //Debug.Log("Current Selected turret is: " + selectedTurret.ToString());

    turretToBuild = null;

    turretUI.SetTarget(selectedTurret);
}

public void DeselectTurret(GameObject turret)
{
    if(turret != null)
    {
        Debug.Log("Turret to deselect is: " + turret.ToString());
        turretUI.Hide(turret);
        selectedTurret = null;
    }
    else
    {
        Debug.Log("Turret to deselect is null!");
    }
}

```

it should deselect the turret if clicked twice but instead it select the turret on first click and don't execute on second click

# Answer
> -1 votes
It seems I was changing Layers but not all the children layers

# Answer
> 0 votes
Since

```
if (EventSystem.current.IsPointerOverGameObject())
{
    return;
}

```

Returns true on second click. It returns and does not execute other part of the code.

```
if (thisTurret != null)
{
    buildManager.SelectTurret(thisTurret);
}

```

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


# Question
Title: Why table in libgdx game give wrong position
Can anybody guide me, I am creating a table in libgdx game on menu screen to set different buttons on my screen. here is the code for table draw

```
 table.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

```

and here is the code for background for this menu screen

```
batch.draw(bckTexture, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

```

My bcktexture image size is 600 by 400.

Now this table draws in the middle of the screen. I dont understand this why. it should be drawn by 0 , 0 corner and fill the whole screen. I have checked table by table.debug();

what I want is that the table should cover the whole screen so that I can adjust my buttons anywhere on the screen i want especially at the corners.

# Answer
> 0 votes
The `setBounds()` method comes from the `Actor` class, which the `Table` class subclasses. It is usually used for stuff like collision detection, but not setting the size of your actors.

In your case, you can go as simple as calling `table.setFillParent(true);` to have your table fill up the entire space in its parent (btw, are you adding it to a stage or something?)

Otherwise, use the `setSize()` and `setPosition()` methods to explicitly set size and position of your table inside its parent.

You might also want to check out this tutorial on using tables in libGDX: TableLayout.

Hope this helps.

# Answer
> 0 votes
Is your camera centered? If your camera is not centered, then it may be looking at (0, 0), which from your perspective is the center of the screen.

---
Tags: java, android, game-design, libgdx
---


title: How to animate infinite rotary movement

text:
# Question
Title: How to animate infinite rotary movement
I would like to add a chainsaw (or something similar to it... a rotary blade) to my game as a melee weapon. In fact, a rotary blade is a better example.

Would it be better to do it in blender somehow, using skeleton, or should I just create two parts (the handle and the blade) and then rotate it in UE4?

# Answer
> 1 votes
Obviously, there is no "better" in cases like this. Whatever works for you works. However, to convey the image of a running chainsaw, you might want to add a little shake to the engine. You could do all that by scaling the model slightly up and down based on time passed in unreal engine, but you'd have much more direct control over it if you rigged and animated the model. That way, you can see what happens the moment you edit it.

---
Tags: animation, blender, unreal-4
---


title: Comparing performance

text:
# Question
Title: Comparing performance
I wanted to create a portal. This portal looks like a semi-transparent texture rotating on a cylinder:

At first I created such a portal using a Particle System.

Then I realized that this might be an overkill and built another portal the following way:

I put a cylinder in the scene, put the texture on it and added a script that would rotate the cylinder.

The visual result of the 2 approaches (Particle System vs. Mesh approach) is perfectly the same.

Now I wanted to test which one performs better.

Am I right to assume that I should write a script which creates 10.000 portals of type A or B in the scene and have a look at some statistics (not sure yet which / where to find them), or is there anything more convinient to test performance?

Thank you!

# Answer
> 3 votes
Ideally the way you compare performance is to profile (with the appropriate tools, in this case probably both CPU and GPU-based profiling tools that may be available to you) the *actual scenarios* you're considering between, and compare the results.

There's a good chance that the impact either approach has on performance is so small, in this case, that it will be negligible within the larger actual scenario you're rendering. In those scenarios, it is typical to try to artificially increase the scale of the scenario to make the differences more pronounced -- in other words, to try to render tens of thousands of objects using both techniques and look at them side-by-side.

While this can help make the difference in techniques more pronounced, it can also make it *seem* more significant than it is. If tens of thousands of portals is a scenario you might expect to actually encounter in your game, by all means, profile for it. But if it's not, consider that perhaps all you need to do is determine if your technique is *good enough* at the expected scale of only *tens* (say) of portals in the scene.

As DMGregory said in the comments, don't get caught up in chasing micro-optimizations.

---
Tags: unity
---


title: DuDv Map has seams

text:
# Question
Title: DuDv Map has seams
I've made a dudvMap to give my water a ripple effect, however it is giving it a repeated look and I can see the areas where two textures on the water meet

It's a little hard to see here, but if you look closely in the bottom center you can see the area where the four textures meet. How would I fix this? I thought about loading a single texture across the entire watertile, however then the ripple effect would be extremely stretched.

Here is my fragmentShader at the suggestion of @DMGregor

```
#version 400 core

in vec4 clipSpace;
in vec2 textureCoords;
in vec3 toCameraVector;

out vec4 out_Color;

uniform sampler2D reflection;
uniform sampler2D refraction;
uniform sampler2D dudvMap;
uniform float moveFactor;

const float strength = 0.1;

void main(void) {

    vec2 ndc = (clipSpace.xy/clipSpace.w)/2.0 + 0.5;
    vec2 refractCoords = vec2(ndc.x, ndc.y);
    vec2 reflectCoords = vec2(ndc.x, -ndc.y);

    vec2 distortion1 = (texture(dudvMap, vec2(textureCoords.x + moveFactor, textureCoords.y)).rg * 2.0 - 1.0) * strength;

    refractCoords += distortion1;
    refractCoords = clamp(refractCoords, 0.001, 0.999);

    reflectCoords += distortion1;
    reflectCoords.x = clamp(reflectCoords.x, 0.001, 0.999);
    reflectCoords.y = clamp(reflectCoords.y, -0.999, -0.001);

    vec4 reflectColour = texture(reflection, reflectCoords);
    vec4 refractColour = texture(refraction, refractCoords);

    vec3 viewVector = normalize(toCameraVector);
    float refractiveFactor = dot(viewVector, vec3(0.0, 1.0, 0.0));

    out_Color = mix(reflectColour, refractColour, refractiveFactor);

}

```

The way I load the image is pretty standard as well:

```
    shader.start();
    shader.loadViewMatrix(camera);
    waveFactor += WAVE_SPEED * DisplayManager.getFrameTimeSeconds();
    waveFactor %= 1;
    shader.loadMoveFactor(waveFactor);
    GL30.glBindVertexArray(quad.getVaoID());
    GL20.glEnableVertexAttribArray(0);
    GL13.glActiveTexture(GL13.GL_TEXTURE0);
    GL11.glBindTexture(GL11.GL_TEXTURE_2D, fbos.getReflectionTexture());
    GL13.glActiveTexture(GL13.GL_TEXTURE1);
    GL11.glBindTexture(GL11.GL_TEXTURE_2D, fbos.getRefractionTexture());
    GL13.glActiveTexture(GL13.GL_TEXTURE2);
    GL11.glBindTexture(GL11.GL_TEXTURE_2D, dudvMap);

```

# Answer
Check that your move factor no more than 1.0. This because when you are trying to add distortion moving to texture coords for dudv map and your value is more than 1.0. I know where your code comes from. I'm using C++ and can't use this dynamic type conversion from float to int. `(waveFactor %=1)`

Try to use this:

```
moveFactor += 0.01 * deltaTime;
moveFactor = moveFactor - int(moveFactor);

```

That works fine for me and this issue no longer occurs.
> 0 votes

---
Tags: 3d, lwjgl, water, shading
---


title: LibGDX Button and Table Layout

text:
# Question
Title: LibGDX Button and Table Layout
I want to change the position of the Buttons inside a table, I tried setting their X and Y, or get their position when adding the Buttons on the Table, but it didn't work. It always aligns the button on the center.

Code:

```
    TextureAtlas ta = new TextureAtlas("Comecar.txt");
    final TextureAtlas.AtlasRegion as = ta.findRegion("comeca");
    final TextureAtlas.AtlasRegion as2 = ta.findRegion("comecaversao2");
    myTexRegionDrawable2 = new TextureRegionDrawable(as2);
    myTexRegionDrawable = new TextureRegionDrawable(as);
    myTexRegionDrawable.setMinHeight(300);
    myTexRegionDrawable.setMinWidth(260);
    myTexRegionDrawable2.setMinHeight(300);
    myTexRegionDrawable2.setMinWidth(260);
    b = new ImageButton(myTexRegionDrawable);
    op = new ImageButton(myTexRegionDrawable2);
    op.addListener(new ClickListener() {
        @Override
        public void clicked(InputEvent event, float x, float y) {
        }
    });
    b.addListener(new ClickListener() {
        @Override
        public void clicked(InputEvent event, float x, float y) {
            gdxGame.setScreen(new Janela2(gdxGame));
        }
    });
    t = new Table();
    t.add(b);//I tried setting the position here
    t.add(op);
    t.setFillParent(true);
    stage.addActor(t);
    Gdx.input.setInputProcessor(stage);
}

```

# Answer
When you add an actor inside a table, its position is always derived from the alignments of the table layout. The only solution to re-position the actor you might then get would be playing with its alignment and padding (which I believe does not suit the needs in many cases).
> 0 votes

---
Tags: libgdx
---


# Question
Title: Failed to get socket connection from UnityShaderCompiler.exe shader compiler! C:/Program Files/Unity/Editor/Data/Tools/UnityShaderCompiler.exe
When running a jenkins build using the Unity 3D plugin I get the following error repeatedly:

```
Failed to get socket connection from UnityShaderCompiler.exe shader compiler! C:/Program Files/Unity/Editor/Data/Tools/UnityShaderCompiler.exe

```

Not sure what's going on there, I tried giving a pass to the exe in windows firewall but it didn't help.

I have Unity 2017.1 installed...

# Answer
I also encountered this problem. For me it happened when I was running multiple Unity instances at once on a single Jenkins node what the Jenkins agent was running as Windows Service.

The problem turned out to be that the amount of Windows Desktop Heap available to services, as opposed to applications, was too small. I worked around it by increasing the Windows Desktop Heap size for services on my node, following the advice here -- https://stackoverflow.com/questions/17472389/how-to-increase-the-maximum-number-of-child-processes-that-can-be-spawned-by-a-w/17472390#17472390 (which I found here -- https://answers.unity.com/questions/1430683/failed-to-get-socket-connection-from-unityshaderco-2.html ).
> 4 votes

# Answer
Don't run the Jenkins agent using Windows Services. Instead, launch the agent manually using CLI.

This seems to be a bug with Unity, I've been unsuccessfully trying to create a small repro case that I could submit to Unity.
> 3 votes

# Answer
Another condition for this error message occurring repeatedly is when multiple Unity builds are running at the same time on Jenkins.

One possible workaround solution for this is to reduce the # of executors in Jenkins to 1 (from 2 in my case) so that only 1 Unity build can occur at a time.

---

Notes

* I have Unity 2017.3 installed, and I did not have this issue with Unity 5.6.
* To find the option, see `Manage Jenkins -> Configure System -> # of executors` in the Jenkins interface.)

Here is the error message with stack trace

```
Failed to get socket connection from UnityShaderCompiler.exe shader compiler! C:/Program Files/Unity/Editor/Data/Tools/UnityShaderCompiler.exe
UnityEditor.BuildPipeline:BuildPlayerInternalNoCheck(String[], String, String, BuildTargetGroup, BuildTarget, BuildOptions, Boolean)
UnityEditor.BuildPipeline:BuildPlayerInternal(String[], String, String, BuildTargetGroup, BuildTarget, BuildOptions) (at C:\buildslave\unity\build\artifacts\generated\common\editor\BuildPipelineBindings.gen.cs:337)
UnityEditor.BuildPipeline:BuildPlayer(String[], String, String, BuildTargetGroup, BuildTarget, BuildOptions) (at C:\buildslave\unity\build\artifacts\generated\common\editor\BuildPipelineBindings.gen.cs:234)
UnityEditor.BuildPipeline:BuildPlayer(BuildPlayerOptions) (at C:\buildslave\unity\build\artifacts\generated\common\editor\BuildPipelineBindings.gen.cs:212)
[+ call stack from my build script]

```
> 1 votes

---
Tags: unity, jenkins
---


# Question
Title: How to make a rigidbody come to rest faster
I'm trying to move around a 3D rigidbody in Unity 2018.1.0f2 Personal. I am using a C# script with the basic vector3 and velocity stuff from a YouTube video:

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

public class Player : MonoBehaviour {
    [SerializeField]
    private Rigidbody playerBody;

    private Vector3 inputVector;

    private float xMovement;
    private float zMovement;

    [SerializeField]
    private float playerSpeed;

    private float maxSpeed;

    // Use this for initialization
    void Start () {
        playerBody = GetComponent<Rigidbody>();
        playerSpeed = 1;

    }

    // Update is called once per frame
    void Update () {
        xMovement = Input.GetAxisRaw("Horizontal")* playerSpeed;
        zMovement = Input.GetAxisRaw("Vertical") * playerSpeed;

        inputVector = new Vector3(xMovement, playerBody.velocity.y, zMovement);
        playerBody.velocity = inputVector;
    }
}

```

It works great with a cube I put it on, except for this: if I move the rigidbody and then stop, it takes a long time for it rotate from go only one of the edges or corners just touching the ground (screenshot of what I mean, another screenshot) to resting flat. How can I make it fall back to stability faster?

# Answer
> 1 votes
From my understanding, it seems like you are updating the x and z rotation of the player inside the update method. so, it's setting the velocity each frame with the player movement. So stopping the player might causing that slow rigidbody.

So either you should manually handle the rotational movement along with the ground movement, or simply use Relative Torque to add rotational force to your player. Here is how my output looks like.

https://i.stack.imgur.com/mrODH.jpg

This is the change I made inside your code. I am not taking any consideration of y-axis movement and adding relative torque according to the input.

```
    inputVector = new Vector3(xMovement, 0, zMovement);
    playerBody.AddRelativeTorque(inputVector * playerSpeed,ForceMode.VelocityChange);

```

Hope that helps.

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


# Question
Title: Why does my Unity C# List not load from FromJSON()?
I'm using Unity and trying to load in data from JSON files. It finds the files, but no data comes through. when I do a Debug.Log(count) on it it tells me there are zero entries. But the same code for planets works fine. (I haven't got any code in the agent's field yet).

I even used a wrapper like you're supposed to. Here are the object and its wrapper:

```
    public class StructureList
    {
        public List<Structure> structures = new List<Structure>();
    }

    public class Structure
    {

        public int id;
        public string structureName;
        public int productionMaterials;
        public int productionPersonnel;
        public int defensiveShields;
        public int offensiveDamage;
        public int defensiveIonDamage;
        public int constructionShip;
        public int constructionStructure;
        public int constructionArmy;
        public int detectionFleet;
        public int detectionAgents;
        public string structureDescription;
        public int colonyId;
        public int costCrew;
        public int costMaterials;
    }

```

here's the json file:

```
{
  "structures": [
    {
      "id": 0,
      "structureName": "Factory",
      "productionMaterials": 5,
      "productionPersonnel": 0,
      "defensiveShields": 0,
      "offensiveDamage": 0,
      "defensiveIonDamage": 0,
      "constructionShip": 0,
      "constructionStructure": 0,
      "constructionArmy": 0,
      "detectionFleet": 0,
      "detectionAgents": 0,
      "structureDescription": "A basic factory that provides construction materials to the empire.",
      "costCrew": 100,
      "costMaterials": 200,
      "colonyId": 0
    },
    {
      "id": 1,
      "structureName": "Recruitment Center",
      "productionMaterials": 0,
      "productionPersonnel": 5,
      "defensiveShields": 0,
      "offensiveDamage": 0,
      "defensiveIonDamage": 0,
      "constructionShip": 0,
      "constructionStructure": 0,
      "constructionArmy": 0,
      "detectionFleet": 0,
      "detectionAgents": 0,
      "structureDescription": "A basic structure that recruits personnel for employ in the empire.",
      "costCrew": 200,
      "costMaterials": 100,
      "colonyId": 0
    },
    {
      "id": 2,
      "structureName": "Shield Generator",
      "productionMaterials": 0,
      "productionPersonnel": 0,
      "defensiveShields": 10,
      "offensiveDamage": 0,
      "defensiveIonDamage": 0,
      "constructionShip": 0,
      "constructionStructure": 0,
      "constructionArmy": 0,
      "detectionFleet": 0,
      "detectionAgents": 0,
      "structureDescription": "A planetary shield generator that will defend against orbital bombardment. Can defend against incursions if their are multiple.",
      "costCrew": 25,
      "costMaterials": 200,
      "colonyId": 0
    },
    {
      "id": 3,
      "structureName": "SOL Platform",
      "productionMaterials": 0,
      "productionPersonnel": 0,
      "defensiveShields": 0,
      "offensiveDamage": 10,
      "defensiveIonDamage": 0,
      "constructionShip": 0,
      "constructionStructure": 0,
      "constructionArmy": 0,
      "detectionFleet": 0,
      "detectionAgents": 0,
      "structureDescription": "A Surface to Orbit laser turret that fires at ships which come close enough for orbital bombardments.",
      "costCrew": 25,
      "costMaterials": 350,
      "colonyId": 0
    },
    {
      "id": 4,
      "structureName": "Ion Cannon",
      "productionMaterials": 0,
      "productionPersonnel": 0,
      "defensiveShields": 0,
      "offensiveDamage": 0,
      "defensiveIonDamage": 5,
      "constructionShip": 0,
      "constructionStructure": 0,
      "constructionArmy": 0,
      "detectionFleet": 0,
      "detectionAgents": 0,
      "structureDescription": "A low orbit station designed to build space worthy ships.",
      "costCrew": 25,
      "costMaterials": 250,
      "colonyId": 0
    },
    {
      "id": 5,
      "structureName": "Shipyard",
      "productionMaterials": 0,
      "productionPersonnel": 0,
      "defensiveShields": 0,
      "offensiveDamage": 0,
      "defensiveIonDamage": 0,
      "constructionShip": 10,
      "constructionStructure": 0,
      "constructionArmy": 0,
      "detectionFleet": 0,
      "detectionAgents": 0,
      "structureDescription": "A base of operations with construction crews for building other structures.",
      "costCrew": 500,
      "costMaterials": 250,
      "colonyId": 0
    },
    {
      "id": 6,
      "structureName": "Construction Yard",
      "productionMaterials": 0,
      "productionPersonnel": 0,
      "defensiveShields": 0,
      "offensiveDamage": 0,
      "defensiveIonDamage": 0,
      "constructionShip": 0,
      "constructionStructure": 10,
      "constructionArmy": 0,
      "detectionFleet": 0,
      "detectionAgents": 0,
      "structureDescription": "A training center that turns personnel into armies. Also, helps detect enemy agents.",
      "costCrew": 500,
      "costMaterials": 500,
      "colonyId": 0
    },
    {
      "id": 7,
      "structureName": "Barracks",
      "productionMaterials": 0,
      "productionPersonnel": 0,
      "defensiveShields": 0,
      "offensiveDamage": 0,
      "defensiveIonDamage": 0,
      "constructionShip": 0,
      "constructionStructure": 0,
      "constructionArmy": 5,
      "detectionFleet": 0,
      "detectionAgents": 5,
      "structureDescription": "An empty planet, devoid of life.",
      "costCrew": 250,
      "costMaterials": 500,
      "colonyId": 0
    },
    {
      "id": 8,
      "structureName": "Sensor Array",
      "productionMaterials": 0,
      "productionPersonnel": 0,
      "defensiveShields": 0,
      "offensiveDamage": 0,
      "defensiveIonDamage": 0,
      "constructionShip": 0,
      "constructionStructure": 0,
      "constructionArmy": 0,
      "detectionFleet": 10,
      "detectionAgents": 0,
      "structureDescription": "Detects fleets at a distance, incoming to the planet.",
      "costCrew": 10,
      "costMaterials": 500,
      "colonyId": 0
    },
    {
      "id": 9,
      "structureName": "Communications Array",
      "productionMaterials": 0,
      "productionPersonnel": 0,
      "defensiveShields": 0,
      "offensiveDamage": 0,
      "defensiveIonDamage": 0,
      "constructionShip": 0,
      "constructionStructure": 0,
      "constructionArmy": 0,
      "detectionFleet": 0,
      "detectionAgents": 10,
      "structureDescription": "Used to decrypt messages being sent out from the planet, in order to detect enemy agents.",
      "costCrew": 150,
      "costMaterials": 50,
      "colonyId": 0
    }
  ]
}

```

And here's my loading code:

        public static PlanetList planets;
        public static StructureList structures;
        public static AgentList agents;

        public static void LoadData()
        {
            string planetPath = Application.dataPath + "/Resources/PlanetDB.json";
            string structurePath = Application.dataPath + "/Resources/StructureDB.json";
            string agentPath = Application.dataPath + "/Resources/AgentDB.json";

            if (File.Exists(planetPath))
            {
                string planetsdataAsJson = File.ReadAllText(planetPath);
                planets = JsonUtility.FromJson<PlanetList>(planetsdataAsJson);
                Debug.Log("Planets Loaded: " + planets.planets.Count);
            }
            else
            {
                planets = new PlanetList();
                Debug.LogError("FAILED TO LOAD PLANETDATA");
            }

            if (File.Exists(structurePath))
            {
                string structuresdataAsJson = File.ReadAllText(structurePath);
                structures = JsonUtility.FromJson<StructureList>(structuresdataAsJson);
                Debug.Log("Structures Loaded: " + structures.structures.Count);
            }
            else
            {
                structures = new StructureList();
                Debug.LogError("FAILED TO LOAD STRUCUREDATA");
            }

            if (File.Exists(agentPath))
            {
                string agentsdataAsJson = File.ReadAllText(agentPath);
                agents = JsonUtility.FromJson<AgentList>(agentsdataAsJson);
                Debug.Log("Agents Loaded: " + agents.agents.Count);
            }
            else
            {
                agents = new AgentList();
                Debug.LogError("FAILED TO LOAD AGENTDATA");
            }
        }
```
</code></pre>

# Answer
You forgot to add `[Serializable]` attribute :)

From https://docs.unity3d.com/ScriptReference/JsonUtility.FromJson.html:

> It must be a plain class/struct marked with the Serializable attribute.

Add the attributes and it will deserialize:

```
[Serializable]
public class StructureList
{
    public List<Structure> structures = new List<Structure>();
}

[Serializable]
public class Structure
{
    public int id;
    public string structureName;
    public int productionMaterials;
    public int productionPersonnel;
    public int defensiveShields;
    public int offensiveDamage;
    public int defensiveIonDamage;
    public int constructionShip;
    public int constructionStructure;
    public int constructionArmy;
    public int detectionFleet;
    public int detectionAgents;
    public string structureDescription;
    public int colonyId;
    public int costCrew;
    public int costMaterials;
}

```
> 3 votes

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


title: How do I become a game publisher?

text:
# Question
Title: How do I become a game publisher?
I wonder how I can become a game publisher locally. For example, I know a Japanese game that I want to publish in India, where I live.

How do I acquire a license to do this? I tried emailing the Japanese game company, but they didn't reply. I also asked if they need to know my company size or credits in India before proceeding with a contract, but they also keep silent.

# Answer
First, you need to clarify what you mean by publish locally:

* What services are you providing to the license holder?
* Why should they choose you over others (possibly even themselves) for the services provided?
* What do you want in return for your services?

If you can't give clear, compelling answers to the above, you're unlikely to make progress.

Next, you need to contact the right party. The terms of contracts vary. Just because a given company published a game doesn't automatically mean they have the rights to negotiate publishing it in other markets. Unfortunately, because of all the possibilities, there's not a single absolute answer as to which party to contact & it make take some combination of investigation as well as trial & error. Also, check how you're making contact. It's not uncommon for things to be departmentalized. Do not assume that if you blindly send your request to the wrong department that someone will fix your mistake & forward it for you.

Finally, nobody has any obligation to agree with you, or even reply. Expect to get some rejection (possibly silent rejection) until you have a proven history of being able to deliver value to others. It may be in your interest to start small and/or locally to build up a good reputation before trying to land a larger and/or foreign title.
> 3 votes

# Answer
As I know from my personal experience, the most important thing is to prove devs that you are able to bring revenue and keep players happy.
> 0 votes

---
Tags: licensing, publishing
---


# Question
Title: How to stop Objects with Rigidbodies from explosion when dragging
I have a sequence of capsules linked with fixed join and each capsule have a `Rigidbody` and a cube collider (the picture bellow shows how it's look like)

and this is the drag script I applied on it

```
public class MouseDrag : MonoBehaviour
{
Vector3 screenPoint;
Vector3 offset;

bool dragging = false;

Rigidbody rigid;

void Awake()
{
    rigid = GetComponent<Rigidbody>();
}

void OnMouseDown()
{
    screenPoint = Camera.main.WorldToScreenPoint(transform.position);
    offset = transform.position - Camera.main.ScreenToWorldPoint(
        new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));

    dragging = true;
}

void OnMouseUp()
{
    dragging = false;
}

void FixedUpdate()
{
    if (dragging)
    {
        Vector3 point = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 dest = Camera.main.ScreenToWorldPoint(point) + offset;

        rigid.AddForce((dest - rigid.position) * 200f);
        rigid.velocity *= 0.8f;
    }
}}

```

it works but at some point of the drag all the capsules explode and all the other components do the same thing

after some research I found some people says that the `Rigidbody` did the problem but I couldn't understand why or how it did the problem ?

Here is a link to a small video of the problem : https://drive.google.com/file/d/1Ia3X356L\_VaIGIrDAdLyZHG9K5k71S1j/view?usp=sharing

# Answer
As can be seen in the video, the phenomenon appears when the dragged object gets far behind the dragging cursor.

This might be because the current code increases the force the further the cursor gets ahead of the object. So at some point it receives a really large amount of force, the joints break, and you have an object flying around like a bullet, crashing into other rigidbodies and causing the chain-reaction you see here.

To avoid this from happening, you might want to limit the maximum amount of dragging-force.

```
    const float MAX_DRAG_FORCE = 10.0f // adjust to taste - how high it should be depends on the scale of your simulation

    Vector3 point = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
    Vector3 dest = Camera.main.ScreenToWorldPoint(point) + offset;

    // calculate the force-vector
    Vector3 forceVector = dest - rigid.position;
    // reconstruct it from its direction and clamped magnitude:
    forceVector = forceVector.normalized * Mathf.Clamp(forceVector.magnitude, 0.0f, MAX_DRAG_FORCE);

    rigid.AddForce(forceVector * 200f);

```

I also omitted the `rigid.velocity *= 0.8f;` The documentation discourages you from changing the velocity because it "can result in unrealistic behaviour". Maybe this is part of what you are seeing here. If you don't want objects to slide around and slow down instead, increase the "Drag" value of the rigidbody.
> 0 votes

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


# Question
Title: Why Some objects or prefabs don't respond to mesh collider?
I imported some assets and, I used some prefabs from that assets. Some of them responds when I add the component of mesh collider to it and disable the ability of going through with it. But some of the is not is not. I can still go through them. Is it a good practice to add 3d cube and disable that or, is there any other way to disable of going through it?

# Answer
I remember having something like this happen to me as well.

> Is it a good practice to add 3d cube and disable that or, is there any other way to disable of going through it?

If it works, it works. But personally, I just manually add a primitive collider (box, sphere, cone etc) for simple meshes and a mesh collider (https://docs.unity3d.com/Manual/class-MeshCollider.html) if I have a complex mesh.

As for the meshes not responding to collision, try checking the static checkbox. If a game object is static, it will not move. See: https://docs.unity3d.com/Manual/StaticObjects.html
> 1 votes

# Answer
Following from @user1026622's answer. Mesh colliders do not collide with each other, unless the `convex` option is checked. This is fine for low poly models but not recommended for higher poly models.
> 1 votes

---
Tags: unity, collision-detection, level-design
---


# Question
Title: Displaying debug line in custom raytracer implementation
Not sure if I should post this here or on the Math forum, but I will try my luck.

Some background. I made my custom raytracer. The processing happens purely on the CPU for now, no GPU interaction whatsoever. It supports basic Phong shading and X levels of reflections.

I started fiddling with some ideas now and I realized that I need a way to display debug lines so that I could debug what I am doing, at least to some extent.

I thought of this solution: Debug line is a *constrained* plane, which means that it is basically a rectangle, with pixels having their normal always facing the camera. The line is defined by a start point, magnitude, direction, and thickness. Based on these properties I should be able to calculate everything I need to get it displayed.

Below is some pseudocode for checking if my ray is intersecting this debug line.

Defined in the line initialization are:

* **startPosition** (where the line starts)
* **magnitude** (lenght of the line)
* **direction** (line direction)
* **thickness** (thickness of the line)

Code:

```
function isIntersecting(_originRay, _rayOrigin)

    ray = _originRay.Normalize(); // Ray coming from the camera
    spreadVector = direction.Cross(ray).Normalize(); // Vector showing the line width direction
    lineNormal = ray * (-1); // Debug line pixel always faces the camera directly

    // Plane intersection
    denominator = ray.Dot(lineNormal);
    if (denominator > 0) // Plane not visible
        return false;

    hitDistance = (startPosition - _rayOrigin).Dot(lineNormal) / denominator;
    hitPosition = _rayOrigin + (ray * hitDistance); // Get the intersection point in 3D space

    widthVector = spreadVector  * thickness;
    hitPositionTranslated = hitPosition - startPosition;

    if (hitPositionTranslated.Dot(widthVector) > widthVector.Length() || hitPositionTranslated.Dot(widthVector) < 0) // Ray hitting the plane outside the constrained area
        return false;

    // Code for checking height here - Not putting it cause width is not working at first place

    return true;

```

I get this when using pretty great width (should be ~100px), but it is thin - looks like the algorithm is not constraining the width correctly:

I am obviously doing something wrong here. Any kind of help would be much appreciated!

# Answer
> 1 votes
Found the problem. The dot product is the length of the projected vector multiplied by the length of the vector we are projecting into. That means that I needed to divide the dot product result by the length of the width vector to actually have a valid check:

```
hitPositionTranslated.Dot(widthVector) / widthVector.Length()

```

---
Tags: c++, 3d, graphics, raytracing
---


# Question
Title: Is it legal to make a fan game but only publish the gameplay?
If I make a fan game that uses copyrighted material, sounds, dialogues etc. from other games but only ever upload the gameplay/walkthrough of the fangame to Youtube without publishing it anywhere else, can the copyright holder still sue me? I live in the EU. I don't want to make profit off of it, just showcase my work to people on Youtube. I would still be okay with the owners shutting my videos down but I don't want to possibly go to court with it. What should I do then? :/

# Answer
> 5 votes
Sound, art assets, writing, etc. used in games are all creative works.

When you create a work that uses those pieces as ingredients, it is a derivative work.

If you have not been granted a licence to use these ingredients to make derivative works, then this is copyright infringement.

It does not matter whether that work is a game, or a video, or a recorded playthrough of a game. It's still a derivative work using ingredients which you have no licence to use.

In some jurisdictions, there are carve-outs made for "fair use" for purposes such as parody or education. These exceptions generally do not include self-promotional purpose as you've described, so you would likely not be able to claim fair use for this case. It's also important to recognize that fair use is a defense, not an immunity: if someone pursues legal action against you, you could try to argue in a court of law that your work should be covered by fair use, but this can be a long and expensive process even if you win. It generally won't stop a hosting service from taking down your work in the meantime.

As in most things, your best bet here is to not steal things that do not belong to you.

If you want to show off your skills, make your own original content. Or, if that's outside your area of focus, use assets that you have licence to use that way: either free/public domain/Creative Commons assets that expressly allow derivative works in their licences, assets you've purchased the right to use in this way, or assets you've contracted & paid artists, writers, sound designers & musicians to create for you.

Most of us here (myself included) are not lawyers, and this is not legal advice. If you want to know whether you might be sued, consult a lawyer. But again, your best bet is to not steal from fellow game developers in the first place, especially if you want to make a good impression on peers & potential employers in the game industry.

# Answer
> 3 votes
The copyright holder *would* almost certainly go after you, and I feel fairly confident (even though I'm not a lawyer) that they would be well within their rights to do so: you're still distributing copyrighted material that you don't have a license for. You're still potentially infringing on their trademarks or trade dress. You're just doing it all in video form instead of something more interactive.

This is somewhat similar to how Nintendo (and potentially others) have gone after people who post "let's play" videos. Although potentially *worse* for you, since it provides documentation that you've created the game as well, which is a violation of copyright *even if* you never distribute it.

---
Tags: legal, copyright
---


# Question
Title: Does unity3d's 5 seconds' simulation correspond to 5 seconds in real-world?
How is time modelled in unity? Is it same as the time in real-world?

# Answer
> 2 votes
Unity's elapsed-time metrics, such as `deltaTime` and `fixedDeltaTime` are in actual real-world seconds.

However, it is possible to scale (or effectively pause) the underlying time metrics using `timeScale`, at which point the values reported by Unity will be different than real time according to the scaling specified. Other metrics, such as `realtimeSinceStartup` are not affected by adjusting the time scale.

---
Tags: unity, realtime
---