Edwarddv

Particle Explosions using Vertex Colours

Jul 25th, 2015
361
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class VertexColorParticles : MonoBehaviour {
  5.  
  6.     public int debrisAmount = 10;
  7.     public LayerMask layerMask;
  8.     public Transform debrisParticleTransform;
  9.     private ParticleSystem _debrisParticleSystem;
  10.  
  11. void Awake()
  12.     {
  13.         _debrisParticleSystem = debrisParticleTransform.GetComponent<ParticleSystem>();
  14.     }
  15.  
  16. public void CreateDebrisParticles(RaycastHit hit)
  17.     {
  18.  
  19.         debrisParticleTransform.position = hit.point;
  20.         debrisParticleTransform.rotation = Quaternion.LookRotation(hit.normal);
  21.         Color sampledColor = SampleColour(hit);
  22.         _debrisParticleSystem.startColor = sampledColor;
  23.         _debrisParticleSystem.Emit(debrisAmount);
  24.     }
  25.  
  26.  
  27. Color SampleColour(RaycastHit hit)
  28.     {
  29.         Transform objectHit = hit.transform;
  30.         Mesh _mesh = objectHit.GetComponent<MeshFilter>().mesh;
  31.  
  32.         if (_mesh != null)
  33.         {
  34.  
  35.             int[] triangles = _mesh.triangles;
  36.             Color[] hitColors = _mesh.colors;
  37.  
  38.             if (hitColors.Length != 0)
  39.             {
  40.                 //Vertex indices
  41.                 int t1 = triangles[(hit.triangleIndex*3) + 0];
  42.                 int t2 = triangles[(hit.triangleIndex*3) + 1];
  43.                 int t3 = triangles[(hit.triangleIndex*3) + 2];
  44.  
  45.                 //Colors
  46.                 Color c1 = hitColors[t1];
  47.                 Color c2 = hitColors[t2];
  48.                 Color c3 = hitColors[t3];
  49.  
  50.                 Vector3 b = hit.barycentricCoordinate;
  51.  
  52.                 var sampleColor = c1*b.x + c2*b.y + c3*b.z;
  53.  
  54.                 return sampleColor;
  55.             }
  56.         }
  57.         return Color.grey;
  58.  
  59.     }
  60.  
  61. void Update()
  62.     {
  63.         if (Input.GetMouseButtonDown(0))
  64.         {
  65.             RaycastHit hit;
  66.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  67.             if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask.value))
  68.             {
  69.                 CreateDebrisParticles(hit);
  70.             }
  71.  
  72.         }
  73.     }
  74.  
  75. }
Advertisement
Add Comment
Please, Sign In to add comment