[英]How to draw latitude/longitude lines on the surface of a Sphere in Unity 3D?
我是Unity 3D的初學者。 我正在嘗試使用Unity 3D創建一個地球儀,如下所示。 我在場景上創建了一個Sphere游戲對象並將半徑設置為640.然后,我想在C#腳本中在此Sphere的表面上繪制緯度/經度線(每10度)。
我試圖通過使用LineRender繪制每個緯度/長線,但沒有得到它的工作。 我的代碼:
public class EarthController : MonoBehaviour {
private float _radius = 0;
// Use this for initialization
void Start () {
_radius = gameObject.transform.localScale.x;
DrawLatLongLines();
}
// Update is called once per frame
void Update()
{
}
private void DrawLatLongLines()
{
float thetaStep = 0.0001F;
int size = (int)((2.0 * Mathf.PI) / thetaStep);
// draw lat lines
for (int latDeg = 0; latDeg < 90; latDeg += 10)
{
// throw error here.
// seems I cannot add more than one component per type
LineRenderer latLineNorth = gameObject.AddComponent<LineRenderer>();
latLineNorth.startColor = new Color(255, 0, 0);
latLineNorth.endColor = latLineNorth.startColor;
latLineNorth.startWidth = 0.2F;
latLineNorth.endWidth = 0.2F;
latLineNorth.positionCount = size;
LineRenderer latLineSouth = Object.Instantiate<LineRenderer>(latLineNorth);
float theta = 0;
var r = _radius * Mathf.Cos(Mathf.Deg2Rad * latDeg);
var z = _radius * Mathf.Sin(Mathf.Deg2Rad * latDeg);
for (int i = 0; i < size; i++)
{
var x = r * Mathf.Sin(theta);
var y = r * Mathf.Cos(theta);
Vector3 pos = new Vector3(x, y, z);
latLineNorth.SetPosition(i, pos);
pos.z = -z;
latLineSouth.SetPosition(i, pos);
theta += thetaStep;
}
}
}
}
這樣做的正確方法是什么?
我不想寫自定義着色器(如果可能的話),因為我對它一無所知。
自定義3d對象外觀的常用方法是使用着色器。
在您的情況下,您需要一個線框着色器,如果您想控制線數,那么您可能需要自己編寫。
另一種解決方案是使用紋理。 在統一中,您將擁有許多將在對象上應用紋理的默認材質。 您可以應用包含線條的圖像紋理。
如果您不想要紋理而只需要線條,則可以使用線條渲染器。 LineRenderer不需要3D對象。 你只要給它一些點,它就會用一條線將它們聯系起來。 我將如何做到這一點:
如果您的問題是“圓的等式是什么,那么我可以找到正確的x和y坐標?” 這是一個計算x和y坐標的簡短想法
for(int i =0; i< nbPointsOnTheCircle; ++i)
{
var x = Mathf.Cos(nbPointsOnTheCircle / 360);
var y = Mathf.Sin(nbPointsOnTheCircle / 360);
}
如果您的問題是“如何使用Unity動態分配線條渲染器上的點?” 這是一個簡短的例子:
public class Circle : MonoBehavior
{
private void Start()
{
Vector3[] circlePoints = computePoints(); // a function that compute points of a circle
var lineRenderer = GetComponent<LineRenderer>();
linerenderer.Positions = circlePoints;
}
}
編輯
每個對象只能有一個。 這就是上面的例子只繪制一個圓圈的原因。 你已經有一個地球控制器,但是這個控制器不能為它自己添加很多LineRenderes。 相反,我們的想法是地球對象有一個腳本,可以執行以下操作:
private void Start()
{
for(int i=0; i<nbLines;++i)
{
GameObject go = new GameObject();
go.AddComponent<LineRenderer>();
go.AddCOmponent<Circle>();
go.transform.SetParent = transform;
go.name = "Circle" + i;
}
}
然后,您將看到在場景中創建的多個對象,每個對象只有一個LineRenderer和一個Circle組件
從那里你應該能夠做你想要的(例如,將參數傳遞給Circle,這樣每個圓圈都有點不同)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.