Unity3D中LineRenderer的使用

原文地址:<Unity3D>Unity3D中LineRenderer的使用

LineRenderer线渲染器主要是用于在3D中渲染线段,虽然我们也可以使用GL图像库来渲染线段,但是使用LineRenderer我们可以对线段进行更多的操作,例如:设置颜色,宽度等。在这里要注意LineRenderer渲染出的线段的两个端点是3D世界中的点,即他是属于世界坐标(World Point)中的。


案例】根据鼠标左击的位置,来持续绘制线段

首先我们在场景中新建一个空的GameObject,将Script1脚本添加给他。


using UnityEngine;  
using System.Collections;  
  
public class Script1 : MonoBehaviour {  
    //LineRenderer  
    private LineRenderer lineRenderer;  
    //定义一个Vector3,用来存储鼠标点击的位置  
    private Vector3 position;  
    //用来索引端点  
    private int index = 0;  
    //端点数  
    private int LengthOfLineRenderer=0;  
  
    void Start()  
    {  
        //添加LineRenderer组件  
        lineRenderer = gameObject.AddComponent<LineRenderer>();  
        //设置材质  
        lineRenderer.material = new Material(Shader.Find("Particles/Additive"));  
        //设置颜色  
        lineRenderer.SetColors(Color.red, Color.yellow);  
        //设置宽度  
        lineRenderer.SetWidth(0.02f, 0.02f);
    }  
  
    void Update()  
    {    
       //鼠标左击  
        if (Input.GetMouseButtonDown(0))  
        {  
            //将鼠标点击的屏幕坐标转换为世界坐标,然后存储到position中  
            position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y,1.0f));   
            //端点数+1  
            LengthOfLineRenderer++;  
            //设置线段的端点数  
            lineRenderer.SetVertexCount(LengthOfLineRenderer);  
              
        }  
        //连续绘制线段  
        while (index < LengthOfLineRenderer)  
        {     
            //两点确定一条直线,所以我们依次绘制点就可以形成线段了  
            lineRenderer.SetPosition(index, position);  
            index++;  
        }   
    }  
  
    void OnGUI()  
    {            
        GUILayout.Label("当前鼠标X轴位置:" + Input.mousePosition.x);  
        GUILayout.Label("当前鼠标Y轴位置:" + Input.mousePosition.y);          
    }
}  

效果图:



在这里我提一下,如果我们将Input.GetMouseButtonDown(0)改为Input.GetMouseButton(0)会产生什么样的效果呢?那就是我们拖动鼠标就可以持续的渲染线段了。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值