Unity3D开发之利用LineRenderer画曲线

using UnityEngine;

using System.Collections;

using System.Collections.Generic;



public class LinearDrawLine: MonoBehaviour {

	private int pointCnt = 0;
	public Color c1 = Color.red;
	public Color c2 = Color.blue;
	private LineRenderer lineRenderer;

	private Vector3 screenPoint;
	private Vector3 scanPos;
	private Vector3 first_pos = Vector3.zero;

    void Start () {
		 scanPos = gameObject.transform.position;

		 lineRenderer = (LineRenderer)gameObject.GetComponent("LineRenderer");
		 lineRenderer.material = new Material (Shader.Find("Particles/Additive"));
	     lineRenderer.SetColors(c1, c2);
	     lineRenderer.SetWidth(0.02F, 0.02F);
	     lineRenderer.SetVertexCount(0); 		 
	}
   
	void Update()
	{
	}
	
	void OnMouseDown(){
		Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
		screenPoint = Camera.main.WorldToScreenPoint(scanPos);
		Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
	 	Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint);
		pointCnt = 0;
		DrawRenderLine(lineRenderer, curPosition);
		first_pos = curPosition;
	}
	
	void OnMouseDrag(){
		iTween.ScaleFrom(gameObject,iTween.Hash("x",2,"y",2,"z",2,"time",.1,"easetype","linear"));
		Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
	 	Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint);
		DrawRenderLine(lineRenderer, curPosition);
	}
	
	void DrawRenderLine(LineRenderer line, Vector3 vect3){
		if((Mathf.Abs(first_pos.x - vect3.x) < 0.1) && (Mathf.Abs(first_pos.y - vect3.y) < 0.1))
			return;
		first_pos = vect3;
        line.SetVertexCount(++pointCnt);
        line.SetPosition(pointCnt-1, vect3);
		print("new point: "+vect3+"+"+pointCnt);
	}

}


这种方式相比于GL方式来说,它不需要添加到相机中,可以是点击某个物品来画图。

可以直接把这个脚本拉到物品上面就可以用了。

你可能感兴趣的:(unity3d)