關於用LineRenderer實現畫圖功能

關於用LineRenderer實現畫圖功能

// A code block
var foo = 'bar';
// An highlighted block
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    private LineRenderer currentLine;
    public Material lineMaterial;
    private float paintSize = 0.4f;
    private Color paintColor = Color.blue;
    private List<Vector3> positions = new List<Vector3>();
    private bool isMouseDown;
    private Vector3 lastMousePosition = Vector3.zero;
    private float lineDistance = 0.02f;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            GameObject go = new GameObject();
            go.transform.SetParent(this.transform);
            currentLine = go.AddComponent<LineRenderer>();
            currentLine.material = lineMaterial;
            currentLine.startWidth = paintSize;
            currentLine.endWidth = paintSize;
            currentLine.startColor = paintColor;
            currentLine.endColor = paintColor;
            currentLine.numCornerVertices = 5;
            currentLine.numCapVertices = 5;
            Vector3 position = GetMousePoint();
            AddPosition(position);
            isMouseDown = true;
            lineDistance+=0.02f;
        }
        if (isMouseDown)
        {
            Vector3 position = GetMousePoint();
            if (Vector3.Distance(position,lastMousePosition)> 0.1f)
            {
                 AddPosition(position);
            }
           
        }
        if (Input.GetMouseButtonUp(0))
        {
            currentLine = null;
            positions.Clear();
            isMouseDown = false;
        }
    }
    Vector3 GetMousePoint()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        bool isCollider = Physics.Raycast(ray,out hit);
        if (isCollider)
        {
            return hit.point;
        }
        return Vector3.zero;
    }
    void AddPosition(Vector3 position)
    {
        position.z -= lineDistance;
        positions.Add(position);
        currentLine.positionCount = positions.Count;
        currentLine.SetPositions(positions.ToArray());
        lastMousePosition = position;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章