选择球体上的像素坐标



我正在尝试获取球体上单击的像素位置。我使用了以下代码:

if (Input.GetMouseButtonUp(0))
{
RaycastHit hit;
if (!Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
{
return;
}
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.DrawRay(ray.origin, ray.direction * 50000000, Color.red, 100f);
Renderer renderer = hit.transform.GetComponent<Renderer>();
MeshCollider meshCollider = hit.collider as MeshCollider;
if(renderer == null || renderer.sharedMaterial == null || renderer.sharedMaterial.mainTexture == null || meshCollider == null)
{
return;
}
Texture2D tex = renderer.material.mainTexture as Texture2D;
Vector2 pixelLocation = hit.textureCoord;
pixelLocation.x *= tex.width;
pixelLocation.y *= tex.height;
//This line simply recolours the pixel at the above location to red.
generator.DebugColorPixel((int)pixelLocation.x, (int)pixelLocation.y);
}

我遇到的问题是我在球体对象上也有以下脚本

void Update()
{
if (rotate)
{
transform.Rotate(Vector3.up, RotationSpeed * Time.deltaTime);
}
}
private void OnMouseEnter()
{
rotate = false;
}
private void OnMouseExit()
{
rotate = true;
}

问题是,如果允许球体在单击之前在任意点旋转(例如,旋转速度大于 0(,则从 hit.textureCoord 返回的坐标是无辜的。它们似乎沿 x 轴偏移。如果不允许球体旋转,则会正确返回坐标。使用调试光线,我可以看到光线投射命中的正确位置,但重新着色的像素不是光线投射命中的位置。

我对导致这种情况的原因感到困惑。

编辑: 根据要求,重新颜色代码为:

Texture2D tex = (Texture2D)Sphere.materials[0].mainTexture;
tex.SetPixel(x, y, Color.red);
tex.Apply();

为什么在光线投射命中时避免旋转:

if (Input.GetMouseButtonUp(0))
{
RaycastHit hit;
if (!Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
{
return;
}
rotate = false;
//do something with the pixel

rotate = true;
}

好的,原来这是我自己该死的错。球体是一个空游戏对象的子对象,由于某种未知原因,我过去曾将其缩放为 2,2,1,这导致球体形状错误,从而导致这些问题!

最新更新