1. 程式人生 > 其它 >Unity3D關於兩個物體直接用圓柱進行連線畫線(簡單畫線連線)

Unity3D關於兩個物體直接用圓柱進行連線畫線(簡單畫線連線)

最近做的東西需要用圓柱畫線,網上找了些,沒找到合適的,所以自己簡單寫了一個。

這個函式只需要輸入起始點和終點即可,材質可以自己調整

void DrawLS(GameObject startP, GameObject finalP)
    {
        Vector3 rightPosition = (startP.transform.position + finalP.transform.position) / 2;
        Vector3 rightRotation = finalP.transform.position - startP.transform.position;
        float HalfLength = Vector3.Distance(startP.transform.position, finalP.transform.position) / 2;
        float LThickness = 0.1f;//線的粗細
 
        //建立圓柱體
        GameObject MyLine = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
        MyLine.gameObject.transform.parent = transform;
        MyLine.transform.position = rightPosition;   
        MyLine.transform.rotation = Quaternion.FromToRotation(Vector3.up, rightRotation);
        MyLine.transform.localScale = new Vector3(LThickness, HalfLength, LThickness);
 
        //這裡可以設定材質,具體自己設定
        //MyLine.GetComponent<MeshRenderer>().material = GetComponent<MeshRenderer>().material;
    }