Unity3D中Vector3方向向量Dir不更新:x/y/z打印正常但Dir恒为(0,0,-1)
球面扫描方向向量Dir异常问题
问题描述
我已经被这个问题困扰许久,注释掉的代码部分可直接忽略(并非问题根源)。我计划实现360度经度、180度纬度的方位扫描,后续执行射线检测逻辑,但目前方向向量(即代码中的Dir)始终卡在(0, 0, -1)。我单独校验过x、y、z的计算输出都是正常的,完全不清楚问题出在哪里,相关代码如下:
{ 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()); }
问题定位与解决方案
- 核心原因:你查看
Dir值的时机错误,并非循环内Dir一直卡在(0,0,-1)- 你的外层循环i遍历范围为0~1079,最后一次循环时i=1079,计算出的
theta约为π弧度(180度)。代入公式可得Sin(theta)≈0、Cos(theta)≈-1,因此x≈0、y≈0、z≈-1,Dir最终就是(0,0,-1) - 你单独校验x/y/z输出正常,说明循环内每次赋值
Dir都是正确的,只是你在整个嵌套循环执行完毕后才读取Dir的值,自然只能看到最后一次循环的结果
- 你的外层循环i遍历范围为0~1079,最后一次循环时i=1079,计算出的
- 验证方法
- 不要在循环结束后查看
Dir,直接在Dir = new Vector3(x, y, z)的下一行打断点,或把Log内容改为Debug.Log(Dir),就能看到循环内Dir是正常变化的 - 注释掉循环内的
Debug.Log,2160*1080=233万次日志输出会直接拖垮Unity编辑器
- 不要在循环结束后查看
- 全景扫描适配优化
当前代码的球面坐标以z轴为朝向、y轴为水平方向,不符合常规的上下为y轴的扫描逻辑,可调整转换公式为:
调整后扫描方向会覆盖完整的上下、水平全景,适配后续射线检测的使用逻辑// theta范围0~π(对应上下180度),phi范围0~2π(对应水平360度) float y = Mathf.Cos(theta); float horizontalRadius = Mathf.Sin(theta); float x = horizontalRadius * Mathf.Cos(phi); float z = horizontalRadius * Mathf.Sin(phi); Dir = new Vector3(x, y, z);
内容的提问来源于stack exchange,提问作者Khizar Shakoor
相关产品推荐
相关产品推荐

