Unity3d LineRenderer画线
1、 画多条线
画多条线需要在场景中放置多个GameObject,因为一个GameObject只能添加一个LineRenderer Component。
2、 线段样式
线段的样式由LineRenderer组件的材质控制
3、 坐标系
LineRenderer使用了2种坐标系:World和Location。在设置目标点的时候需要注意你使用的坐标系是哪一种。
Location:
transform.LookAt(rh.point); //GameObject始终面对目标点
lineRenderer = (LineRenderer)gameObject.GetComponent ("LineRenderer"); lineRenderer.useWorldSpace=false; lineRenderer.SetWidth(0.1f,0.1f); Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if(Physics.Raycast(ray,out rh)){ lineRenderer.SetPosition(0, Vector3.forward*rh.distance);//方向*距离,典型的Location坐标系用法 }
World:
void Start () { gameObject.SetActive(false); lr = gameObject.GetComponent(typeof(LineRenderer)) as LineRenderer; lr.SetWidth(0.1f,0.1f); } // Update is called once per frame void Update () { if(Input.GetMouseButtonUp(0)){ //Get click position Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition); lr.SetVertexCount(lineSeg+1); if(Physics.Raycast(ray,out rh)){ pointPos.Add(DrawLine(rh)); } } if(Input.GetMouseButtonUp(1)){ //destroy point DestroyLine(); } } GameObject DrawLine(RaycastHit pointPos){ //Display point GameObject gb_pointer = GameObject.Instantiate(pointer) as GameObject; gb_pointer.transform.position =pointPos.point + (transform.position - pointPos.point) * 0.01f; gb_pointer.transform.rotation = Quaternion.LookRotation (pointPos.normal, Camera.mainCamera.transform.up); Vector3 laserpos = new Vector3(); laserpos.x= 90.0f; laserpos.y= gb_pointer.transform.position.y; laserpos.z= gb_pointer.transform.position.z; gb_pointer.transform.eulerAngles = laserpos; lr.SetPosition(lineSeg,pointPos.point); //设置目标点的坐标,使用的是world坐标系 lineSeg++; return gb_pointer; } void DestroyLine(){ int arrayLength = pointPos.Count; if(arrayLength > 0){ GameObject.Destroy(pointPos[arrayLength-1]); pointPos.RemoveAt(arrayLength-1); lr.SetVertexCount(--lineSeg); } }