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,到这里本教程就结束了