MeshTool.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. // Manipulation tool for displacing the vertices in a list of meshes
  4. public class MeshTool : MonoBehaviour
  5. {
  6. public enum ExtrudeMethod
  7. {
  8. Vertical,
  9. MeshNormal
  10. }
  11. public List<MeshFilter> m_Filters = new List<MeshFilter>();
  12. public float m_Radius = 1.5f;
  13. public float m_Power = 2.0f;
  14. public ExtrudeMethod m_Method = ExtrudeMethod.Vertical;
  15. RaycastHit m_HitInfo = new RaycastHit();
  16. void Start()
  17. {
  18. Cursor.lockState = CursorLockMode.Locked;
  19. Cursor.visible = false;
  20. }
  21. void Update()
  22. {
  23. var ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);
  24. if (Physics.Raycast(ray.origin, ray.direction, out m_HitInfo))
  25. {
  26. Debug.DrawRay(m_HitInfo.point, m_HitInfo.normal, Color.red);
  27. Vector3 displacement = (m_Method == ExtrudeMethod.Vertical) ? Vector3.up : m_HitInfo.normal;
  28. if (Input.GetMouseButton(0) || (Input.GetKey(KeyCode.Space) && !Input.GetKey(KeyCode.LeftShift)))
  29. ModifyMesh(m_Power * displacement, m_HitInfo.point);
  30. if (Input.GetMouseButton(1) || (Input.GetKey(KeyCode.Space) && Input.GetKey(KeyCode.LeftShift)))
  31. ModifyMesh(-m_Power * displacement, m_HitInfo.point);
  32. }
  33. }
  34. void ModifyMesh(Vector3 displacement, Vector3 center)
  35. {
  36. foreach (var filter in m_Filters)
  37. {
  38. Mesh mesh = filter.mesh;
  39. Vector3[] vertices = mesh.vertices;
  40. for (int i = 0; i < vertices.Length; ++i)
  41. {
  42. Vector3 v = filter.transform.TransformPoint(vertices[i]);
  43. vertices[i] = vertices[i] + displacement * Gaussian(v, center, m_Radius);
  44. }
  45. mesh.vertices = vertices;
  46. mesh.RecalculateBounds();
  47. var col = filter.GetComponent<MeshCollider>();
  48. if (col != null)
  49. {
  50. var colliMesh = new Mesh();
  51. colliMesh.vertices = mesh.vertices;
  52. colliMesh.triangles = mesh.triangles;
  53. col.sharedMesh = colliMesh;
  54. }
  55. }
  56. }
  57. static float Gaussian(Vector3 pos, Vector3 mean, float dev)
  58. {
  59. float x = pos.x - mean.x;
  60. float y = pos.y - mean.y;
  61. float z = pos.z - mean.z;
  62. float n = 1.0f / (2.0f * Mathf.PI * dev * dev);
  63. return n * Mathf.Pow(2.718281828f, -(x * x + y * y + z * z) / (2.0f * dev * dev));
  64. }
  65. }