Guest User

PaintBrush.cs

a guest
Nov 7th, 2017
4,878
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class PaintBrush : MonoBehaviour
  6. {
  7. public int resolution = 512;
  8. Texture2D whiteMap;
  9. public float brushSize;
  10. public Texture2D brushTexture;
  11. Vector2 stored;
  12. public static Dictionary<Collider, RenderTexture> paintTextures = new Dictionary<Collider, RenderTexture>();
  13. void Start()
  14. {
  15. CreateClearTexture();// clear white texture to draw on
  16. }
  17.  
  18. void Update()
  19. {
  20.  
  21. Debug.DrawRay(transform.position, Vector3.down * 20f, Color.magenta);
  22. RaycastHit hit;
  23. if (Physics.Raycast(transform.position, Vector3.down, out hit))
  24. //if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit)) // delete previous and uncomment for mouse painting
  25. {
  26. Collider coll = hit.collider;
  27. if (coll != null)
  28. {
  29. if (!paintTextures.ContainsKey(coll)) // if there is already paint on the material, add to that
  30. {
  31. Renderer rend = hit.transform.GetComponent<Renderer>();
  32. paintTextures.Add(coll, getWhiteRT());
  33. rend.material.SetTexture("_PaintMap", paintTextures[coll]);
  34. }
  35. if (stored != hit.lightmapCoord) // stop drawing on the same point
  36. {
  37. stored = hit.lightmapCoord;
  38. Vector2 pixelUV = hit.lightmapCoord;
  39. pixelUV.y *= resolution;
  40. pixelUV.x *= resolution;
  41. DrawTexture(paintTextures[coll], pixelUV.x, pixelUV.y);
  42. }
  43. }
  44. }
  45. }
  46.  
  47. void DrawTexture(RenderTexture rt, float posX, float posY)
  48. {
  49.  
  50. RenderTexture.active = rt; // activate rendertexture for drawtexture;
  51. GL.PushMatrix(); // save matrixes
  52. GL.LoadPixelMatrix(0, resolution, resolution, 0); // setup matrix for correct size
  53.  
  54. // draw brushtexture
  55. Graphics.DrawTexture(new Rect(posX - brushTexture.width / brushSize, (rt.height - posY) - brushTexture.height / brushSize, brushTexture.width / (brushSize * 0.5f), brushTexture.height / (brushSize * 0.5f)), brushTexture);
  56. GL.PopMatrix();
  57. RenderTexture.active = null;// turn off rendertexture
  58.  
  59.  
  60. }
  61.  
  62. RenderTexture getWhiteRT()
  63. {
  64. RenderTexture rt = new RenderTexture(resolution, resolution, 32);
  65. Graphics.Blit(whiteMap, rt);
  66. return rt;
  67. }
  68.  
  69. void CreateClearTexture()
  70. {
  71. whiteMap = new Texture2D(1, 1);
  72. whiteMap.SetPixel(0, 0, Color.white);
  73. whiteMap.Apply();
  74. }
  75. }
RAW Paste Data