Unity3D 使用LineRenderer制作畫板功能


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Painter : MonoBehaviour {
    public Color painterColor = Color.black;
    private LineRenderer currentLineRenderer;
    private int currentPoint = -1;
    private Vector3 lastPoint;
    void Update() {
        if (Input.GetMouseButtonUp(0)) {
            //鼠標抬起后,清除上一次的筆記記錄。
            currentLineRenderer = null;
            currentPoint = -1;
        }
        if (Input.GetMouseButton(0)) {
            //鼠標按下時,將鼠標位置轉換成世界坐標
            //SetZ()是我寫的擴展方法,用於為Vector2添加一個Z
            //如果Z不設置,默認為0,就會直接在相機位置創建,這樣你看不到的
            Vector3 point = Camera.main.ScreenToWorldPoint(Input.mousePosition.SetZ(1));
            //判斷現在是否有LineRenderer,配合鼠標抬起,可以再次下筆的時候新建一個畫筆
            if (!currentLineRenderer) {
                GameObject line = new GameObject("Line");
                currentLineRenderer = line.AddComponent<LineRenderer>();
                //給一個你喜歡的材質球
                currentLineRenderer.material = new Material(Shader.Find("Standard"));
                //設置你喜歡的寬度
                currentLineRenderer.startWidth = currentLineRenderer.endWidth = .02f;
                //設置你喜歡的顏色
                currentLineRenderer.material.SetColor("_Color", painterColor);
                //如果你不希望受燈照影響
                currentLineRenderer.material.SetColor("_EmissionColor", painterColor);
                //記得開啟自發光屬性,不然即使上一條代碼改了也沒用
                currentLineRenderer.material.EnableKeyword("_EMISSION");
                //LineRenderer默認會有一個點,在0,0,0位置,如果不把它清除,之后你畫的線段
                //末尾總會連接到0,0,0
                currentLineRenderer.positionCount = 0;
            }
            //如果鼠標停在一個地方,就沒必要一直加點了,提升效率
            if (lastPoint.NotEquals(point)) {
                //畫之前,先給LineRenderer擴容,它並不聰明
                currentLineRenderer.positionCount++;
                //把點給它,它自己會畫
                currentLineRenderer.SetPosition(++currentPoint, point);
                lastPoint = point;
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM