Search code examples
loopsunity-game-enginevectorraycastingspherical-coordinate

Why is Vector3 not updating Unity3d


I have been losing my sanity on this for a while now. Just disregard the part which is commented out (Not the problem). I am trying to do a 360 degree longitude and 180 degree longitude sweep and then raycast. But apparently the direction vector (Dir in this case) is stuck at (0, 0, -1). I checked the x y and z values and they are working fine. I have no idea now what is wrong. Please answer before I kill myself. sigh

    {
        Vector3 Dir = new Vector3(0.0f, 0.0f, 0.0f);
        Output = new Texture2D(2160, 1080);
        for (int i = 0; i < 1080; i++)
        {
            float theta = (Mathf.Deg2Rad * i * 1.0f) / 6.0f;
            for (int j = 0; j < 2160; j++)
            {
                float phi = (Mathf.Deg2Rad * j) / 6.0f;
                float x = Mathf.Sin(theta) * Mathf.Cos(phi);
                float y = Mathf.Sin(theta) * Mathf.Sin(phi);
                float z = Mathf.Cos(theta);
                Dir = new Vector3(x, y, z);
                Debug.Log(x + " " + y + " " + z);
                /* RaycastHit raycastHit;
                if (Physics.Raycast(transform.position, Dir, out raycastHit))
                {
                    Renderer rend = raycastHit.transform.GetComponent<MeshRenderer>();
                    Texture2D tex = rend.material.mainTexture as Texture2D;
                    Vector2 pCoord = raycastHit.textureCoord;
                    pCoord.x *= tex.width;
                    pCoord.y *= tex.height;
                    Color color = tex.GetPixel((int)(pCoord.x * rend.material.mainTextureScale.x), (int)(pCoord.y * rend.material.mainTextureScale.y));
                    Output.SetPixel(j, i, color);
                    Debug.Log("Ray hit an object! @  theta " + i.ToString() + " phi " + j.ToString() + " Color: " + color.ToString() + "Hit Coordinate x: " + pCoord.x + " y: " + pCoord.y);
                }
                */
            }
        }
        //System.IO.File.WriteAllBytes("D:\\FYProject\\WebcamSnaps\\" + naming + ".png", Output.EncodeToPNG());
    }

Solution

  • In one of your comments, you stated "I am getting nothing other than (0,0,-1) in any iteration."

    Your code has an external loop with an iteration factor of 1080. You inner loop has an iteration factor of 2160. In total, your combined loops produce 2,332,800 output values. I do not believe you verified the output of over two million debug statements. I think you checked the last few dozen values, saw the same output over and over again, and assumed that pattern continued all the way up the chain. That was your first mistake.

    Your second mistake was wasting several hours assuming a formatting feature was a bug.

    Vector3.ToString() rounds its output to one digit after the decimal. If you print the components individually, they'll show what you'd expect.

    You have my sympathies.