用unity的line renderer 組件畫個滑稽

Line Renderer組件是unity自帶的3d畫線組件,通過一個一個的點來在3d空間中畫出一條線。

第一步:

先建一個Quad組件,在3D Object裏面,然後調整一下座標,這樣背景就有了


第二步:

建一個管理畫線的GameObject,Creat Empty就ok,掛上控制畫線的腳本,這樣畫線控制器就寫好了(腳本後面再寫)


第三步:

做每條線的預製件,同上,Creat Empty就ok,加上Line Renderer組件,這樣就做好了


想要後面畫的線條好看一點可以加Material

右鍵Create,Material,然後掛上去


別忘記把做好的預製件拖到


第四步:

寫腳本控制畫線

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour {
    public float sizeOfFont;
    public GameObject linePrefab;
    List<GameObject> Lines;
    GameObject nowline;
	// Use this for initialization
	void Start () {
        Lines = new List<GameObject>();
    }
    IEnumerator Write()
    {
        while(true)
        {
            if(nowline!=null)
            {
                nowline.GetComponent<LineRenderer>().positionCount += 1;
                nowline.GetComponent<LineRenderer>().SetPosition(
                    nowline.GetComponent<LineRenderer>().positionCount - 1,
                    Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, sizeOfFont))
                    );
            }
            yield return new WaitForSeconds(0.01f);
        }
    }
    void write()
    {
        nowline.GetComponent<LineRenderer>().positionCount += 1;
        nowline.GetComponent<LineRenderer>().SetPosition(
            nowline.GetComponent<LineRenderer>().positionCount - 1,
            Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, sizeOfFont))
            );
    }
    // Update is called once per frame
    void creatNewLine()
    {
        nowline = Instantiate(linePrefab, transform.position, new Quaternion(), this.transform);
        Lines.Add(nowline);
        //設置顏色  
        nowline.GetComponent<LineRenderer>().startColor = Color.red;
        nowline.GetComponent<LineRenderer>().endColor = Color.blue;
        //設置寬度  
        //nowline.GetComponent<LineRenderer>().startWidth = 0.02f;
        //nowline.GetComponent<LineRenderer>().endWidth = 0.02f;
        nowline.GetComponent<LineRenderer>().positionCount = 0;
        //InvokeRepeating("write", 0, 0.01f);
        StartCoroutine("Write");
    }
	void Update () {
		if(Input.GetMouseButtonDown(0))
        {
            creatNewLine();
        }
        if (Input.GetMouseButtonDown(1))
        {
            if(Lines.Count>=1)
            {
                Destroy(Lines[Lines.Count - 1]);
                Lines.RemoveAt(Lines.Count - 1);
            }
        }
        if (Input.GetMouseButtonUp(0))
        {
            //CancelInvoke("write");
            StopCoroutine("Write");
        }
	}
}

左鍵按下開始畫線,左鍵彈起結束畫線,右鍵返回撤銷上一步畫的線條

想讓自己畫的線有粗有細怎麼辦,調


多加幾個點就可以讓你畫的線更加生動

ok,到這裏本教程就結束了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章