Advertisement
Guest User

Draw.cs

a guest
Dec 11th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.60 KB | None | 0 0
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3.  
  4. public class Draw : MonoBehaviour {
  5.  
  6.     public int distanceFromCamera;
  7.     public GameObject drawPrefab;
  8.  
  9.     private GameObject _clonedPrefab;
  10.     private LineRenderer _lineRender;
  11.     private List<Vector3> _positions = new List<Vector3>();
  12.  
  13.     private void Update() {
  14.         if (Input.GetMouseButtonDown(0)) {
  15.             DrawLineStart();
  16.         } else if (Input.GetMouseButton(0)) {
  17.             Vector3 newPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
  18.             if (Vector3.Distance(newPosition, _positions[_positions.Count - 1]) > .1f) {
  19.                 DrawLineUpdate(newPosition);
  20.             }
  21.         }
  22.     }
  23.  
  24.     private void DrawLineStart() {
  25.         _clonedPrefab = Instantiate(drawPrefab, Vector3.zero, Quaternion.identity) as GameObject;
  26.         _lineRender = _clonedPrefab.GetComponent<LineRenderer>();
  27.         _positions.Clear();
  28.  
  29.         _positions.Add(fixOffset(Camera.main.ScreenToWorldPoint(Input.mousePosition)));
  30.         _positions.Add(fixOffset(Camera.main.ScreenToWorldPoint(Input.mousePosition)));
  31.  
  32.         _lineRender.SetPosition(0, _positions[0]);
  33.         _lineRender.SetPosition(1, _positions[1]);
  34.     }
  35.  
  36.     private void DrawLineUpdate(Vector3 _newPosition) {
  37.         _positions.Add(fixOffset(_newPosition));
  38.         _lineRender.positionCount++;
  39.         _lineRender.SetPosition(_lineRender.positionCount - 1, _positions[_positions.Count-1]);
  40.     }
  41.  
  42.     private Vector3 fixOffset(Vector3 _newPosition) {
  43.         return new Vector3(_newPosition.x, _newPosition.y, distanceFromCamera);
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement