【发布时间】:2018-06-29 09:53:03
【问题描述】:
我编写了以下脚本,它创建线 LineRenderer 对象并模拟 Unity3d 中的基本“绘画”能力。这工作得很好,但是我似乎无法让它正确地渲染线条。哪个出现在前面,哪个出现在后面似乎是随机的。
例如:
在此图像中,线条按黑色、橙色、蓝色、黄色、红色、绿色的顺序绘制。但是,正如您所看到的,这不是它们呈现的顺序。
void Update ()
{
//Create new Line on left mouse click(down)
if(Input.GetButtonDown("Fire1"))
{
prevPos = Input.mousePosition;
points = 2;
//check if there is no line renderer created
if(line == null){
//create the line
createLine();
}
//get the mouse position
mousePos = Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x,
Input.mousePosition.y, Camera.main.nearClipPlane));
//set the start point and end point of the line renderer
line.SetPosition(0,mousePos);
line.SetPosition(1,mousePos);
}
//if line renderer exists and left mouse button is click exited (up)
else if(Input.GetButtonUp("Fire1") && line)
{
mousePos = Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x,
Input.mousePosition.y, Camera.main.nearClipPlane));
//set the end point of the line renderer to current mouse position
line.SetPosition(points-1,mousePos);
//set line as null once the line is created
line = null;
currLines++;
}
//if mouse button is held clicked and line exists
else if(Input.GetButton("Fire1") && line)
{
mousePos = Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x,
Input.mousePosition.y, Camera.main.nearClipPlane));
//set the end position as current position but dont set line as null as the mouse click is not exited
line.SetPosition(points-1, mousePos);
currPos = Input.mousePosition;
if (currPos != prevPos) {
prevPos = currPos;
points = points + 1;
line.SetVertexCount (points);
line.SetPosition(points-1, mousePos);
}
}
if (clearing) {
GameObject[] gameObjects = GameObject.FindGameObjectsWithTag ("lines");
for(var i = 0 ; i < gameObjects.Length ; i ++)
{
Destroy(gameObjects[i]);
}
}
}
//method to create line
private void createLine()
{
Material newm = new Material(Shader.Find("Unlit/Color"));
newm.SetColor("_Color", lineColor);
//create a new empty gameobject and line renderer component
line = new GameObject("Line"+currLines).AddComponent<LineRenderer>();
line.tag = "lines";
//assign the material to the line
line.material = newm;
//set the number of points to the line
line.SetVertexCount(2);
//set the width
line.SetWidth(((float)lineSize)/1000, ((float)lineSize)/1000);
//render line to the world origin and not to the object's position
line.useWorldSpace = true;
}
【问题讨论】: