我仍然是团结的新手,如果这是一个非常明显的问题,我感到抱歉。实际上,我正在尝试构建一个游戏,其中一个细小的物体(下图中的白色棍子)试图接触一个球形物体(下图中的橙色物体)。红线,绿线,蓝线和黄线是从棍子顶部朝不同方向发射的射线。
主要目标是在球体上绘制黑色形状,以说明杆和球体之间的交点。为了更好地理解它,我们在下图中从顶视图的角度查看场景,以及摇杆能否正确完成工作的外观。
为此,我使用此代码绘制了射线投射的命中点,但由于rend.material.mainTexture
始终为null
,并且我不确定为什么,所以无法正常工作!
RaycastHit hit_down, hit_right, hit_forward, hit_left;
if (Physics.Raycast(stick.transform.position, stick.transform.TransformDirection(Vector3.down), out hit_down))
{
Debug.DrawRay(stick.transform.position, stick.transform.TransformDirection(Vector3.down) * hit_down.distance, Color.yellow);
Debug.Log("Point of contact down: " + hit_down.point + " on " + hit_down.collider.gameObject.tag);
if (hit_down.collider.gameObject.tag == "sphere")
{
Renderer rend = hit_down.transform.GetComponent<Renderer>();
MeshCollider meshCollider = hit_down.collider as MeshCollider;
Debug.Log(rend.material.mainTexture);
if (rend == null || rend.sharedMaterial == null || meshCollider == null)
return;
Texture2D tex = rend.material.mainTexture as Texture2D;
Vector2 pixelUV = hit_down.textureCoord;
pixelUV.x *= tex.width;
pixelUV.y *= tex.height;
tex.SetPixel((int)pixelUV.x, (int)pixelUV.y, Color.black);
tex.Apply();
}
}
最后一个问题,这是实现我的目标的正确方法吗?还有其他更有效的方法来完成此任务吗?
谢谢。
答案 0 :(得分:0)
问题可能出在Renderer rend = hit_down.transform.GetComponent<Renderer>();
由于rend.material.mainTexture
返回null
,因此看来rend
本身实际上是null
。这可能是由于您尝试获取的Renderer
类型引起的。
您可能想尝试使用Renderer rend = hit_down.transform.GetComponent<LineRenderer>();
。其他一切都应该按预期工作